Debian Codegraph @

gcc/config/nvptx/nvptx.cc

raw
1 /* Target code for NVPTX.
2 Copyright (C) 2014-2025 Free Software Foundation, Inc.
3 Contributed by Bernd Schmidt <[email protected]>
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published
9 by the Free Software Foundation; either version 3, or (at your
10 option) any later version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
15 License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
20
21 #define IN_TARGET_CODE 1
22
23 #include "config.h"
24 #include <sstream>
25 #include "system.h"
26 #include "coretypes.h"
27 #include "backend.h"
28 #include "target.h"
29 #include "rtl.h"
30 #include "tree.h"
31 #include "cfghooks.h"
32 #include "df.h"
33 #include "memmodel.h"
34 #include "tm_p.h"
35 #include "expmed.h"
36 #include "optabs.h"
37 #include "regs.h"
38 #include "emit-rtl.h"
39 #include "recog.h"
40 #include "diagnostic.h"
41 #include "alias.h"
42 #include "insn-flags.h"
43 #include "output.h"
44 #include "insn-attr.h"
45 #include "flags.h"
46 #include "dojump.h"
47 #include "explow.h"
48 #include "calls.h"
49 #include "varasm.h"
50 #include "stmt.h"
51 #include "expr.h"
52 #include "tm-preds.h"
53 #include "tm-constrs.h"
54 #include "langhooks.h"
55 #include "cfgrtl.h"
56 #include "gimple.h"
57 #include "stor-layout.h"
58 #include "builtins.h"
59 #include "omp-general.h"
60 #include "omp-low.h"
61 #include "omp-offload.h"
62 #include "gomp-constants.h"
63 #include "dumpfile.h"
64 #include "internal-fn.h"
65 #include "gimple-iterator.h"
66 #include "stringpool.h"
67 #include "attribs.h"
68 #include "tree-vrp.h"
69 #include "tree-ssa-operands.h"
70 #include "tree-ssanames.h"
71 #include "gimplify.h"
72 #include "tree-phinodes.h"
73 #include "cfgloop.h"
74 #include "fold-const.h"
75 #include "intl.h"
76 #include "opts.h"
77 #include "tree-pretty-print.h"
78 #include "rtl-iter.h"
79 #include "cgraph.h"
80
81 /* This file should be included last. */
82 #include "target-def.h"
83
84 #define WORKAROUND_PTXJIT_BUG 1
85 #define WORKAROUND_PTXJIT_BUG_2 1
86 #define WORKAROUND_PTXJIT_BUG_3 1
87
88 /* The PTX concept CTA (Concurrent Thread Array) maps on the CUDA concept thread
89 block, which has had a maximum number of threads of 1024 since CUDA version
90 2.x. */
91 #define PTX_CTA_SIZE 1024
92
93 #define PTX_CTA_NUM_BARRIERS 16
94 #define PTX_WARP_SIZE 32
95
96 #define PTX_PER_CTA_BARRIER 0
97 #define PTX_NUM_PER_CTA_BARRIERS 1
98 #define PTX_FIRST_PER_WORKER_BARRIER (PTX_NUM_PER_CTA_BARRIERS)
99 #define PTX_NUM_PER_WORKER_BARRIERS (PTX_CTA_NUM_BARRIERS - PTX_NUM_PER_CTA_BARRIERS)
100
101 #define PTX_DEFAULT_VECTOR_LENGTH PTX_WARP_SIZE
102 #define PTX_MAX_VECTOR_LENGTH PTX_CTA_SIZE
103 #define PTX_WORKER_LENGTH 32
104 #define PTX_DEFAULT_RUNTIME_DIM 0 /* Defer to runtime. */
105
106 /* The various PTX memory areas an object might reside in. */
107 enum nvptx_data_area
108 {
109 DATA_AREA_GENERIC,
110 DATA_AREA_GLOBAL,
111 DATA_AREA_SHARED,
112 DATA_AREA_LOCAL,
113 DATA_AREA_CONST,
114 DATA_AREA_PARAM,
115 DATA_AREA_MAX
116 };
117
118 /* We record the data area in the target symbol flags. */
119 #define SYMBOL_DATA_AREA(SYM) \
120 (nvptx_data_area)((SYMBOL_REF_FLAGS (SYM) >> SYMBOL_FLAG_MACH_DEP_SHIFT) \
121 & 7)
122 #define SET_SYMBOL_DATA_AREA(SYM,AREA) \
123 (SYMBOL_REF_FLAGS (SYM) |= (AREA) << SYMBOL_FLAG_MACH_DEP_SHIFT)
124
125 /* Record the function decls we've written, and the libfuncs and function
126 decls corresponding to them. */
127 static std::stringstream func_decls;
128
129 struct declared_libfunc_hasher : ggc_cache_ptr_hash<rtx_def>
130 {
131 static hashval_t hash (rtx x) { return htab_hash_pointer (x); }
132 static bool equal (rtx a, rtx b) { return a == b; }
133 };
134
135 static GTY((cache))
136 hash_table<declared_libfunc_hasher> *declared_libfuncs_htab;
137
138 struct tree_hasher : ggc_cache_ptr_hash<tree_node>
139 {
140 static hashval_t hash (tree t) { return htab_hash_pointer (t); }
141 static bool equal (tree a, tree b) { return a == b; }
142 };
143
144 static GTY((cache)) hash_table<tree_hasher> *declared_fndecls_htab;
145 static GTY((cache)) hash_table<tree_hasher> *needed_fndecls_htab;
146
147 /* Buffer needed to broadcast across workers and vectors. This is
148 used for both worker-neutering and worker broadcasting, and
149 vector-neutering and boardcasting when vector_length > 32. It is
150 shared by all functions emitted. The buffer is placed in shared
151 memory. It'd be nice if PTX supported common blocks, because then
152 this could be shared across TUs (taking the largest size). */
153 static unsigned oacc_bcast_size;
154 static unsigned oacc_bcast_partition;
155 static unsigned oacc_bcast_align;
156 static GTY(()) rtx oacc_bcast_sym;
157
158 /* Buffer needed for worker reductions. This has to be distinct from
159 the worker broadcast array, as both may be live concurrently. */
160 static unsigned worker_red_size;
161 static unsigned worker_red_align;
162 static GTY(()) rtx worker_red_sym;
163
164 /* Buffer needed for vector reductions, when vector_length >
165 PTX_WARP_SIZE. This has to be distinct from the worker broadcast
166 array, as both may be live concurrently. */
167 static unsigned vector_red_size;
168 static unsigned vector_red_align;
169 static unsigned vector_red_partition;
170 static GTY(()) rtx vector_red_sym;
171
172 /* Shared memory block for gang-private variables. */
173 static unsigned gang_private_shared_size;
174 static unsigned gang_private_shared_align;
175 static GTY(()) rtx gang_private_shared_sym;
176 static hash_map<tree_decl_hash, unsigned int> gang_private_shared_hmap;
177
178 /* Global lock variable, needed for 128bit worker & gang reductions. */
179 static GTY(()) tree global_lock_var;
180
181 /* True if any function references __nvptx_stacks. */
182 static bool need_softstack_decl;
183
184 /* True if any function references __nvptx_uni. */
185 static bool need_unisimt_decl;
186
187 static int nvptx_mach_max_workers ();
188
189 /* Allocate a new, cleared machine_function structure. */
190
191 static struct machine_function *
192 nvptx_init_machine_status (void)
193 {
194 struct machine_function *p = ggc_cleared_alloc<machine_function> ();
195 p->return_mode = VOIDmode;
196 return p;
197 }
198
199 /* Issue a diagnostic when option OPTNAME is enabled (as indicated by OPTVAL)
200 and -fopenacc is also enabled. */
201
202 static void
203 diagnose_openacc_conflict (bool optval, const char *optname)
204 {
205 if (flag_openacc && optval)
206 error ("option %s is not supported together with %<-fopenacc%>", optname);
207 }
208
209 static enum ptx_version
210 first_ptx_version_supporting_sm (enum ptx_isa sm)
211 {
212 switch (sm)
213 {
214 case PTX_ISA_SM30:
215 return /* PTX_VERSION_3_0 not defined */ PTX_VERSION_3_1;
216 case PTX_ISA_SM35:
217 return PTX_VERSION_3_1;
218 case PTX_ISA_SM37:
219 case PTX_ISA_SM52:
220 return PTX_VERSION_4_1;
221 case PTX_ISA_SM53:
222 return PTX_VERSION_4_2;
223 case PTX_ISA_SM61:
224 return PTX_VERSION_5_0;
225 case PTX_ISA_SM70:
226 return PTX_VERSION_6_0;
227 case PTX_ISA_SM75:
228 return PTX_VERSION_6_3;
229 case PTX_ISA_SM80:
230 return PTX_VERSION_7_0;
231 case PTX_ISA_SM89:
232 return PTX_VERSION_7_8;
233 default:
234 gcc_unreachable ();
235 }
236 }
237
238 static enum ptx_version
239 default_ptx_version_option (void)
240 {
241 enum ptx_version first = first_ptx_version_supporting_sm (ptx_isa_option);
242
243 /* Pick a version that supports the sm. */
244 enum ptx_version res = first;
245
246 /* Pick at least 6.0, to enable using bar.warp.sync to have a way to force
247 warp convergence. */
248 res = MAX (res, PTX_VERSION_6_0);
249
250 /* Pick at least 6.3, to enable PTX '.alias'. */
251 res = MAX (res, PTX_VERSION_6_3);
252
253 /* For sm_52+, pick at least 7.3, to enable PTX 'alloca'. */
254 if (ptx_isa_option >= PTX_ISA_SM52)
255 res = MAX (res, PTX_VERSION_7_3);
256
257 /* Verify that we pick a version that supports the sm. */
258 gcc_assert (first <= res);
259 return res;
260 }
261
262 static const char *
263 ptx_version_to_string (enum ptx_version v)
264 {
265 switch (v)
266 {
267 case PTX_VERSION_3_1:
268 return "3.1";
269 case PTX_VERSION_4_1:
270 return "4.1";
271 case PTX_VERSION_4_2:
272 return "4.2";
273 case PTX_VERSION_5_0:
274 return "5.0";
275 case PTX_VERSION_6_0:
276 return "6.0";
277 case PTX_VERSION_6_3:
278 return "6.3";
279 case PTX_VERSION_7_0:
280 return "7.0";
281 case PTX_VERSION_7_3:
282 return "7.3";
283 case PTX_VERSION_7_8:
284 return "7.8";
285 default:
286 gcc_unreachable ();
287 }
288 }
289
290 unsigned int
291 ptx_version_to_number (enum ptx_version v, bool major_p)
292 {
293 switch (v)
294 {
295 case PTX_VERSION_3_1:
296 return major_p ? 3 : 1;
297 case PTX_VERSION_4_1:
298 return major_p ? 4 : 1;
299 case PTX_VERSION_4_2:
300 return major_p ? 4 : 2;
301 case PTX_VERSION_5_0:
302 return major_p ? 5 : 0;
303 case PTX_VERSION_6_0:
304 return major_p ? 6 : 0;
305 case PTX_VERSION_6_3:
306 return major_p ? 6 : 3;
307 case PTX_VERSION_7_0:
308 return major_p ? 7 : 0;
309 case PTX_VERSION_7_3:
310 return major_p ? 7 : 3;
311 case PTX_VERSION_7_8:
312 return major_p ? 7 : 8;
313 default:
314 gcc_unreachable ();
315 }
316 }
317
318 static const char *
319 sm_version_to_string (enum ptx_isa sm)
320 {
321 switch (sm)
322 {
323 #define NVPTX_SM(XX, SEP) \
324 case PTX_ISA_SM ## XX: \
325 return #XX;
326 #include "nvptx-sm.def"
327 #undef NVPTX_SM
328 default:
329 gcc_unreachable ();
330 }
331 }
332
333 static void
334 handle_ptx_version_option (void)
335 {
336 if (!OPTION_SET_P (ptx_version_option))
337 gcc_checking_assert (ptx_version_option == PTX_VERSION_default);
338
339 if (ptx_version_option == PTX_VERSION_default)
340 {
341 ptx_version_option = default_ptx_version_option ();
342 return;
343 }
344
345 enum ptx_version first = first_ptx_version_supporting_sm (ptx_isa_option);
346
347 if (ptx_version_option < first)
348 error ("PTX version (%<-mptx%>) needs to be at least %s to support selected"
349 " %<-misa%> (sm_%s)", ptx_version_to_string (first),
350 sm_version_to_string (ptx_isa_option));
351 }
352
353 /* Implement TARGET_OPTION_OVERRIDE. */
354
355 static void
356 nvptx_option_override (void)
357 {
358 init_machine_status = nvptx_init_machine_status;
359
360 /* Via nvptx 'OPTION_DEFAULT_SPECS', '-misa' always appears on the command
361 line; but handle the case that the compiler is not run via the driver. */
362 gcc_checking_assert ((ptx_isa_option == PTX_ISA_unset)
363 == (!OPTION_SET_P (ptx_isa_option)));
364 if (ptx_isa_option == PTX_ISA_unset)
365 fatal_error (UNKNOWN_LOCATION, "%<-march=%> must be specified");
366
367 handle_ptx_version_option ();
368
369 /* Set toplevel_reorder, unless explicitly disabled. We need
370 reordering so that we emit necessary assembler decls of
371 undeclared variables. */
372 if (!OPTION_SET_P (flag_toplevel_reorder))
373 flag_toplevel_reorder = 1;
374
375 debug_nonbind_markers_p = 0;
376
377 /* Set flag_no_common, unless explicitly disabled. We fake common
378 using .weak, and that's not entirely accurate, so avoid it
379 unless forced. */
380 if (!OPTION_SET_P (flag_no_common))
381 flag_no_common = 1;
382
383 /* The patch area requires nops, which we don't have. */
384 HOST_WIDE_INT patch_area_size, patch_area_entry;
385 parse_and_check_patch_area (flag_patchable_function_entry, false,
386 &patch_area_size, &patch_area_entry);
387 if (patch_area_size > 0)
388 sorry ("not generating patch area, nops not supported");
389
390 /* Assumes that it will see only hard registers. */
391 flag_var_tracking = 0;
392
393 if (nvptx_optimize < 0)
394 nvptx_optimize = optimize > 0;
395
396 declared_fndecls_htab = hash_table<tree_hasher>::create_ggc (17);
397 needed_fndecls_htab = hash_table<tree_hasher>::create_ggc (17);
398 declared_libfuncs_htab
399 = hash_table<declared_libfunc_hasher>::create_ggc (17);
400
401 oacc_bcast_sym = gen_rtx_SYMBOL_REF (Pmode, "__oacc_bcast");
402 SET_SYMBOL_DATA_AREA (oacc_bcast_sym, DATA_AREA_SHARED);
403 oacc_bcast_align = GET_MODE_ALIGNMENT (SImode) / BITS_PER_UNIT;
404 oacc_bcast_partition = 0;
405
406 worker_red_sym = gen_rtx_SYMBOL_REF (Pmode, "__worker_red");
407 SET_SYMBOL_DATA_AREA (worker_red_sym, DATA_AREA_SHARED);
408 worker_red_align = GET_MODE_ALIGNMENT (SImode) / BITS_PER_UNIT;
409
410 vector_red_sym = gen_rtx_SYMBOL_REF (Pmode, "__vector_red");
411 SET_SYMBOL_DATA_AREA (vector_red_sym, DATA_AREA_SHARED);
412 vector_red_align = GET_MODE_ALIGNMENT (SImode) / BITS_PER_UNIT;
413 vector_red_partition = 0;
414
415 gang_private_shared_sym = gen_rtx_SYMBOL_REF (Pmode, "__gang_private_shared");
416 SET_SYMBOL_DATA_AREA (gang_private_shared_sym, DATA_AREA_SHARED);
417 gang_private_shared_align = GET_MODE_ALIGNMENT (SImode) / BITS_PER_UNIT;
418
419 diagnose_openacc_conflict (TARGET_GOMP, "-mgomp");
420 diagnose_openacc_conflict (TARGET_SOFT_STACK, "-msoft-stack");
421 diagnose_openacc_conflict (TARGET_UNIFORM_SIMT, "-muniform-simt");
422
423 if (TARGET_GOMP)
424 target_flags |= MASK_SOFT_STACK | MASK_UNIFORM_SIMT;
425 }
426
427 /* Return a ptx type for MODE. If PROMOTE, then use .u32 for QImode to
428 deal with ptx ideosyncracies. */
429
430 const char *
431 nvptx_ptx_type_from_mode (machine_mode mode, bool promote)
432 {
433 switch (mode)
434 {
435 case E_BLKmode:
436 return ".b8";
437 case E_BImode:
438 return ".pred";
439 case E_QImode:
440 if (promote)
441 return ".u32";
442 else
443 return ".u8";
444 case E_HImode:
445 return ".u16";
446 case E_SImode:
447 return ".u32";
448 case E_DImode:
449 return ".u64";
450
451 case E_HFmode:
452 return ".f16";
453 case E_SFmode:
454 return ".f32";
455 case E_DFmode:
456 return ".f64";
457
458 case E_V2SImode:
459 return ".v2.u32";
460 case E_V2DImode:
461 return ".v2.u64";
462
463 default:
464 gcc_unreachable ();
465 }
466 }
467
468 /* Encode the PTX data area that DECL (which might not actually be a
469 _DECL) should reside in. */
470
471 static void
472 nvptx_encode_section_info (tree decl, rtx rtl, int first)
473 {
474 default_encode_section_info (decl, rtl, first);
475 if (first && MEM_P (rtl))
476 {
477 nvptx_data_area area = DATA_AREA_GENERIC;
478
479 if (VAR_P (decl))
480 {
481 if (lookup_attribute ("shared", DECL_ATTRIBUTES (decl)))
482 {
483 area = DATA_AREA_SHARED;
484 if (DECL_INITIAL (decl))
485 error ("static initialization of variable %q+D in %<.shared%>"
486 " memory is not supported", decl);
487 }
488 else
489 area = DATA_AREA_GLOBAL;
490 }
491
492 SET_SYMBOL_DATA_AREA (XEXP (rtl, 0), area);
493 }
494 }
495
496 /* Return the PTX name of the data area in which SYM should be
497 placed. The symbol must have already been processed by
498 nvptx_encode_seciton_info, or equivalent. */
499
500 static const char *
501 section_for_sym (rtx sym)
502 {
503 nvptx_data_area area = SYMBOL_DATA_AREA (sym);
504 /* Same order as nvptx_data_area enum. */
505 static char const *const areas[] =
506 {"", ".global", ".shared", ".local", ".const", ".param"};
507
508 return areas[area];
509 }
510
511 /* Similarly for a decl. */
512
513 static const char *
514 section_for_decl (const_tree decl)
515 {
516 return section_for_sym (XEXP (DECL_RTL (CONST_CAST (tree, decl)), 0));
517 }
518
519 /* Check NAME for special function names and redirect them by returning a
520 replacement. This applies to malloc, free and realloc, for which we
521 want to use libgcc wrappers, and call, which triggers a bug in
522 ptxas. We can't use TARGET_MANGLE_DECL_ASSEMBLER_NAME, as that's
523 not active in an offload compiler -- the names are all set by the
524 host-side compiler. */
525
526 static const char *
527 nvptx_name_replacement (const char *name)
528 {
529 if (strcmp (name, "call") == 0)
530 return "__nvptx_call";
531 if (strcmp (name, "malloc") == 0)
532 return "__nvptx_malloc";
533 if (strcmp (name, "free") == 0)
534 return "__nvptx_free";
535 if (strcmp (name, "realloc") == 0)
536 return "__nvptx_realloc";
537 return name;
538 }
539
540 /* Return NULL if NAME contains no dot. Otherwise return a copy of NAME
541 with the dots replaced with dollar signs. */
542
543 static char *
544 nvptx_replace_dot (const char *name)
545 {
546 if (strchr (name, '.') == NULL)
547 return NULL;
548
549 char *p = xstrdup (name);
550 for (size_t i = 0; i < strlen (p); ++i)
551 if (p[i] == '.')
552 p[i] = '$';
553 return p;
554 }
555
556 /* If MODE should be treated as two registers of an inner mode, return
557 that inner mode. Otherwise return VOIDmode. */
558
559 static machine_mode
560 maybe_split_mode (machine_mode mode)
561 {
562 if (COMPLEX_MODE_P (mode))
563 return GET_MODE_INNER (mode);
564
565 if (mode == TImode)
566 return DImode;
567
568 return VOIDmode;
569 }
570
571 /* Return true if mode should be treated as two registers. */
572
573 static bool
574 split_mode_p (machine_mode mode)
575 {
576 return maybe_split_mode (mode) != VOIDmode;
577 }
578
579 /* Output a register, subreg, or register pair (with optional
580 enclosing braces). */
581
582 static void
583 output_reg (FILE *file, unsigned regno, machine_mode inner_mode,
584 int subreg_offset = -1)
585 {
586 if (inner_mode == VOIDmode)
587 {
588 if (HARD_REGISTER_NUM_P (regno))
589 fprintf (file, "%s", reg_names[regno]);
590 else
591 fprintf (file, "%%r%d", regno);
592 }
593 else if (subreg_offset >= 0)
594 {
595 output_reg (file, regno, VOIDmode);
596 fprintf (file, "$%d", subreg_offset);
597 }
598 else
599 {
600 if (subreg_offset == -1)
601 fprintf (file, "{");
602 output_reg (file, regno, inner_mode, GET_MODE_SIZE (inner_mode));
603 fprintf (file, ",");
604 output_reg (file, regno, inner_mode, 0);
605 if (subreg_offset == -1)
606 fprintf (file, "}");
607 }
608 }
609
610 /* Emit forking instructions for MASK. */
611
612 static void
613 nvptx_emit_forking (unsigned mask, bool is_call)
614 {
615 mask &= (GOMP_DIM_MASK (GOMP_DIM_WORKER)
616 | GOMP_DIM_MASK (GOMP_DIM_VECTOR));
617 if (mask)
618 {
619 rtx op = GEN_INT (mask | (is_call << GOMP_DIM_MAX));
620
621 /* Emit fork at all levels. This helps form SESE regions, as
622 it creates a block with a single successor before entering a
623 partitooned region. That is a good candidate for the end of
624 an SESE region. */
625 emit_insn (gen_nvptx_fork (op));
626 emit_insn (gen_nvptx_forked (op));
627 }
628 }
629
630 /* Emit joining instructions for MASK. */
631
632 static void
633 nvptx_emit_joining (unsigned mask, bool is_call)
634 {
635 mask &= (GOMP_DIM_MASK (GOMP_DIM_WORKER)
636 | GOMP_DIM_MASK (GOMP_DIM_VECTOR));
637 if (mask)
638 {
639 rtx op = GEN_INT (mask | (is_call << GOMP_DIM_MAX));
640
641 /* Emit joining for all non-call pars to ensure there's a single
642 predecessor for the block the join insn ends up in. This is
643 needed for skipping entire loops. */
644 emit_insn (gen_nvptx_joining (op));
645 emit_insn (gen_nvptx_join (op));
646 }
647 }
648
649
650 /* Determine whether MODE and TYPE (possibly NULL) should be passed or
651 returned in memory. Integer and floating types supported by the
652 machine are passed in registers, everything else is passed in
653 memory. Complex types are split. */
654
655 static bool
656 pass_in_memory (machine_mode mode, const_tree type, bool for_return)
657 {
658 if (type)
659 {
660 if (AGGREGATE_TYPE_P (type))
661 return true;
662 if (VECTOR_TYPE_P (type))
663 return true;
664 }
665
666 if (!for_return && COMPLEX_MODE_P (mode))
667 /* Complex types are passed as two underlying args. */
668 mode = GET_MODE_INNER (mode);
669
670 if (GET_MODE_CLASS (mode) != MODE_INT
671 && GET_MODE_CLASS (mode) != MODE_FLOAT)
672 return true;
673
674 if (GET_MODE_SIZE (mode) > UNITS_PER_WORD)
675 return true;
676
677 return false;
678 }
679
680 /* A non-memory argument of mode MODE is being passed, determine the mode it
681 should be promoted to. This is also used for determining return
682 type promotion. */
683
684 static machine_mode
685 promote_arg (machine_mode mode, bool prototyped)
686 {
687 if (!prototyped && mode == SFmode)
688 /* K&R float promotion for unprototyped functions. */
689 mode = DFmode;
690 else if (GET_MODE_SIZE (mode) < GET_MODE_SIZE (SImode))
691 mode = SImode;
692
693 return mode;
694 }
695
696 /* A non-memory return type of MODE is being returned. Determine the
697 mode it should be promoted to. */
698
699 static machine_mode
700 promote_return (machine_mode mode)
701 {
702 return promote_arg (mode, true);
703 }
704
705 /* Implement TARGET_FUNCTION_ARG. */
706
707 static rtx
708 nvptx_function_arg (cumulative_args_t, const function_arg_info &arg)
709 {
710 if (arg.end_marker_p () || !arg.named)
711 return NULL_RTX;
712
713 return gen_reg_rtx (arg.mode);
714 }
715
716 /* Implement TARGET_FUNCTION_INCOMING_ARG. */
717
718 static rtx
719 nvptx_function_incoming_arg (cumulative_args_t cum_v,
720 const function_arg_info &arg)
721 {
722 CUMULATIVE_ARGS *cum = get_cumulative_args (cum_v);
723
724 if (arg.end_marker_p () || !arg.named)
725 return NULL_RTX;
726
727 /* No need to deal with split modes here, the only case that can
728 happen is complex modes and those are dealt with by
729 TARGET_SPLIT_COMPLEX_ARG. */
730 return gen_rtx_UNSPEC (arg.mode,
731 gen_rtvec (1, GEN_INT (cum->count)),
732 UNSPEC_ARG_REG);
733 }
734
735 /* Implement TARGET_FUNCTION_ARG_ADVANCE. */
736
737 static void
738 nvptx_function_arg_advance (cumulative_args_t cum_v, const function_arg_info &)
739 {
740 CUMULATIVE_ARGS *cum = get_cumulative_args (cum_v);
741
742 cum->count++;
743 }
744
745 /* Implement TARGET_FUNCTION_ARG_BOUNDARY.
746
747 For nvptx This is only used for variadic args. The type has already
748 been promoted and/or converted to invisible reference. */
749
750 static unsigned
751 nvptx_function_arg_boundary (machine_mode mode, const_tree ARG_UNUSED (type))
752 {
753 return GET_MODE_ALIGNMENT (mode);
754 }
755
756 /* Handle the TARGET_STRICT_ARGUMENT_NAMING target hook.
757
758 For nvptx, we know how to handle functions declared as stdarg: by
759 passing an extra pointer to the unnamed arguments. However, the
760 Fortran frontend can produce a different situation, where a
761 function pointer is declared with no arguments, but the actual
762 function and calls to it take more arguments. In that case, we
763 want to ensure the call matches the definition of the function. */
764
765 static bool
766 nvptx_strict_argument_naming (cumulative_args_t cum_v)
767 {
768 CUMULATIVE_ARGS *cum = get_cumulative_args (cum_v);
769
770 return cum->fntype == NULL_TREE || stdarg_p (cum->fntype);
771 }
772
773 /* Implement TARGET_LIBCALL_VALUE. */
774
775 static rtx
776 nvptx_libcall_value (machine_mode mode, const_rtx)
777 {
778 if (!cfun || !cfun->machine->doing_call)
779 /* Pretend to return in a hard reg for early uses before pseudos can be
780 generated. */
781 return gen_rtx_REG (mode, NVPTX_RETURN_REGNUM);
782
783 return gen_reg_rtx (mode);
784 }
785
786 /* TARGET_FUNCTION_VALUE implementation. Returns an RTX representing the place
787 where function FUNC returns or receives a value of data type TYPE. */
788
789 static rtx
790 nvptx_function_value (const_tree type, const_tree ARG_UNUSED (func),
791 bool outgoing)
792 {
793 machine_mode mode = promote_return (TYPE_MODE (type));
794
795 if (outgoing)
796 {
797 gcc_assert (cfun);
798 cfun->machine->return_mode = mode;
799 return gen_rtx_REG (mode, NVPTX_RETURN_REGNUM);
800 }
801
802 return nvptx_libcall_value (mode, NULL_RTX);
803 }
804
805 /* Implement TARGET_FUNCTION_VALUE_REGNO_P. */
806
807 static bool
808 nvptx_function_value_regno_p (const unsigned int regno)
809 {
810 return regno == NVPTX_RETURN_REGNUM;
811 }
812
813 /* Types with a mode other than those supported by the machine are passed by
814 reference in memory. */
815
816 static bool
817 nvptx_pass_by_reference (cumulative_args_t, const function_arg_info &arg)
818 {
819 return pass_in_memory (arg.mode, arg.type, false);
820 }
821
822 /* Implement TARGET_RETURN_IN_MEMORY. */
823
824 static bool
825 nvptx_return_in_memory (const_tree type, const_tree)
826 {
827 return pass_in_memory (TYPE_MODE (type), type, true);
828 }
829
830 /* Implement TARGET_PROMOTE_FUNCTION_MODE. */
831
832 static machine_mode
833 nvptx_promote_function_mode (const_tree type, machine_mode mode,
834 int *ARG_UNUSED (punsignedp),
835 const_tree funtype, int for_return)
836 {
837 return promote_arg (mode, for_return || !type || TYPE_ARG_TYPES (funtype));
838 }
839
840 /* Helper for write_arg. Emit a single PTX argument of MODE, either
841 in a prototype, or as copy in a function prologue. ARGNO is the
842 index of this argument in the PTX function. FOR_REG is negative,
843 if we're emitting the PTX prototype. It is zero if we're copying
844 to an argument register and it is greater than zero if we're
845 copying to a specific hard register. */
846
847 static int
848 write_arg_mode (std::stringstream &s, int for_reg, int argno,
849 machine_mode mode)
850 {
851 const char *ptx_type = nvptx_ptx_type_from_mode (mode, false);
852
853 if (for_reg < 0)
854 {
855 /* Writing PTX prototype. */
856 s << (argno ? ", " : " (");
857 s << ".param" << ptx_type << " %in_ar" << argno;
858 }
859 else
860 {
861 s << "\t.reg" << ptx_type << " ";
862 if (for_reg)
863 s << reg_names[for_reg];
864 else
865 s << "%ar" << argno;
866 s << ";\n";
867 if (argno >= 0)
868 {
869 s << "\tld.param" << ptx_type << " ";
870 if (for_reg)
871 s << reg_names[for_reg];
872 else
873 s << "%ar" << argno;
874 s << ", [%in_ar" << argno << "];\n";
875 }
876 }
877 return argno + 1;
878 }
879
880 /* Process function parameter TYPE to emit one or more PTX
881 arguments. S, FOR_REG and ARGNO as for write_arg_mode. PROTOTYPED
882 is true, if this is a prototyped function, rather than an old-style
883 C declaration. Returns the next argument number to use.
884
885 The promotion behavior here must match the regular GCC function
886 parameter marshalling machinery. */
887
888 static int
889 write_arg_type (std::stringstream &s, int for_reg, int argno,
890 tree type, bool prototyped)
891 {
892 machine_mode mode = TYPE_MODE (type);
893
894 if (mode == VOIDmode)
895 return argno;
896
897 if (pass_in_memory (mode, type, false))
898 mode = Pmode;
899 else
900 {
901 bool split = TREE_CODE (type) == COMPLEX_TYPE;
902
903 if (split)
904 {
905 /* Complex types are sent as two separate args. */
906 type = TREE_TYPE (type);
907 mode = TYPE_MODE (type);
908 prototyped = true;
909 }
910
911 mode = promote_arg (mode, prototyped);
912 if (split)
913 argno = write_arg_mode (s, for_reg, argno, mode);
914 }
915
916 return write_arg_mode (s, for_reg, argno, mode);
917 }
918
919 /* Emit a PTX return as a prototype or function prologue declaration
920 for MODE. */
921
922 static void
923 write_return_mode (std::stringstream &s, bool for_proto, machine_mode mode)
924 {
925 const char *ptx_type = nvptx_ptx_type_from_mode (mode, false);
926 const char *pfx = "\t.reg";
927 const char *sfx = ";\n";
928
929 if (for_proto)
930 pfx = "(.param", sfx = "_out) ";
931
932 s << pfx << ptx_type << " " << reg_names[NVPTX_RETURN_REGNUM] << sfx;
933 }
934
935 /* Process a function return TYPE to emit a PTX return as a prototype
936 or function prologue declaration. Returns true if return is via an
937 additional pointer parameter. The promotion behavior here must
938 match the regular GCC function return mashalling. */
939
940 static bool
941 write_return_type (std::stringstream &s, bool for_proto, tree type)
942 {
943 machine_mode mode = TYPE_MODE (type);
944
945 if (mode == VOIDmode)
946 return false;
947
948 bool return_in_mem = pass_in_memory (mode, type, true);
949
950 if (return_in_mem)
951 {
952 if (for_proto)
953 return return_in_mem;
954
955 /* Named return values can cause us to return a pointer as well
956 as expect an argument for the return location. This is
957 optimization-level specific, so no caller can make use of
958 this data, but more importantly for us, we must ensure it
959 doesn't change the PTX prototype. */
960 mode = (machine_mode) cfun->machine->return_mode;
961
962 if (mode == VOIDmode)
963 return return_in_mem;
964
965 /* Clear return_mode to inhibit copy of retval to non-existent
966 retval parameter. */
967 cfun->machine->return_mode = VOIDmode;
968 }
969 else
970 mode = promote_return (mode);
971
972 write_return_mode (s, for_proto, mode);
973
974 return return_in_mem;
975 }
976
977 /* Look for attributes in ATTRS that would indicate we must write a function
978 as a .entry kernel rather than a .func. Return true if one is found. */
979
980 static bool
981 write_as_kernel (tree attrs)
982 {
983 return (lookup_attribute ("kernel", attrs) != NULL_TREE
984 || (lookup_attribute ("omp target entrypoint", attrs) != NULL_TREE
985 && lookup_attribute ("oacc function", attrs) != NULL_TREE));
986 /* For OpenMP target regions, the corresponding kernel entry is emitted from
987 write_omp_entry as a separate function. */
988 }
989
990 /* Emit a linker marker for a function decl or defn. */
991
992 static void
993 write_fn_marker (std::stringstream &s, bool is_defn, bool globalize,
994 const char *name)
995 {
996 s << "\n// BEGIN";
997 if (globalize)
998 s << " GLOBAL";
999 s << " FUNCTION " << (is_defn ? "DEF: " : "DECL: ");
1000 s << name << "\n";
1001 }
1002
1003 /* Emit a linker marker for a variable decl or defn. */
1004
1005 static void
1006 write_var_marker (FILE *file, bool is_defn, bool globalize, const char *name)
1007 {
1008 fprintf (file, "\n// BEGIN%s VAR %s: ",
1009 globalize ? " GLOBAL" : "",
1010 is_defn ? "DEF" : "DECL");
1011 assemble_name_raw (file, name);
1012 fputs ("\n", file);
1013 }
1014
1015 /* Helper function for write_fn_proto. */
1016
1017 static void
1018 write_fn_proto_1 (std::stringstream &s, bool is_defn,
1019 const char *name, const_tree decl, bool force_public)
1020 {
1021 write_fn_marker (s, is_defn, TREE_PUBLIC (decl) || force_public, name);
1022
1023 /* PTX declaration. */
1024 if (DECL_EXTERNAL (decl))
1025 s << ".extern ";
1026 else if (TREE_PUBLIC (decl) || force_public)
1027 s << (DECL_WEAK (decl) ? ".weak " : ".visible ");
1028 s << (write_as_kernel (DECL_ATTRIBUTES (decl)) ? ".entry " : ".func ");
1029
1030 tree fntype = TREE_TYPE (decl);
1031 tree result_type = TREE_TYPE (fntype);
1032
1033 /* atomic_compare_exchange_$n builtins have an exceptional calling
1034 convention. */
1035 int not_atomic_weak_arg = -1;
1036 if (DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
1037 switch (DECL_FUNCTION_CODE (decl))
1038 {
1039 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_1:
1040 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_2:
1041 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_4:
1042 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_8:
1043 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_16:
1044 /* These atomics skip the 'weak' parm in an actual library
1045 call. We must skip it in the prototype too. */
1046 not_atomic_weak_arg = 3;
1047 break;
1048
1049 default:
1050 break;
1051 }
1052
1053 /* Declare the result. */
1054 bool return_in_mem = write_return_type (s, true, result_type);
1055
1056 s << name;
1057
1058 int argno = 0;
1059
1060 /* Emit argument list. */
1061 if (return_in_mem)
1062 argno = write_arg_type (s, -1, argno, ptr_type_node, true);
1063
1064 /* We get:
1065 NULL in TYPE_ARG_TYPES, for old-style functions
1066 NULL in DECL_ARGUMENTS, for builtin functions without another
1067 declaration.
1068 So we have to pick the best one we have. */
1069 tree args = TYPE_ARG_TYPES (fntype);
1070 bool prototyped = true;
1071 if (!args)
1072 {
1073 args = DECL_ARGUMENTS (decl);
1074 prototyped = false;
1075 }
1076
1077 for (; args; args = TREE_CHAIN (args), not_atomic_weak_arg--)
1078 {
1079 tree type = prototyped ? TREE_VALUE (args) : TREE_TYPE (args);
1080
1081 if (not_atomic_weak_arg)
1082 argno = write_arg_type (s, -1, argno, type, prototyped);
1083 else
1084 gcc_assert (TREE_CODE (type) == BOOLEAN_TYPE);
1085 }
1086
1087 if (stdarg_p (fntype))
1088 argno = write_arg_type (s, -1, argno, ptr_type_node, true);
1089
1090 if (DECL_STATIC_CHAIN (decl))
1091 argno = write_arg_type (s, -1, argno, ptr_type_node, true);
1092
1093 if (argno < 2 && strcmp (name, "main") == 0)
1094 {
1095 if (argno == 0)
1096 argno = write_arg_type (s, -1, argno, integer_type_node, true);
1097
1098 if (argno == 1)
1099 argno = write_arg_type (s, -1, argno, ptr_type_node, true);
1100 }
1101
1102 if (argno)
1103 s << ")";
1104
1105 s << (is_defn ? "\n" : ";\n");
1106 }
1107
1108 /* Write a .func or .kernel declaration or definition along with
1109 a helper comment for use by ld. S is the stream to write to, DECL
1110 the decl for the function with name NAME. For definitions, emit
1111 a declaration too. */
1112
1113 static void
1114 write_fn_proto (std::stringstream &s, bool is_defn,
1115 const char *name, const_tree decl, bool force_public=false)
1116 {
1117 const char *replacement = nvptx_name_replacement (name);
1118 char *replaced_dots = NULL;
1119 if (replacement != name)
1120 name = replacement;
1121 else
1122 {
1123 replaced_dots = nvptx_replace_dot (name);
1124 if (replaced_dots)
1125 name = replaced_dots;
1126 }
1127 if (name[0] == '*')
1128 name++;
1129
1130 if (is_defn)
1131 /* Emit a declaration. The PTX assembler gets upset without it. */
1132 write_fn_proto_1 (s, false, name, decl, force_public);
1133
1134 write_fn_proto_1 (s, is_defn, name, decl, force_public);
1135
1136 if (replaced_dots)
1137 XDELETE (replaced_dots);
1138 }
1139
1140 /* Construct a function declaration from a call insn. This can be
1141 necessary for two reasons - either we have an indirect call which
1142 requires a .callprototype declaration, or we have a libcall
1143 generated by emit_library_call for which no decl exists. */
1144
1145 static void
1146 write_fn_proto_from_insn (std::stringstream &s, const char *name,
1147 rtx result, rtx pat)
1148 {
1149 char *replaced_dots = NULL;
1150
1151 if (!name)
1152 {
1153 s << "\t.callprototype ";
1154 name = "_";
1155 }
1156 else
1157 {
1158 const char *replacement = nvptx_name_replacement (name);
1159 if (replacement != name)
1160 name = replacement;
1161 else
1162 {
1163 replaced_dots = nvptx_replace_dot (name);
1164 if (replaced_dots)
1165 name = replaced_dots;
1166 }
1167 write_fn_marker (s, false, true, name);
1168 s << "\t.extern .func ";
1169 }
1170
1171 if (result != NULL_RTX)
1172 write_return_mode (s, true, GET_MODE (result));
1173
1174 s << name;
1175 if (replaced_dots)
1176 XDELETE (replaced_dots);
1177
1178 int arg_end = XVECLEN (pat, 0);
1179 for (int i = 1; i < arg_end; i++)
1180 {
1181 /* We don't have to deal with mode splitting & promotion here,
1182 as that was already done when generating the call
1183 sequence. */
1184 machine_mode mode = GET_MODE (XEXP (XVECEXP (pat, 0, i), 0));
1185
1186 write_arg_mode (s, -1, i - 1, mode);
1187 }
1188 if (arg_end != 1)
1189 s << ")";
1190 s << ";\n";
1191 }
1192
1193 /* DECL is an external FUNCTION_DECL, make sure its in the fndecl hash
1194 table and write a ptx prototype. These are emitted at end of
1195 compilation. */
1196
1197 static void
1198 nvptx_record_fndecl (tree decl)
1199 {
1200 tree *slot = declared_fndecls_htab->find_slot (decl, INSERT);
1201 if (*slot == NULL)
1202 {
1203 *slot = decl;
1204 const char *name = get_fnname_from_decl (decl);
1205 write_fn_proto (func_decls, false, name, decl);
1206 }
1207 }
1208
1209 /* Record a libcall or unprototyped external function. CALLEE is the
1210 SYMBOL_REF. Insert into the libfunc hash table and emit a ptx
1211 declaration for it. */
1212
1213 static void
1214 nvptx_record_libfunc (rtx callee, rtx retval, rtx pat)
1215 {
1216 rtx *slot = declared_libfuncs_htab->find_slot (callee, INSERT);
1217 if (*slot == NULL)
1218 {
1219 *slot = callee;
1220
1221 const char *name = XSTR (callee, 0);
1222 write_fn_proto_from_insn (func_decls, name, retval, pat);
1223 }
1224 }
1225
1226 /* DECL is an external FUNCTION_DECL, that we're referencing. If it
1227 is prototyped, record it now. Otherwise record it as needed at end
1228 of compilation, when we might have more information about it. */
1229
1230 static void
1231 nvptx_record_needed_fndecl (tree decl)
1232 {
1233 if (TYPE_ARG_TYPES (TREE_TYPE (decl)) == NULL_TREE)
1234 {
1235 tree *slot = needed_fndecls_htab->find_slot (decl, INSERT);
1236 if (*slot == NULL)
1237 *slot = decl;
1238 }
1239 else
1240 nvptx_record_fndecl (decl);
1241 }
1242
1243 /* SYM is a SYMBOL_REF. If it refers to an external function, record
1244 it as needed. */
1245
1246 static void
1247 nvptx_maybe_record_fnsym (rtx sym)
1248 {
1249 tree decl = SYMBOL_REF_DECL (sym);
1250
1251 if (decl && TREE_CODE (decl) == FUNCTION_DECL && DECL_EXTERNAL (decl))
1252 nvptx_record_needed_fndecl (decl);
1253 }
1254
1255 /* Emit a local array to hold some part of a conventional stack frame
1256 and initialize REGNO to point to it. If the size is zero, it'll
1257 never be valid to dereference, so we can simply initialize to
1258 zero. */
1259
1260 static void
1261 init_frame (FILE *file, int regno, unsigned align, unsigned size)
1262 {
1263 if (size)
1264 fprintf (file, "\t.local .align %d .b8 %s_ar[%u];\n",
1265 align, reg_names[regno], size);
1266 fprintf (file, "\t.reg.u%d %s;\n",
1267 POINTER_SIZE, reg_names[regno]);
1268 fprintf (file, (size ? "\tcvta.local.u%d %s, %s_ar;\n"
1269 : "\tmov.u%d %s, 0;\n"),
1270 POINTER_SIZE, reg_names[regno], reg_names[regno]);
1271 }
1272
1273 /* Emit soft stack frame setup sequence. */
1274
1275 static void
1276 init_softstack_frame (FILE *file, unsigned alignment, HOST_WIDE_INT size)
1277 {
1278 /* Maintain 64-bit stack alignment. */
1279 unsigned keep_align = BIGGEST_ALIGNMENT / BITS_PER_UNIT;
1280 size = ROUND_UP (size, keep_align);
1281 int bits = POINTER_SIZE;
1282 const char *reg_stack = reg_names[STACK_POINTER_REGNUM];
1283 const char *reg_frame = reg_names[FRAME_POINTER_REGNUM];
1284 const char *reg_sspslot = reg_names[SOFTSTACK_SLOT_REGNUM];
1285 const char *reg_sspprev = reg_names[SOFTSTACK_PREV_REGNUM];
1286 fprintf (file, "\t.reg.u%d %s;\n", bits, reg_stack);
1287 fprintf (file, "\t.reg.u%d %s;\n", bits, reg_frame);
1288 fprintf (file, "\t.reg.u%d %s;\n", bits, reg_sspslot);
1289 fprintf (file, "\t.reg.u%d %s;\n", bits, reg_sspprev);
1290 fprintf (file, "\t{\n");
1291 fprintf (file, "\t\t.reg.u32 %%fstmp0;\n");
1292 fprintf (file, "\t\t.reg.u%d %%fstmp1;\n", bits);
1293 fprintf (file, "\t\t.reg.u%d %%fstmp2;\n", bits);
1294 fprintf (file, "\t\tmov.u32 %%fstmp0, %%tid.y;\n");
1295 fprintf (file, "\t\tmul%s.u32 %%fstmp1, %%fstmp0, %d;\n",
1296 bits == 64 ? ".wide" : ".lo", bits / 8);
1297 fprintf (file, "\t\tmov.u%d %%fstmp2, __nvptx_stacks;\n", bits);
1298
1299 /* Initialize %sspslot = &__nvptx_stacks[tid.y]. */
1300 fprintf (file, "\t\tadd.u%d %s, %%fstmp2, %%fstmp1;\n", bits, reg_sspslot);
1301
1302 /* Initialize %sspprev = __nvptx_stacks[tid.y]. */
1303 fprintf (file, "\t\tld.shared.u%d %s, [%s];\n",
1304 bits, reg_sspprev, reg_sspslot);
1305
1306 /* Initialize %frame = %sspprev - size. */
1307 fprintf (file, "\t\tsub.u%d %s, %s, " HOST_WIDE_INT_PRINT_DEC ";\n",
1308 bits, reg_frame, reg_sspprev, size);
1309
1310 /* Apply alignment, if larger than 64. */
1311 if (alignment > keep_align)
1312 fprintf (file, "\t\tand.b%d %s, %s, %d;\n",
1313 bits, reg_frame, reg_frame, -alignment);
1314
1315 size = crtl->outgoing_args_size;
1316 gcc_assert (size % keep_align == 0);
1317
1318 /* Initialize %stack. */
1319 fprintf (file, "\t\tsub.u%d %s, %s, " HOST_WIDE_INT_PRINT_DEC ";\n",
1320 bits, reg_stack, reg_frame, size);
1321
1322 if (!crtl->is_leaf)
1323 fprintf (file, "\t\tst.shared.u%d [%s], %s;\n",
1324 bits, reg_sspslot, reg_stack);
1325 fprintf (file, "\t}\n");
1326 cfun->machine->has_softstack = true;
1327 need_softstack_decl = true;
1328 }
1329
1330 /* Emit code to initialize the REGNO predicate register to indicate
1331 whether we are not lane zero on the NAME axis. */
1332
1333 static void
1334 nvptx_init_axis_predicate (FILE *file, int regno, const char *name)
1335 {
1336 fprintf (file, "\t{\n");
1337 fprintf (file, "\t\t.reg.u32\t%%%s;\n", name);
1338 if (strcmp (name, "x") == 0 && cfun->machine->red_partition)
1339 {
1340 fprintf (file, "\t\t.reg.u64\t%%t_red;\n");
1341 fprintf (file, "\t\t.reg.u64\t%%y64;\n");
1342 }
1343 fprintf (file, "\t\tmov.u32\t%%%s, %%tid.%s;\n", name, name);
1344 fprintf (file, "\t\tsetp.ne.u32\t%%r%d, %%%s, 0;\n", regno, name);
1345 if (strcmp (name, "x") == 0 && cfun->machine->red_partition)
1346 {
1347 fprintf (file, "\t\tcvt.u64.u32\t%%y64, %%tid.y;\n");
1348 fprintf (file, "\t\tcvta.shared.u64\t%%t_red, __vector_red;\n");
1349 fprintf (file, "\t\tmad.lo.u64\t%%r%d, %%y64, %d, %%t_red; "
1350 "// vector reduction buffer\n",
1351 REGNO (cfun->machine->red_partition),
1352 vector_red_partition);
1353 }
1354 /* Verify vector_red_size. */
1355 gcc_assert (vector_red_partition * nvptx_mach_max_workers ()
1356 <= vector_red_size);
1357 fprintf (file, "\t}\n");
1358 }
1359
1360 /* Emit code to initialize OpenACC worker broadcast and synchronization
1361 registers. */
1362
1363 static void
1364 nvptx_init_oacc_workers (FILE *file)
1365 {
1366 fprintf (file, "\t{\n");
1367 fprintf (file, "\t\t.reg.u32\t%%tidy;\n");
1368 if (cfun->machine->bcast_partition)
1369 {
1370 fprintf (file, "\t\t.reg.u64\t%%t_bcast;\n");
1371 fprintf (file, "\t\t.reg.u64\t%%y64;\n");
1372 }
1373 fprintf (file, "\t\tmov.u32\t\t%%tidy, %%tid.y;\n");
1374 if (cfun->machine->bcast_partition)
1375 {
1376 fprintf (file, "\t\tcvt.u64.u32\t%%y64, %%tidy;\n");
1377 fprintf (file, "\t\tadd.u64\t\t%%y64, %%y64, 1; // vector ID\n");
1378 fprintf (file, "\t\tcvta.shared.u64\t%%t_bcast, __oacc_bcast;\n");
1379 fprintf (file, "\t\tmad.lo.u64\t%%r%d, %%y64, %d, %%t_bcast; "
1380 "// vector broadcast offset\n",
1381 REGNO (cfun->machine->bcast_partition),
1382 oacc_bcast_partition);
1383 }
1384 /* Verify oacc_bcast_size. */
1385 gcc_assert (oacc_bcast_partition * (nvptx_mach_max_workers () + 1)
1386 <= oacc_bcast_size);
1387 if (cfun->machine->sync_bar)
1388 fprintf (file, "\t\tadd.u32\t\t%%r%d, %%tidy, 1; "
1389 "// vector synchronization barrier\n",
1390 REGNO (cfun->machine->sync_bar));
1391 fprintf (file, "\t}\n");
1392 }
1393
1394 /* Emit code to initialize predicate and master lane index registers for
1395 -muniform-simt code generation variant. */
1396
1397 static void
1398 nvptx_init_unisimt_predicate (FILE *file)
1399 {
1400 cfun->machine->unisimt_location = gen_reg_rtx (Pmode);
1401 int loc = REGNO (cfun->machine->unisimt_location);
1402 int bits = POINTER_SIZE;
1403 fprintf (file, "\t.reg.u%d %%r%d;\n", bits, loc);
1404 fprintf (file, "\t{\n");
1405 fprintf (file, "\t\t.reg.u32 %%ustmp0;\n");
1406 fprintf (file, "\t\t.reg.u%d %%ustmp1;\n", bits);
1407 fprintf (file, "\t\tmov.u32 %%ustmp0, %%tid.y;\n");
1408 fprintf (file, "\t\tmul%s.u32 %%ustmp1, %%ustmp0, 4;\n",
1409 bits == 64 ? ".wide" : ".lo");
1410 fprintf (file, "\t\tmov.u%d %%r%d, __nvptx_uni;\n", bits, loc);
1411 fprintf (file, "\t\tadd.u%d %%r%d, %%r%d, %%ustmp1;\n", bits, loc, loc);
1412 if (cfun->machine->unisimt_predicate)
1413 {
1414 int master = REGNO (cfun->machine->unisimt_master);
1415 int pred = REGNO (cfun->machine->unisimt_predicate);
1416 fprintf (file, "\t\tld.shared.u32 %%r%d, [%%r%d];\n", master, loc);
1417 if (cfun->machine->unisimt_outside_simt_predicate)
1418 {
1419 int pred_outside_simt
1420 = REGNO (cfun->machine->unisimt_outside_simt_predicate);
1421 fprintf (file, "\t\tsetp.eq.u32 %%r%d, %%r%d, 0;\n",
1422 pred_outside_simt, master);
1423 }
1424 fprintf (file, "\t\tmov.u32 %%ustmp0, %%laneid;\n");
1425 /* Compute 'master lane index' as 'laneid & __nvptx_uni[tid.y]'. */
1426 fprintf (file, "\t\tand.b32 %%r%d, %%r%d, %%ustmp0;\n", master, master);
1427 /* Compute predicate as 'tid.x == master'. */
1428 fprintf (file, "\t\tsetp.eq.u32 %%r%d, %%r%d, %%ustmp0;\n", pred, master);
1429 }
1430 fprintf (file, "\t}\n");
1431 need_unisimt_decl = true;
1432 }
1433
1434 /* Emit kernel NAME for function ORIG outlined for an OpenMP 'target' region:
1435
1436 extern void gomp_nvptx_main (void (*fn)(void*), void *fnarg);
1437 void __attribute__((kernel)) NAME (void *arg, char *stack, size_t stacksize)
1438 {
1439 __nvptx_stacks[tid.y] = stack + stacksize * (ctaid.x * ntid.y + tid.y + 1);
1440 __nvptx_uni[tid.y] = 0;
1441 gomp_nvptx_main (ORIG, arg);
1442 }
1443 ORIG itself should not be emitted as a PTX .entry function. */
1444
1445 static void
1446 write_omp_entry (FILE *file, const char *name, const char *orig)
1447 {
1448 static bool gomp_nvptx_main_declared;
1449 if (!gomp_nvptx_main_declared)
1450 {
1451 gomp_nvptx_main_declared = true;
1452 write_fn_marker (func_decls, false, true, "gomp_nvptx_main");
1453 func_decls << ".extern .func gomp_nvptx_main (.param.u" << POINTER_SIZE
1454 << " %in_ar1, .param.u" << POINTER_SIZE << " %in_ar2);\n";
1455 }
1456 /* PR79332. Single out this string; it confuses gcc.pot generation. */
1457 #define NTID_Y "%ntid.y"
1458 #define ENTRY_TEMPLATE(PS, PS_BYTES, MAD_PS_32) "\
1459 (.param.u" PS " %arg, .param.u" PS " %stack, .param.u" PS " %sz)\n\
1460 {\n\
1461 .reg.u32 %r<3>;\n\
1462 .reg.u" PS " %R<4>;\n\
1463 mov.u32 %r0, %tid.y;\n\
1464 mov.u32 %r1, " NTID_Y ";\n\
1465 mov.u32 %r2, %ctaid.x;\n\
1466 cvt.u" PS ".u32 %R1, %r0;\n\
1467 " MAD_PS_32 " %R1, %r1, %r2, %R1;\n\
1468 mov.u" PS " %R0, __nvptx_stacks;\n\
1469 " MAD_PS_32 " %R0, %r0, " PS_BYTES ", %R0;\n\
1470 ld.param.u" PS " %R2, [%stack];\n\
1471 ld.param.u" PS " %R3, [%sz];\n\
1472 add.u" PS " %R2, %R2, %R3;\n\
1473 mad.lo.u" PS " %R2, %R1, %R3, %R2;\n\
1474 st.shared.u" PS " [%R0], %R2;\n\
1475 mov.u" PS " %R0, __nvptx_uni;\n\
1476 " MAD_PS_32 " %R0, %r0, 4, %R0;\n\
1477 mov.u32 %r0, 0;\n\
1478 st.shared.u32 [%R0], %r0;\n\
1479 mov.u" PS " %R0, \0;\n\
1480 ld.param.u" PS " %R1, [%arg];\n\
1481 {\n\
1482 .param.u" PS " %P<2>;\n\
1483 st.param.u" PS " [%P0], %R0;\n\
1484 st.param.u" PS " [%P1], %R1;\n\
1485 call.uni gomp_nvptx_main, (%P0, %P1);\n\
1486 }\n\
1487 ret.uni;\n\
1488 }\n"
1489 static const char entry64[] = ENTRY_TEMPLATE ("64", "8", "mad.wide.u32");
1490 static const char entry32[] = ENTRY_TEMPLATE ("32", "4", "mad.lo.u32 ");
1491 #undef ENTRY_TEMPLATE
1492 #undef NTID_Y
1493 const char *entry_1 = TARGET_ABI64 ? entry64 : entry32;
1494 /* Position ENTRY_2 after the embedded nul using strlen of the prefix. */
1495 const char *entry_2 = entry_1 + strlen (entry64) + 1;
1496 fprintf (file, ".visible .entry %s%s%s%s", name, entry_1, orig, entry_2);
1497 need_softstack_decl = need_unisimt_decl = true;
1498 }
1499
1500 /* Implement ASM_DECLARE_FUNCTION_NAME. Writes the start of a ptx
1501 function, including local var decls and copies from the arguments to
1502 local regs. */
1503
1504 void
1505 nvptx_declare_function_name (FILE *file, const char *name, const_tree decl)
1506 {
1507 tree fntype = TREE_TYPE (decl);
1508 tree result_type = TREE_TYPE (fntype);
1509 int argno = 0;
1510 bool force_public = false;
1511
1512 /* For reverse-offload 'nohost' functions: In order to be collectable in
1513 '$offload_func_table', cf. mkoffload.cc, the function has to be visible. */
1514 if (lookup_attribute ("omp target device_ancestor_nohost",
1515 DECL_ATTRIBUTES (decl)))
1516 force_public = true;
1517 if (lookup_attribute ("omp target entrypoint", DECL_ATTRIBUTES (decl))
1518 && !lookup_attribute ("oacc function", DECL_ATTRIBUTES (decl)))
1519 {
1520 char *buf = (char *) alloca (strlen (name) + sizeof ("$impl"));
1521 sprintf (buf, "%s$impl", name);
1522 write_omp_entry (file, name, buf);
1523 name = buf;
1524 }
1525 /* We construct the initial part of the function into a string
1526 stream, in order to share the prototype writing code. */
1527 std::stringstream s;
1528 write_fn_proto (s, true, name, decl, force_public);
1529 s << "{\n";
1530
1531 bool return_in_mem = write_return_type (s, false, result_type);
1532 if (return_in_mem)
1533 argno = write_arg_type (s, 0, argno, ptr_type_node, true);
1534
1535 /* Declare and initialize incoming arguments. */
1536 tree args = TYPE_ARG_TYPES (fntype);
1537 bool prototyped = true;
1538 if (!args)
1539 {
1540 args = DECL_ARGUMENTS (decl);
1541 prototyped = false;
1542 }
1543
1544 for (; args != NULL_TREE; args = TREE_CHAIN (args))
1545 {
1546 tree type = prototyped ? TREE_VALUE (args) : TREE_TYPE (args);
1547
1548 argno = write_arg_type (s, 0, argno, type, prototyped);
1549 }
1550
1551 if (stdarg_p (fntype))
1552 argno = write_arg_type (s, ARG_POINTER_REGNUM, argno, ptr_type_node,
1553 true);
1554
1555 if (DECL_STATIC_CHAIN (decl) || cfun->machine->has_chain)
1556 write_arg_type (s, STATIC_CHAIN_REGNUM,
1557 DECL_STATIC_CHAIN (decl) ? argno : -1, ptr_type_node,
1558 true);
1559
1560 fprintf (file, "%s", s.str().c_str());
1561
1562 /* Usually 'crtl->is_leaf' is computed during register allocator
1563 initialization (which is not done on NVPTX) or for pressure-sensitive
1564 optimizations. Initialize it here, except if already set. */
1565 if (!crtl->is_leaf)
1566 crtl->is_leaf = leaf_function_p ();
1567
1568 HOST_WIDE_INT sz = get_frame_size ();
1569 bool need_frameptr = sz || cfun->machine->has_chain;
1570 int alignment = crtl->stack_alignment_needed / BITS_PER_UNIT;
1571 if (!TARGET_SOFT_STACK)
1572 {
1573 /* Declare a local var for outgoing varargs. */
1574 if (cfun->machine->has_variadic)
1575 init_frame (file, STACK_POINTER_REGNUM,
1576 UNITS_PER_WORD, crtl->outgoing_args_size);
1577
1578 /* Declare a local variable for the frame. Force its size to be
1579 DImode-compatible. */
1580 if (need_frameptr)
1581 init_frame (file, FRAME_POINTER_REGNUM, alignment,
1582 ROUND_UP (sz, GET_MODE_SIZE (DImode)));
1583 }
1584 else if (need_frameptr || cfun->machine->has_variadic || cfun->calls_alloca
1585 || (cfun->machine->has_simtreg && !crtl->is_leaf))
1586 init_softstack_frame (file, alignment, sz);
1587
1588 if (cfun->machine->has_simtreg)
1589 {
1590 unsigned HOST_WIDE_INT &simtsz = cfun->machine->simt_stack_size;
1591 unsigned HOST_WIDE_INT &align = cfun->machine->simt_stack_align;
1592 align = MAX (align, GET_MODE_SIZE (DImode));
1593 if (!crtl->is_leaf || cfun->calls_alloca)
1594 simtsz = HOST_WIDE_INT_M1U;
1595 if (simtsz == HOST_WIDE_INT_M1U)
1596 simtsz = nvptx_softstack_size;
1597 if (cfun->machine->has_softstack)
1598 simtsz += POINTER_SIZE / 8;
1599 simtsz = ROUND_UP (simtsz, GET_MODE_SIZE (DImode));
1600 if (align > GET_MODE_SIZE (DImode))
1601 simtsz += align - GET_MODE_SIZE (DImode);
1602 if (simtsz)
1603 fprintf (file, "\t.local.align 8 .b8 %%simtstack_ar["
1604 HOST_WIDE_INT_PRINT_DEC "];\n", simtsz);
1605 }
1606
1607 /* Restore the vector reduction partition register, if necessary.
1608 FIXME: Find out when and why this is necessary, and fix it. */
1609 if (cfun->machine->red_partition)
1610 regno_reg_rtx[REGNO (cfun->machine->red_partition)]
1611 = cfun->machine->red_partition;
1612
1613 /* Declare the pseudos we have as ptx registers. */
1614 int maxregs = max_reg_num ();
1615 for (int i = LAST_VIRTUAL_REGISTER + 1; i < maxregs; i++)
1616 {
1617 if (regno_reg_rtx[i] != const0_rtx)
1618 {
1619 machine_mode mode = PSEUDO_REGNO_MODE (i);
1620 machine_mode split = maybe_split_mode (mode);
1621
1622 if (split_mode_p (mode))
1623 mode = split;
1624 fprintf (file, "\t.reg%s ", nvptx_ptx_type_from_mode (mode, true));
1625 output_reg (file, i, split, -2);
1626 fprintf (file, ";\n");
1627 }
1628 }
1629
1630 /* Emit axis predicates. */
1631 if (cfun->machine->axis_predicate[0])
1632 nvptx_init_axis_predicate (file,
1633 REGNO (cfun->machine->axis_predicate[0]), "y");
1634 if (cfun->machine->axis_predicate[1])
1635 nvptx_init_axis_predicate (file,
1636 REGNO (cfun->machine->axis_predicate[1]), "x");
1637 if (cfun->machine->unisimt_predicate
1638 || (cfun->machine->has_simtreg && !crtl->is_leaf))
1639 nvptx_init_unisimt_predicate (file);
1640 if (cfun->machine->bcast_partition || cfun->machine->sync_bar)
1641 nvptx_init_oacc_workers (file);
1642 }
1643
1644 /* Output code for switching uniform-simt state. ENTERING indicates whether
1645 we are entering or leaving non-uniform execution region. */
1646
1647 static void
1648 nvptx_output_unisimt_switch (FILE *file, bool entering)
1649 {
1650 if (crtl->is_leaf && !cfun->machine->unisimt_predicate)
1651 return;
1652 fprintf (file, "\t{\n");
1653 fprintf (file, "\t\t.reg.u32 %%ustmp2;\n");
1654 fprintf (file, "\t\tmov.u32 %%ustmp2, %d;\n", entering ? -1 : 0);
1655 if (cfun->machine->unisimt_outside_simt_predicate)
1656 {
1657 int pred_outside_simt
1658 = REGNO (cfun->machine->unisimt_outside_simt_predicate);
1659 fprintf (file, "\t\tmov.pred %%r%d, %d;\n", pred_outside_simt,
1660 entering ? 0 : 1);
1661 }
1662 if (!crtl->is_leaf)
1663 {
1664 int loc = REGNO (cfun->machine->unisimt_location);
1665 fprintf (file, "\t\tst.shared.u32 [%%r%d], %%ustmp2;\n", loc);
1666 }
1667 if (cfun->machine->unisimt_predicate)
1668 {
1669 int master = REGNO (cfun->machine->unisimt_master);
1670 int pred = REGNO (cfun->machine->unisimt_predicate);
1671 fprintf (file, "\t\tmov.u32 %%ustmp2, %%laneid;\n");
1672 fprintf (file, "\t\tmov.u32 %%r%d, %s;\n",
1673 master, entering ? "%ustmp2" : "0");
1674 fprintf (file, "\t\tsetp.eq.u32 %%r%d, %%r%d, %%ustmp2;\n", pred, master);
1675 }
1676 fprintf (file, "\t}\n");
1677 }
1678
1679 /* Output code for allocating per-lane storage and switching soft-stack pointer.
1680 ENTERING indicates whether we are entering or leaving non-uniform execution.
1681 PTR is the register pointing to allocated storage, it is assigned to on
1682 entering and used to restore state on leaving. SIZE and ALIGN are used only
1683 on entering. */
1684
1685 static void
1686 nvptx_output_softstack_switch (FILE *file, bool entering,
1687 rtx ptr, rtx size, rtx align)
1688 {
1689 gcc_assert (REG_P (ptr) && !HARD_REGISTER_P (ptr));
1690 if (crtl->is_leaf && !cfun->machine->simt_stack_size)
1691 return;
1692 int bits = POINTER_SIZE, regno = REGNO (ptr);
1693 fprintf (file, "\t{\n");
1694 if (entering)
1695 {
1696 fprintf (file, "\t\tcvta.local.u%d %%r%d, %%simtstack_ar + "
1697 HOST_WIDE_INT_PRINT_DEC ";\n", bits, regno,
1698 cfun->machine->simt_stack_size);
1699 fprintf (file, "\t\tsub.u%d %%r%d, %%r%d, ", bits, regno, regno);
1700 if (CONST_INT_P (size))
1701 fprintf (file, HOST_WIDE_INT_PRINT_DEC,
1702 ROUND_UP (UINTVAL (size), GET_MODE_SIZE (DImode)));
1703 else
1704 output_reg (file, REGNO (size), VOIDmode);
1705 fputs (";\n", file);
1706 if (!CONST_INT_P (size) || UINTVAL (align) > GET_MODE_SIZE (DImode))
1707 fprintf (file,
1708 "\t\tand.b%d %%r%d, %%r%d, -" HOST_WIDE_INT_PRINT_DEC ";\n",
1709 bits, regno, regno, UINTVAL (align));
1710 }
1711 if (cfun->machine->has_softstack)
1712 {
1713 const char *reg_stack = reg_names[STACK_POINTER_REGNUM];
1714 if (entering)
1715 {
1716 fprintf (file, "\t\tst.u%d [%%r%d + -%d], %s;\n",
1717 bits, regno, bits / 8, reg_stack);
1718 fprintf (file, "\t\tsub.u%d %s, %%r%d, %d;\n",
1719 bits, reg_stack, regno, bits / 8);
1720 }
1721 else
1722 {
1723 fprintf (file, "\t\tld.u%d %s, [%%r%d + -%d];\n",
1724 bits, reg_stack, regno, bits / 8);
1725 }
1726 nvptx_output_set_softstack (REGNO (stack_pointer_rtx));
1727 }
1728 fprintf (file, "\t}\n");
1729 }
1730
1731 /* Output code to enter non-uniform execution region. DEST is a register
1732 to hold a per-lane allocation given by SIZE and ALIGN. */
1733
1734 const char *
1735 nvptx_output_simt_enter (rtx dest, rtx size, rtx align)
1736 {
1737 nvptx_output_unisimt_switch (asm_out_file, true);
1738 nvptx_output_softstack_switch (asm_out_file, true, dest, size, align);
1739 return "";
1740 }
1741
1742 /* Output code to leave non-uniform execution region. SRC is the register
1743 holding per-lane storage previously allocated by omp_simt_enter insn. */
1744
1745 const char *
1746 nvptx_output_simt_exit (rtx src)
1747 {
1748 nvptx_output_unisimt_switch (asm_out_file, false);
1749 nvptx_output_softstack_switch (asm_out_file, false, src, NULL_RTX, NULL_RTX);
1750 return "";
1751 }
1752
1753 /* Output instruction that sets soft stack pointer in shared memory to the
1754 value in register given by SRC_REGNO. */
1755
1756 const char *
1757 nvptx_output_set_softstack (unsigned src_regno)
1758 {
1759 if (cfun->machine->has_softstack && !crtl->is_leaf)
1760 {
1761 fprintf (asm_out_file, "\tst.shared.u%d\t[%s], ",
1762 POINTER_SIZE, reg_names[SOFTSTACK_SLOT_REGNUM]);
1763 output_reg (asm_out_file, src_regno, VOIDmode);
1764 fprintf (asm_out_file, ";\n");
1765 }
1766 return "";
1767 }
1768
1769 /* Output a fake PTX 'alloca'. */
1770
1771 const char *
1772 nvptx_output_fake_ptx_alloca (void)
1773 {
1774 #define FAKE_PTX_ALLOCA_NAME "__GCC_nvptx__PTX_alloca_not_supported"
1775 static tree decl;
1776 if (!decl)
1777 {
1778 tree alloca_type = TREE_TYPE (builtin_decl_explicit (BUILT_IN_ALLOCA));
1779 decl = build_decl (UNKNOWN_LOCATION, FUNCTION_DECL,
1780 get_identifier (FAKE_PTX_ALLOCA_NAME), alloca_type);
1781 DECL_EXTERNAL (decl) = 1;
1782 TREE_PUBLIC (decl) = 1;
1783 nvptx_record_needed_fndecl (decl);
1784 }
1785 return "\tcall\t(%0), " FAKE_PTX_ALLOCA_NAME ", (%1);";
1786 #undef FAKE_PTX_ALLOCA_NAME
1787 }
1788
1789 /* Output a return instruction. Also copy the return value to its outgoing
1790 location. */
1791
1792 const char *
1793 nvptx_output_return (void)
1794 {
1795 machine_mode mode = (machine_mode)cfun->machine->return_mode;
1796
1797 if (mode != VOIDmode)
1798 fprintf (asm_out_file, "\tst.param%s\t[%s_out], %s;\n",
1799 nvptx_ptx_type_from_mode (mode, false),
1800 reg_names[NVPTX_RETURN_REGNUM],
1801 reg_names[NVPTX_RETURN_REGNUM]);
1802
1803 return "ret;";
1804 }
1805
1806 /* Terminate a function by writing a closing brace to FILE. */
1807
1808 void
1809 nvptx_function_end (FILE *file)
1810 {
1811 fprintf (file, "}\n");
1812 }
1813
1814 /* Decide whether we can make a sibling call to a function. For ptx, we
1815 can't. */
1816
1817 static bool
1818 nvptx_function_ok_for_sibcall (tree, tree)
1819 {
1820 return false;
1821 }
1822
1823 /* Return Dynamic ReAlignment Pointer RTX. For PTX there isn't any. */
1824
1825 static rtx
1826 nvptx_get_drap_rtx (void)
1827 {
1828 if (stack_realign_drap)
1829 return arg_pointer_rtx;
1830 return NULL_RTX;
1831 }
1832
1833 /* Implement the TARGET_CALL_ARGS hook. Record information about one
1834 argument to the next call. */
1835
1836 static void
1837 nvptx_call_args (cumulative_args_t, rtx arg, tree fntype)
1838 {
1839 if (!cfun->machine->doing_call)
1840 {
1841 cfun->machine->doing_call = true;
1842 cfun->machine->is_variadic = false;
1843 cfun->machine->num_args = 0;
1844
1845 if (fntype && stdarg_p (fntype))
1846 {
1847 cfun->machine->is_variadic = true;
1848 cfun->machine->has_variadic = true;
1849 cfun->machine->num_args++;
1850 }
1851 }
1852
1853 if (REG_P (arg) && arg != pc_rtx)
1854 {
1855 cfun->machine->num_args++;
1856 cfun->machine->call_args = alloc_EXPR_LIST (VOIDmode, arg,
1857 cfun->machine->call_args);
1858 }
1859 }
1860
1861 /* Implement the corresponding END_CALL_ARGS hook. Clear and free the
1862 information we recorded. */
1863
1864 static void
1865 nvptx_end_call_args (cumulative_args_t)
1866 {
1867 cfun->machine->doing_call = false;
1868 free_EXPR_LIST_list (&cfun->machine->call_args);
1869 }
1870
1871 /* Emit the sequence for a call to ADDRESS, setting RETVAL. Keep
1872 track of whether calls involving static chains or varargs were seen
1873 in the current function.
1874 For libcalls, maintain a hash table of decls we have seen, and
1875 record a function decl for later when encountering a new one. */
1876
1877 void
1878 nvptx_expand_call (rtx retval, rtx address)
1879 {
1880 rtx callee = XEXP (address, 0);
1881 rtx varargs = NULL_RTX;
1882 unsigned parallel = 0;
1883
1884 if (!call_insn_operand (callee, Pmode))
1885 {
1886 callee = force_reg (Pmode, callee);
1887 address = change_address (address, QImode, callee);
1888 }
1889
1890 if (GET_CODE (callee) == SYMBOL_REF)
1891 {
1892 tree decl = SYMBOL_REF_DECL (callee);
1893 if (decl != NULL_TREE)
1894 {
1895 if (DECL_STATIC_CHAIN (decl))
1896 cfun->machine->has_chain = true;
1897
1898 tree attr = oacc_get_fn_attrib (decl);
1899 if (attr)
1900 {
1901 tree dims = TREE_VALUE (attr);
1902
1903 parallel = GOMP_DIM_MASK (GOMP_DIM_MAX) - 1;
1904 for (int ix = 0; ix != GOMP_DIM_MAX; ix++)
1905 {
1906 if (TREE_PURPOSE (dims)
1907 && !integer_zerop (TREE_PURPOSE (dims)))
1908 break;
1909 /* Not on this axis. */
1910 parallel ^= GOMP_DIM_MASK (ix);
1911 dims = TREE_CHAIN (dims);
1912 }
1913 }
1914 }
1915 }
1916
1917 unsigned nargs = cfun->machine->num_args;
1918 if (cfun->machine->is_variadic)
1919 {
1920 varargs = gen_reg_rtx (Pmode);
1921 emit_move_insn (varargs, stack_pointer_rtx);
1922 }
1923
1924 rtvec vec = rtvec_alloc (nargs + 1);
1925 rtx pat = gen_rtx_PARALLEL (VOIDmode, vec);
1926 int vec_pos = 0;
1927
1928 rtx call = gen_rtx_CALL (VOIDmode, address, const0_rtx);
1929 rtx tmp_retval = retval;
1930 if (retval)
1931 {
1932 if (!nvptx_register_operand (retval, GET_MODE (retval)))
1933 tmp_retval = gen_reg_rtx (GET_MODE (retval));
1934 call = gen_rtx_SET (tmp_retval, call);
1935 }
1936 XVECEXP (pat, 0, vec_pos++) = call;
1937
1938 /* Construct the call insn, including a USE for each argument pseudo
1939 register. These will be used when printing the insn. */
1940 for (rtx arg = cfun->machine->call_args; arg; arg = XEXP (arg, 1))
1941 XVECEXP (pat, 0, vec_pos++) = gen_rtx_USE (VOIDmode, XEXP (arg, 0));
1942
1943 if (varargs)
1944 XVECEXP (pat, 0, vec_pos++) = gen_rtx_USE (VOIDmode, varargs);
1945
1946 gcc_assert (vec_pos == XVECLEN (pat, 0));
1947
1948 nvptx_emit_forking (parallel, true);
1949 emit_call_insn (pat);
1950 nvptx_emit_joining (parallel, true);
1951
1952 if (tmp_retval != retval)
1953 emit_move_insn (retval, tmp_retval);
1954 }
1955
1956 /* Emit a comparison COMPARE, and return the new test to be used in the
1957 jump. */
1958
1959 rtx
1960 nvptx_expand_compare (rtx compare)
1961 {
1962 rtx pred = gen_reg_rtx (BImode);
1963 rtx cmp = gen_rtx_fmt_ee (GET_CODE (compare), BImode,
1964 XEXP (compare, 0), XEXP (compare, 1));
1965 emit_insn (gen_rtx_SET (pred, cmp));
1966 return gen_rtx_NE (BImode, pred, const0_rtx);
1967 }
1968
1969 /* Expand the oacc fork & join primitive into ptx-required unspecs. */
1970
1971 void
1972 nvptx_expand_oacc_fork (unsigned mode)
1973 {
1974 nvptx_emit_forking (GOMP_DIM_MASK (mode), false);
1975 }
1976
1977 void
1978 nvptx_expand_oacc_join (unsigned mode)
1979 {
1980 nvptx_emit_joining (GOMP_DIM_MASK (mode), false);
1981 }
1982
1983 /* Generate instruction(s) to unpack a 64 bit object into 2 32 bit
1984 objects. */
1985
1986 static rtx
1987 nvptx_gen_unpack (rtx dst0, rtx dst1, rtx src)
1988 {
1989 rtx res;
1990
1991 switch (GET_MODE (src))
1992 {
1993 case E_DImode:
1994 res = gen_unpackdisi2 (dst0, dst1, src);
1995 break;
1996 case E_DFmode:
1997 res = gen_unpackdfsi2 (dst0, dst1, src);
1998 break;
1999 default: gcc_unreachable ();
2000 }
2001 return res;
2002 }
2003
2004 /* Generate instruction(s) to pack 2 32 bit objects into a 64 bit
2005 object. */
2006
2007 static rtx
2008 nvptx_gen_pack (rtx dst, rtx src0, rtx src1)
2009 {
2010 rtx res;
2011
2012 switch (GET_MODE (dst))
2013 {
2014 case E_DImode:
2015 res = gen_packsidi2 (dst, src0, src1);
2016 break;
2017 case E_DFmode:
2018 res = gen_packsidf2 (dst, src0, src1);
2019 break;
2020 default: gcc_unreachable ();
2021 }
2022 return res;
2023 }
2024
2025 /* Generate an instruction or sequence to broadcast register REG
2026 across the vectors of a single warp. */
2027
2028 rtx
2029 nvptx_gen_shuffle (rtx dst, rtx src, rtx idx, nvptx_shuffle_kind kind)
2030 {
2031 rtx res;
2032
2033 switch (GET_MODE (dst))
2034 {
2035 case E_DCmode:
2036 case E_CDImode:
2037 {
2038 gcc_assert (GET_CODE (dst) == CONCAT);
2039 gcc_assert (GET_CODE (src) == CONCAT);
2040 rtx dst_real = XEXP (dst, 0);
2041 rtx dst_imag = XEXP (dst, 1);
2042 rtx src_real = XEXP (src, 0);
2043 rtx src_imag = XEXP (src, 1);
2044
2045 start_sequence ();
2046 emit_insn (nvptx_gen_shuffle (dst_real, src_real, idx, kind));
2047 emit_insn (nvptx_gen_shuffle (dst_imag, src_imag, idx, kind));
2048 res = get_insns ();
2049 end_sequence ();
2050 }
2051 break;
2052 case E_SImode:
2053 res = gen_nvptx_shufflesi (dst, src, idx, GEN_INT (kind));
2054 break;
2055 case E_SFmode:
2056 res = gen_nvptx_shufflesf (dst, src, idx, GEN_INT (kind));
2057 break;
2058 case E_DImode:
2059 case E_DFmode:
2060 {
2061 rtx tmp0 = gen_reg_rtx (SImode);
2062 rtx tmp1 = gen_reg_rtx (SImode);
2063
2064 start_sequence ();
2065 emit_insn (nvptx_gen_unpack (tmp0, tmp1, src));
2066 emit_insn (nvptx_gen_shuffle (tmp0, tmp0, idx, kind));
2067 emit_insn (nvptx_gen_shuffle (tmp1, tmp1, idx, kind));
2068 emit_insn (nvptx_gen_pack (dst, tmp0, tmp1));
2069 res = get_insns ();
2070 end_sequence ();
2071 }
2072 break;
2073 case E_V2SImode:
2074 {
2075 rtx src0 = gen_rtx_SUBREG (SImode, src, 0);
2076 rtx src1 = gen_rtx_SUBREG (SImode, src, 4);
2077 rtx dst0 = gen_rtx_SUBREG (SImode, dst, 0);
2078 rtx dst1 = gen_rtx_SUBREG (SImode, dst, 4);
2079 rtx tmp0 = gen_reg_rtx (SImode);
2080 rtx tmp1 = gen_reg_rtx (SImode);
2081 start_sequence ();
2082 emit_insn (gen_movsi (tmp0, src0));
2083 emit_insn (gen_movsi (tmp1, src1));
2084 emit_insn (nvptx_gen_shuffle (tmp0, tmp0, idx, kind));
2085 emit_insn (nvptx_gen_shuffle (tmp1, tmp1, idx, kind));
2086 emit_insn (gen_movsi (dst0, tmp0));
2087 emit_insn (gen_movsi (dst1, tmp1));
2088 res = get_insns ();
2089 end_sequence ();
2090 }
2091 break;
2092 case E_V2DImode:
2093 {
2094 rtx src0 = gen_rtx_SUBREG (DImode, src, 0);
2095 rtx src1 = gen_rtx_SUBREG (DImode, src, 8);
2096 rtx dst0 = gen_rtx_SUBREG (DImode, dst, 0);
2097 rtx dst1 = gen_rtx_SUBREG (DImode, dst, 8);
2098 rtx tmp0 = gen_reg_rtx (DImode);
2099 rtx tmp1 = gen_reg_rtx (DImode);
2100 start_sequence ();
2101 emit_insn (gen_movdi (tmp0, src0));
2102 emit_insn (gen_movdi (tmp1, src1));
2103 emit_insn (nvptx_gen_shuffle (tmp0, tmp0, idx, kind));
2104 emit_insn (nvptx_gen_shuffle (tmp1, tmp1, idx, kind));
2105 emit_insn (gen_movdi (dst0, tmp0));
2106 emit_insn (gen_movdi (dst1, tmp1));
2107 res = get_insns ();
2108 end_sequence ();
2109 }
2110 break;
2111 case E_BImode:
2112 {
2113 rtx tmp = gen_reg_rtx (SImode);
2114
2115 start_sequence ();
2116 emit_insn (gen_sel_truesi (tmp, src, GEN_INT (1), const0_rtx));
2117 emit_insn (nvptx_gen_shuffle (tmp, tmp, idx, kind));
2118 emit_insn (gen_rtx_SET (dst, gen_rtx_NE (BImode, tmp, const0_rtx)));
2119 res = get_insns ();
2120 end_sequence ();
2121 }
2122 break;
2123 case E_QImode:
2124 case E_HImode:
2125 {
2126 rtx tmp = gen_reg_rtx (SImode);
2127
2128 start_sequence ();
2129 emit_insn (gen_rtx_SET (tmp, gen_rtx_fmt_e (ZERO_EXTEND, SImode, src)));
2130 emit_insn (nvptx_gen_shuffle (tmp, tmp, idx, kind));
2131 emit_insn (gen_rtx_SET (dst, gen_rtx_fmt_e (TRUNCATE, GET_MODE (dst),
2132 tmp)));
2133 res = get_insns ();
2134 end_sequence ();
2135 }
2136 break;
2137
2138 default:
2139 gcc_unreachable ();
2140 }
2141 return res;
2142 }
2143
2144 /* Generate an instruction or sequence to broadcast register REG
2145 across the vectors of a single warp. */
2146
2147 static rtx
2148 nvptx_gen_warp_bcast (rtx reg)
2149 {
2150 return nvptx_gen_shuffle (reg, reg, const0_rtx, SHUFFLE_IDX);
2151 }
2152
2153 /* Structure used when generating a worker-level spill or fill. */
2154
2155 struct broadcast_data_t
2156 {
2157 rtx base; /* Register holding base addr of buffer. */
2158 rtx ptr; /* Iteration var, if needed. */
2159 unsigned offset; /* Offset into worker buffer. */
2160 };
2161
2162 /* Direction of the spill/fill and looping setup/teardown indicator. */
2163
2164 enum propagate_mask
2165 {
2166 PM_read = 1 << 0,
2167 PM_write = 1 << 1,
2168 PM_loop_begin = 1 << 2,
2169 PM_loop_end = 1 << 3,
2170
2171 PM_read_write = PM_read | PM_write
2172 };
2173
2174 /* Generate instruction(s) to spill or fill register REG to/from the
2175 worker broadcast array. PM indicates what is to be done, REP
2176 how many loop iterations will be executed (0 for not a loop). */
2177
2178 static rtx
2179 nvptx_gen_shared_bcast (rtx reg, propagate_mask pm, unsigned rep,
2180 broadcast_data_t *data, bool vector)
2181 {
2182 rtx res;
2183 machine_mode mode = GET_MODE (reg);
2184
2185 switch (mode)
2186 {
2187 case E_BImode:
2188 {
2189 rtx tmp = gen_reg_rtx (SImode);
2190
2191 start_sequence ();
2192 if (pm & PM_read)
2193 emit_insn (gen_sel_truesi (tmp, reg, GEN_INT (1), const0_rtx));
2194 emit_insn (nvptx_gen_shared_bcast (tmp, pm, rep, data, vector));
2195 if (pm & PM_write)
2196 emit_insn (gen_rtx_SET (reg, gen_rtx_NE (BImode, tmp, const0_rtx)));
2197 res = get_insns ();
2198 end_sequence ();
2199 }
2200 break;
2201
2202 default:
2203 {
2204 rtx addr = data->ptr;
2205
2206 if (!addr)
2207 {
2208 unsigned align = GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT;
2209
2210 oacc_bcast_align = MAX (oacc_bcast_align, align);
2211 data->offset = ROUND_UP (data->offset, align);
2212 addr = data->base;
2213 gcc_assert (data->base != NULL);
2214 if (data->offset)
2215 addr = gen_rtx_PLUS (Pmode, addr, GEN_INT (data->offset));
2216 }
2217
2218 addr = gen_rtx_MEM (mode, addr);
2219 if (pm == PM_read)
2220 res = gen_rtx_SET (addr, reg);
2221 else if (pm == PM_write)
2222 res = gen_rtx_SET (reg, addr);
2223 else
2224 gcc_unreachable ();
2225
2226 if (data->ptr)
2227 {
2228 /* We're using a ptr, increment it. */
2229 start_sequence ();
2230
2231 emit_insn (res);
2232 emit_insn (gen_adddi3 (data->ptr, data->ptr,
2233 GEN_INT (GET_MODE_SIZE (GET_MODE (reg)))));
2234 res = get_insns ();
2235 end_sequence ();
2236 }
2237 else
2238 rep = 1;
2239 data->offset += rep * GET_MODE_SIZE (GET_MODE (reg));
2240 }
2241 break;
2242 }
2243 return res;
2244 }
2245
2246 /* Returns true if X is a valid address for use in a memory reference. */
2247
2248 static bool
2249 nvptx_legitimate_address_p (machine_mode, rtx x, bool, code_helper)
2250 {
2251 enum rtx_code code = GET_CODE (x);
2252
2253 switch (code)
2254 {
2255 case REG:
2256 return true;
2257
2258 case PLUS:
2259 if (REG_P (XEXP (x, 0)) && CONST_INT_P (XEXP (x, 1)))
2260 return true;
2261 return false;
2262
2263 case CONST:
2264 case SYMBOL_REF:
2265 case LABEL_REF:
2266 return true;
2267
2268 default:
2269 return false;
2270 }
2271 }
2272
2273 /* Machinery to output constant initializers. When beginning an
2274 initializer, we decide on a fragment size (which is visible in ptx
2275 in the type used), and then all initializer data is buffered until
2276 a fragment is filled and ready to be written out. */
2277
2278 static struct
2279 {
2280 unsigned HOST_WIDE_INT mask; /* Mask for storing fragment. */
2281 unsigned HOST_WIDE_INT val; /* Current fragment value. */
2282 unsigned HOST_WIDE_INT remaining; /* Remaining bytes to be written
2283 out. */
2284 unsigned size; /* Fragment size to accumulate. */
2285 unsigned offset; /* Offset within current fragment. */
2286 bool active; /* Whether this machinery is active. */
2287 bool started; /* Whether we've output any initializer. */
2288 } init_frag;
2289
2290 /* The current fragment is full, write it out. SYM may provide a
2291 symbolic reference we should output, in which case the fragment
2292 value is the addend. */
2293
2294 static void
2295 output_init_frag (rtx sym)
2296 {
2297 gcc_checking_assert (init_frag.active);
2298
2299 fprintf (asm_out_file, init_frag.started ? ", " : " = { ");
2300 unsigned HOST_WIDE_INT val = init_frag.val;
2301
2302 init_frag.started = true;
2303 init_frag.val = 0;
2304 init_frag.offset = 0;
2305 init_frag.remaining--;
2306
2307 if (sym)
2308 {
2309 bool function = (SYMBOL_REF_DECL (sym)
2310 && (TREE_CODE (SYMBOL_REF_DECL (sym)) == FUNCTION_DECL));
2311 if (!function)
2312 fprintf (asm_out_file, "generic(");
2313 output_address (VOIDmode, sym);
2314 if (!function)
2315 fprintf (asm_out_file, ")");
2316 if (val)
2317 fprintf (asm_out_file, " + ");
2318 }
2319
2320 if (!sym || val)
2321 fprintf (asm_out_file, HOST_WIDE_INT_PRINT_DEC, val);
2322 }
2323
2324 /* Add value VAL of size SIZE to the data we're emitting, and keep
2325 writing out chunks as they fill up. */
2326
2327 static void
2328 nvptx_assemble_value (unsigned HOST_WIDE_INT val, unsigned size)
2329 {
2330 gcc_checking_assert (init_frag.active);
2331
2332 bool negative_p
2333 = val & (HOST_WIDE_INT_1U << (HOST_BITS_PER_WIDE_INT - 1));
2334
2335 /* Avoid undefined behaviour. */
2336 if (size * BITS_PER_UNIT < HOST_BITS_PER_WIDE_INT)
2337 val &= (HOST_WIDE_INT_1U << (size * BITS_PER_UNIT)) - 1;
2338
2339 for (unsigned part = 0; size; size -= part)
2340 {
2341 if (part * BITS_PER_UNIT == HOST_BITS_PER_WIDE_INT)
2342 /* Avoid undefined behaviour. */
2343 val = negative_p ? -1 : 0;
2344 else
2345 val >>= (part * BITS_PER_UNIT);
2346 part = init_frag.size - init_frag.offset;
2347 part = MIN (part, size);
2348
2349 unsigned HOST_WIDE_INT partial
2350 = val << (init_frag.offset * BITS_PER_UNIT);
2351 init_frag.val |= partial & init_frag.mask;
2352 init_frag.offset += part;
2353
2354 if (init_frag.offset == init_frag.size)
2355 output_init_frag (NULL);
2356 }
2357 }
2358
2359 /* Target hook for assembling integer object X of size SIZE. */
2360
2361 static bool
2362 nvptx_assemble_integer (rtx x, unsigned int size, int ARG_UNUSED (aligned_p))
2363 {
2364 if (in_section == exception_section)
2365 {
2366 gcc_checking_assert (!init_frag.active);
2367 /* Just use the default machinery; it's not getting used, anyway. */
2368 bool ok = default_assemble_integer (x, size, aligned_p);
2369 /* ..., but a few cases need special handling. */
2370 switch (GET_CODE (x))
2371 {
2372 case SYMBOL_REF:
2373 /* The default machinery won't work: we don't define the necessary
2374 operations; don't use them outside of this. */
2375 gcc_checking_assert (!ok);
2376 {
2377 /* Just emit something; it's not getting used, anyway. */
2378 const char *op = "\t.symbol_ref\t";
2379 ok = (assemble_integer_with_op (op, x), true);
2380 }
2381 break;
2382
2383 default:
2384 break;
2385 }
2386 return ok;
2387 }
2388
2389 gcc_checking_assert (init_frag.active);
2390
2391 HOST_WIDE_INT val = 0;
2392
2393 switch (GET_CODE (x))
2394 {
2395 default:
2396 /* Let the generic machinery figure it out, usually for a
2397 CONST_WIDE_INT. */
2398 return false;
2399
2400 case CONST_INT:
2401 nvptx_assemble_value (INTVAL (x), size);
2402 break;
2403
2404 case CONST:
2405 x = XEXP (x, 0);
2406 gcc_assert (GET_CODE (x) == PLUS);
2407 val = INTVAL (XEXP (x, 1));
2408 x = XEXP (x, 0);
2409 gcc_assert (GET_CODE (x) == SYMBOL_REF);
2410 gcc_fallthrough (); /* FALLTHROUGH */
2411
2412 case SYMBOL_REF:
2413 gcc_assert (size == init_frag.size);
2414 if (init_frag.offset)
2415 sorry ("cannot emit unaligned pointers in ptx assembly");
2416
2417 nvptx_maybe_record_fnsym (x);
2418 init_frag.val = val;
2419 output_init_frag (x);
2420 break;
2421 }
2422
2423 return true;
2424 }
2425
2426 /* Output SIZE zero bytes. We ignore the FILE argument since the
2427 functions we're calling to perform the output just use
2428 asm_out_file. */
2429
2430 void
2431 nvptx_output_skip (FILE *, unsigned HOST_WIDE_INT size)
2432 {
2433 gcc_checking_assert (in_section == data_section
2434 || in_section == text_section);
2435
2436 if (!init_frag.active)
2437 /* We're in the 'data_section' or 'text_section', outside of an
2438 initializer context ('init_frag'). There's nothing to do here:
2439 in PTX, there's no concept of an assembler's "location counter",
2440 "current address", "dot symbol" ('.') that might need padding or
2441 aligning. */
2442 return;
2443
2444 /* Finish the current fragment, if it's started. */
2445 if (init_frag.offset)
2446 {
2447 unsigned part = init_frag.size - init_frag.offset;
2448 part = MIN (part, (unsigned)size);
2449 size -= part;
2450 nvptx_assemble_value (0, part);
2451 }
2452
2453 /* If this skip doesn't terminate the initializer, write as many
2454 remaining pieces as possible directly. */
2455 if (size < init_frag.remaining * init_frag.size)
2456 {
2457 while (size >= init_frag.size)
2458 {
2459 size -= init_frag.size;
2460 output_init_frag (NULL_RTX);
2461 }
2462 if (size)
2463 nvptx_assemble_value (0, size);
2464 }
2465 else
2466 /* Otherwise, we don't have to do anything: this skip terminates the
2467 initializer; we skip either the full ('!init_frag.started' case) or the
2468 remainder ('init_frag.started' case) of the initializer (that is, either
2469 no or incomplete initializer). */
2470 gcc_checking_assert (size == init_frag.remaining * init_frag.size);
2471 }
2472
2473 /* Output a string STR with length SIZE. As in nvptx_output_skip we
2474 ignore the FILE arg. */
2475
2476 void
2477 nvptx_output_ascii (FILE *, const char *str, unsigned HOST_WIDE_INT size)
2478 {
2479 for (unsigned HOST_WIDE_INT i = 0; i < size; i++)
2480 nvptx_assemble_value (str[i], 1);
2481 }
2482
2483 /* Return true if TYPE is a record type where the last field is an array without
2484 given dimension. */
2485
2486 static bool
2487 flexible_array_member_type_p (const_tree type)
2488 {
2489 if (TREE_CODE (type) != RECORD_TYPE)
2490 return false;
2491
2492 const_tree last_field = NULL_TREE;
2493 for (const_tree f = TYPE_FIELDS (type); f; f = TREE_CHAIN (f))
2494 last_field = f;
2495
2496 if (!last_field)
2497 return false;
2498
2499 const_tree last_field_type = TREE_TYPE (last_field);
2500 if (TREE_CODE (last_field_type) != ARRAY_TYPE)
2501 return false;
2502
2503 return (! TYPE_DOMAIN (last_field_type)
2504 || ! TYPE_MAX_VALUE (TYPE_DOMAIN (last_field_type)));
2505 }
2506
2507 /* Emit a PTX variable decl and prepare for emission of its
2508 initializer. NAME is the symbol name and SETION the PTX data
2509 area. The type is TYPE, object size SIZE and alignment is ALIGN.
2510 The caller has already emitted any indentation and linkage
2511 specifier. It is responsible for any initializer, terminating ;
2512 and newline. SIZE is in bytes, ALIGN is in bits -- confusingly
2513 this is the opposite way round that PTX wants them! */
2514
2515 static void
2516 nvptx_assemble_decl_begin (FILE *file, const char *name, const char *section,
2517 const_tree type, HOST_WIDE_INT size, unsigned align,
2518 bool undefined = false)
2519 {
2520 gcc_checking_assert (!init_frag.active);
2521
2522 bool atype = (TREE_CODE (type) == ARRAY_TYPE)
2523 && (TYPE_DOMAIN (type) == NULL_TREE);
2524
2525 if (undefined && flexible_array_member_type_p (type))
2526 {
2527 size = 0;
2528 atype = true;
2529 }
2530
2531 while (TREE_CODE (type) == ARRAY_TYPE)
2532 type = TREE_TYPE (type);
2533
2534 if (TREE_CODE (type) == VECTOR_TYPE
2535 || TREE_CODE (type) == COMPLEX_TYPE)
2536 /* Neither vector nor complex types can contain the other. */
2537 type = TREE_TYPE (type);
2538
2539 unsigned HOST_WIDE_INT elt_size = int_size_in_bytes (type);
2540
2541 /* Largest mode we're prepared to accept. For BLKmode types we
2542 don't know if it'll contain pointer constants, so have to choose
2543 pointer size, otherwise we can choose DImode. */
2544 machine_mode elt_mode = TYPE_MODE (type) == BLKmode ? Pmode : DImode;
2545
2546 elt_size |= GET_MODE_SIZE (elt_mode);
2547 elt_size &= -elt_size; /* Extract LSB set. */
2548
2549 init_frag.active = true;
2550
2551 init_frag.size = elt_size;
2552 /* Avoid undefined shift behavior by using '2'. */
2553 init_frag.mask = ((unsigned HOST_WIDE_INT)2
2554 << (elt_size * BITS_PER_UNIT - 1)) - 1;
2555 init_frag.val = 0;
2556 init_frag.offset = 0;
2557 init_frag.started = false;
2558 /* Size might not be a multiple of elt size, if there's an
2559 initialized trailing struct array with smaller type than
2560 elt_size. */
2561 init_frag.remaining = (size + elt_size - 1) / elt_size;
2562
2563 fprintf (file, "%s .align %d .u" HOST_WIDE_INT_PRINT_UNSIGNED " ",
2564 section, align / BITS_PER_UNIT,
2565 elt_size * BITS_PER_UNIT);
2566 assemble_name (file, name);
2567
2568 if (size)
2569 /* We make everything an array, to simplify any initialization
2570 emission. */
2571 fprintf (file, "[" HOST_WIDE_INT_PRINT_UNSIGNED "]", init_frag.remaining);
2572 else if (atype)
2573 fprintf (file, "[]");
2574 }
2575
2576 /* Called when the initializer for a decl has been completely output through
2577 combinations of the three functions above. */
2578
2579 static void
2580 nvptx_assemble_decl_end (void)
2581 {
2582 gcc_checking_assert (init_frag.active);
2583
2584 if (init_frag.offset)
2585 /* This can happen with a packed struct with trailing array member. */
2586 nvptx_assemble_value (0, init_frag.size - init_frag.offset);
2587 fprintf (asm_out_file, init_frag.started ? " };\n" : ";\n");
2588
2589 init_frag.active = false;
2590 }
2591
2592 /* Output an uninitialized common or file-scope variable. */
2593
2594 void
2595 nvptx_output_aligned_decl (FILE *file, const char *name,
2596 const_tree decl, HOST_WIDE_INT size, unsigned align)
2597 {
2598 write_var_marker (file, true, TREE_PUBLIC (decl), name);
2599
2600 /* If this is public, it is common. The nearest thing we have to
2601 common is weak. */
2602 fprintf (file, "\t%s", TREE_PUBLIC (decl) ? ".weak " : "");
2603
2604 nvptx_assemble_decl_begin (file, name, section_for_decl (decl),
2605 TREE_TYPE (decl), size, align);
2606 nvptx_assemble_decl_end ();
2607 }
2608
2609 /* Implement TARGET_ASM_DECLARE_CONSTANT_NAME. Begin the process of
2610 writing a constant variable EXP with NAME and SIZE and its
2611 initializer to FILE. */
2612
2613 static void
2614 nvptx_asm_declare_constant_name (FILE *file, const char *name,
2615 const_tree exp, HOST_WIDE_INT obj_size)
2616 {
2617 write_var_marker (file, true, false, name);
2618
2619 fprintf (file, "\t");
2620
2621 tree type = TREE_TYPE (exp);
2622 nvptx_assemble_decl_begin (file, name, ".global", type, obj_size,
2623 TYPE_ALIGN (type));
2624 }
2625
2626 /* Implement the ASM_DECLARE_OBJECT_NAME macro. Used to start writing
2627 a variable DECL with NAME to FILE. */
2628
2629 void
2630 nvptx_declare_object_name (FILE *file, const char *name, const_tree decl)
2631 {
2632 write_var_marker (file, true, TREE_PUBLIC (decl), name);
2633
2634 fprintf (file, "\t%s", (!TREE_PUBLIC (decl) ? ""
2635 : DECL_WEAK (decl) ? ".weak " : ".visible "));
2636
2637 tree type = TREE_TYPE (decl);
2638 HOST_WIDE_INT obj_size = tree_to_shwi (DECL_SIZE_UNIT (decl));
2639 nvptx_assemble_decl_begin (file, name, section_for_decl (decl),
2640 type, obj_size, DECL_ALIGN (decl));
2641 }
2642
2643 /* Implement TARGET_ASM_GLOBALIZE_LABEL by doing nothing. */
2644
2645 static void
2646 nvptx_globalize_label (FILE *, const char *)
2647 {
2648 }
2649
2650 /* Implement TARGET_ASM_ASSEMBLE_UNDEFINED_DECL. Write an extern
2651 declaration only for variable DECL with NAME to FILE. */
2652
2653 static void
2654 nvptx_assemble_undefined_decl (FILE *file, const char *name, const_tree decl)
2655 {
2656 /* The middle end can place constant pool decls into the varpool as
2657 undefined. Until that is fixed, catch the problem here. */
2658 if (DECL_IN_CONSTANT_POOL (decl))
2659 return;
2660
2661 /* We support weak defintions, and hence have the right
2662 ASM_WEAKEN_DECL definition. Diagnose the problem here. */
2663 if (DECL_WEAK (decl))
2664 error_at (DECL_SOURCE_LOCATION (decl),
2665 "PTX does not support weak declarations"
2666 " (only weak definitions)");
2667 write_var_marker (file, false, TREE_PUBLIC (decl), name);
2668
2669 fprintf (file, "\t.extern ");
2670 tree size = DECL_SIZE_UNIT (decl);
2671 nvptx_assemble_decl_begin (file, name, section_for_decl (decl),
2672 TREE_TYPE (decl), size ? tree_to_shwi (size) : 0,
2673 DECL_ALIGN (decl), true);
2674 nvptx_assemble_decl_end ();
2675 }
2676
2677 /* Output a pattern for a move instruction. */
2678
2679 const char *
2680 nvptx_output_mov_insn (rtx dst, rtx src)
2681 {
2682 machine_mode dst_mode = GET_MODE (dst);
2683 machine_mode src_mode = GET_MODE (src);
2684 machine_mode dst_inner = (GET_CODE (dst) == SUBREG
2685 ? GET_MODE (XEXP (dst, 0)) : dst_mode);
2686 machine_mode src_inner = (GET_CODE (src) == SUBREG
2687 ? GET_MODE (XEXP (src, 0)) : dst_mode);
2688
2689 rtx sym = src;
2690 if (GET_CODE (sym) == CONST)
2691 sym = XEXP (XEXP (sym, 0), 0);
2692 if (SYMBOL_REF_P (sym))
2693 {
2694 if (SYMBOL_DATA_AREA (sym) != DATA_AREA_GENERIC)
2695 return "%.\tcvta%D1%t0\t%0, %1;";
2696 nvptx_maybe_record_fnsym (sym);
2697 }
2698
2699 if (src_inner == dst_inner)
2700 return "%.\tmov%t0\t%0, %1;";
2701
2702 if (CONSTANT_P (src))
2703 return (GET_MODE_CLASS (dst_inner) == MODE_INT
2704 && GET_MODE_CLASS (src_inner) != MODE_FLOAT
2705 ? "%.\tmov%t0\t%0, %1;" : "%.\tmov.b%T0\t%0, %1;");
2706
2707 if (GET_MODE_SIZE (dst_inner) == GET_MODE_SIZE (src_inner))
2708 {
2709 if (GET_MODE_BITSIZE (dst_mode) == 128
2710 && GET_MODE_BITSIZE (src_mode) == 128)
2711 {
2712 /* mov.b128 is not supported. */
2713 if (dst_inner == V2DImode && src_inner == TImode)
2714 return "%.\tmov.u64\t%0.x, %L1;\n\t%.\tmov.u64\t%0.y, %H1;";
2715 else if (dst_inner == TImode && src_inner == V2DImode)
2716 return "%.\tmov.u64\t%L0, %1.x;\n\t%.\tmov.u64\t%H0, %1.y;";
2717
2718 gcc_unreachable ();
2719 }
2720 return "%.\tmov.b%T0\t%0, %1;";
2721 }
2722
2723 if (GET_MODE_BITSIZE (src_inner) == 128
2724 && GET_MODE_BITSIZE (src_mode) == 64)
2725 return "%.\tmov.b%T0\t%0, %1;";
2726
2727 return "%.\tcvt%t0%t1\t%0, %1;";
2728 }
2729
2730 /* Output a pre/post barrier for MEM_OPERAND according to MEMMODEL. */
2731
2732 static void
2733 nvptx_output_barrier (rtx *mem_operand, int memmodel, bool pre_p)
2734 {
2735 bool post_p = !pre_p;
2736
2737 switch (memmodel)
2738 {
2739 case MEMMODEL_RELAXED:
2740 return;
2741 case MEMMODEL_CONSUME:
2742 case MEMMODEL_ACQUIRE:
2743 case MEMMODEL_SYNC_ACQUIRE:
2744 if (post_p)
2745 break;
2746 return;
2747 case MEMMODEL_RELEASE:
2748 case MEMMODEL_SYNC_RELEASE:
2749 if (pre_p)
2750 break;
2751 return;
2752 case MEMMODEL_ACQ_REL:
2753 case MEMMODEL_SEQ_CST:
2754 case MEMMODEL_SYNC_SEQ_CST:
2755 if (pre_p || post_p)
2756 break;
2757 return;
2758 default:
2759 gcc_unreachable ();
2760 }
2761
2762 output_asm_insn ("%.\tmembar%B0;", mem_operand);
2763 }
2764
2765 const char *
2766 nvptx_output_atomic_insn (const char *asm_template, rtx *operands, int mem_pos,
2767 int memmodel_pos)
2768 {
2769 nvptx_output_barrier (&operands[mem_pos], INTVAL (operands[memmodel_pos]),
2770 true);
2771 output_asm_insn (asm_template, operands);
2772 nvptx_output_barrier (&operands[mem_pos], INTVAL (operands[memmodel_pos]),
2773 false);
2774 return "";
2775 }
2776
2777 static void nvptx_print_operand (FILE *, rtx, int);
2778
2779 /* Output INSN, which is a call to CALLEE with result RESULT. For ptx, this
2780 involves writing .param declarations and in/out copies into them. For
2781 indirect calls, also write the .callprototype. */
2782
2783 const char *
2784 nvptx_output_call_insn (rtx_insn *insn, rtx result, rtx callee)
2785 {
2786 char buf[16];
2787 static int labelno;
2788 bool needs_tgt = register_operand (callee, Pmode);
2789 rtx pat = PATTERN (insn);
2790 if (GET_CODE (pat) == COND_EXEC)
2791 pat = COND_EXEC_CODE (pat);
2792 int arg_end = XVECLEN (pat, 0);
2793 tree decl = NULL_TREE;
2794
2795 fprintf (asm_out_file, "\t{\n");
2796 if (result != NULL)
2797 fprintf (asm_out_file, "\t\t.param%s %s_in;\n",
2798 nvptx_ptx_type_from_mode (GET_MODE (result), false),
2799 reg_names[NVPTX_RETURN_REGNUM]);
2800
2801 /* Ensure we have a ptx declaration in the output if necessary. */
2802 if (GET_CODE (callee) == SYMBOL_REF)
2803 {
2804 decl = SYMBOL_REF_DECL (callee);
2805 if (!decl
2806 || (DECL_EXTERNAL (decl) && !TYPE_ARG_TYPES (TREE_TYPE (decl))))
2807 nvptx_record_libfunc (callee, result, pat);
2808 else if (DECL_EXTERNAL (decl))
2809 nvptx_record_fndecl (decl);
2810 }
2811
2812 if (needs_tgt)
2813 {
2814 ASM_GENERATE_INTERNAL_LABEL (buf, "LCT", labelno);
2815 labelno++;
2816 ASM_OUTPUT_LABEL (asm_out_file, buf);
2817 std::stringstream s;
2818 write_fn_proto_from_insn (s, NULL, result, pat);
2819 fputs (s.str().c_str(), asm_out_file);
2820 }
2821
2822 for (int argno = 1; argno < arg_end; argno++)
2823 {
2824 rtx t = XEXP (XVECEXP (pat, 0, argno), 0);
2825 machine_mode mode = GET_MODE (t);
2826 const char *ptx_type = nvptx_ptx_type_from_mode (mode, false);
2827
2828 /* Mode splitting has already been done. */
2829 fprintf (asm_out_file, "\t\t.param%s %%out_arg%d;\n"
2830 "\t\tst.param%s [%%out_arg%d], ",
2831 ptx_type, argno, ptx_type, argno);
2832 output_reg (asm_out_file, REGNO (t), VOIDmode);
2833 fprintf (asm_out_file, ";\n");
2834 }
2835
2836 /* The '.' stands for the call's predicate, if any. */
2837 nvptx_print_operand (asm_out_file, NULL_RTX, '.');
2838 fprintf (asm_out_file, "\t\tcall ");
2839 if (result != NULL_RTX)
2840 fprintf (asm_out_file, "(%s_in), ", reg_names[NVPTX_RETURN_REGNUM]);
2841
2842 if (decl)
2843 {
2844 char *replaced_dots = NULL;
2845 const char *name = get_fnname_from_decl (decl);
2846 const char *replacement = nvptx_name_replacement (name);
2847 if (replacement != name)
2848 name = replacement;
2849 else
2850 {
2851 replaced_dots = nvptx_replace_dot (name);
2852 if (replaced_dots)
2853 name = replaced_dots;
2854 }
2855 assemble_name (asm_out_file, name);
2856 if (replaced_dots)
2857 XDELETE (replaced_dots);
2858 }
2859 else
2860 output_address (VOIDmode, callee);
2861
2862 const char *open = "(";
2863 for (int argno = 1; argno < arg_end; argno++)
2864 {
2865 fprintf (asm_out_file, ", %s%%out_arg%d", open, argno);
2866 open = "";
2867 }
2868 if (decl && DECL_STATIC_CHAIN (decl))
2869 {
2870 fprintf (asm_out_file, ", %s%s", open, reg_names [STATIC_CHAIN_REGNUM]);
2871 open = "";
2872 }
2873 if (!open[0])
2874 fprintf (asm_out_file, ")");
2875
2876 if (needs_tgt)
2877 {
2878 fprintf (asm_out_file, ", ");
2879 assemble_name (asm_out_file, buf);
2880 }
2881 fprintf (asm_out_file, ";\n");
2882
2883 if (find_reg_note (insn, REG_NORETURN, NULL))
2884 {
2885 /* No return functions confuse the PTX JIT, as it doesn't realize
2886 the flow control barrier they imply. It can seg fault if it
2887 encounters what looks like an unexitable loop. Emit a trailing
2888 trap and exit, which it does grok. */
2889 fprintf (asm_out_file, "\t\ttrap; // (noreturn)\n");
2890 fprintf (asm_out_file, "\t\texit; // (noreturn)\n");
2891 }
2892
2893 if (result)
2894 {
2895 static char rval[sizeof ("\tld.param%%t0\t%%0, [%%%s_in];\n\t}") + 8];
2896
2897 if (!rval[0])
2898 /* We must escape the '%' that starts RETURN_REGNUM. */
2899 sprintf (rval, "\tld.param%%t0\t%%0, [%%%s_in];\n\t}",
2900 reg_names[NVPTX_RETURN_REGNUM]);
2901 return rval;
2902 }
2903
2904 return "}";
2905 }
2906
2907 /* Implement TARGET_PRINT_OPERAND_PUNCT_VALID_P. */
2908
2909 static bool
2910 nvptx_print_operand_punct_valid_p (unsigned char c)
2911 {
2912 return c == '.' || c== '#';
2913 }
2914
2915 /* Subroutine of nvptx_print_operand; used to print a memory reference X to FILE. */
2916
2917 static void
2918 nvptx_print_address_operand (FILE *file, rtx x, machine_mode)
2919 {
2920 rtx off;
2921 if (GET_CODE (x) == CONST)
2922 x = XEXP (x, 0);
2923 switch (GET_CODE (x))
2924 {
2925 case PLUS:
2926 off = XEXP (x, 1);
2927 output_address (VOIDmode, XEXP (x, 0));
2928 fprintf (file, "+");
2929 output_address (VOIDmode, off);
2930 break;
2931
2932 case SYMBOL_REF:
2933 case LABEL_REF:
2934 output_addr_const (file, x);
2935 break;
2936
2937 default:
2938 gcc_assert (GET_CODE (x) != MEM);
2939 nvptx_print_operand (file, x, 0);
2940 break;
2941 }
2942 }
2943
2944 /* Write assembly language output for the address ADDR to FILE. */
2945
2946 static void
2947 nvptx_print_operand_address (FILE *file, machine_mode mode, rtx addr)
2948 {
2949 nvptx_print_address_operand (file, addr, mode);
2950 }
2951
2952 static nvptx_data_area
2953 nvptx_mem_data_area (const_rtx x)
2954 {
2955 gcc_assert (GET_CODE (x) == MEM);
2956
2957 const_rtx addr = XEXP (x, 0);
2958 subrtx_iterator::array_type array;
2959 FOR_EACH_SUBRTX (iter, array, addr, ALL)
2960 if (SYMBOL_REF_P (*iter))
2961 return SYMBOL_DATA_AREA (*iter);
2962
2963 return DATA_AREA_GENERIC;
2964 }
2965
2966 bool
2967 nvptx_mem_maybe_shared_p (const_rtx x)
2968 {
2969 nvptx_data_area area = nvptx_mem_data_area (x);
2970 return area == DATA_AREA_SHARED || area == DATA_AREA_GENERIC;
2971 }
2972
2973 /* Print an operand, X, to FILE, with an optional modifier in CODE.
2974
2975 Meaning of CODE:
2976 . -- print the predicate for the instruction or an emptry string for an
2977 unconditional one.
2978 # -- print a rounding mode for the instruction
2979
2980 A -- print a data area for a MEM
2981 c -- print an opcode suffix for a comparison operator, including a type code
2982 D -- print a data area for a MEM operand
2983 S -- print a shuffle kind specified by CONST_INT
2984 t -- print a type opcode suffix, promoting QImode to 32 bits
2985 T -- print a type size in bits
2986 u -- print a type opcode suffix without promotions.
2987 p -- print a '!' for constant 0.
2988 x -- print a destination operand that may also be a bit bucket. */
2989
2990 static void
2991 nvptx_print_operand (FILE *file, rtx x, int code)
2992 {
2993 if (code == '.')
2994 {
2995 x = current_insn_predicate;
2996 if (x)
2997 {
2998 fputs ("@", file);
2999 if (GET_CODE (x) == EQ)
3000 fputs ("!", file);
3001 output_reg (file, REGNO (XEXP (x, 0)), VOIDmode);
3002 }
3003 return;
3004 }
3005 else if (code == '#')
3006 {
3007 fputs (".rn", file);
3008 return;
3009 }
3010
3011 enum rtx_code x_code = GET_CODE (x);
3012 machine_mode mode = GET_MODE (x);
3013
3014 switch (code)
3015 {
3016 case 'x':
3017 if (current_output_insn != NULL
3018 && find_reg_note (current_output_insn, REG_UNUSED, x) != NULL_RTX)
3019 {
3020 fputs ("_", file);
3021 return;
3022 }
3023 goto common;
3024 case 'B':
3025 if (SYMBOL_REF_P (XEXP (x, 0)))
3026 switch (SYMBOL_DATA_AREA (XEXP (x, 0)))
3027 {
3028 case DATA_AREA_GENERIC:
3029 /* Assume worst-case: global. */
3030 gcc_fallthrough (); /* FALLTHROUGH. */
3031 case DATA_AREA_GLOBAL:
3032 break;
3033 case DATA_AREA_SHARED:
3034 fputs (".cta", file);
3035 return;
3036 case DATA_AREA_LOCAL:
3037 case DATA_AREA_CONST:
3038 case DATA_AREA_PARAM:
3039 default:
3040 gcc_unreachable ();
3041 }
3042
3043 /* There are 2 cases where membar.sys differs from membar.gl:
3044 - host accesses global memory (f.i. systemwide atomics)
3045 - 2 or more devices are setup in peer-to-peer mode, and one
3046 peer can access global memory of other peer.
3047 Neither are currently supported by openMP/OpenACC on nvptx, but
3048 that could change, so we default to membar.sys. We could support
3049 this more optimally by adding DATA_AREA_SYS and then emitting
3050 .gl for DATA_AREA_GLOBAL and .sys for DATA_AREA_SYS. */
3051 fputs (".sys", file);
3052 return;
3053
3054 case 'A':
3055 x = XEXP (x, 0);
3056 gcc_fallthrough (); /* FALLTHROUGH. */
3057
3058 case 'D':
3059 if (GET_CODE (x) == CONST)
3060 x = XEXP (x, 0);
3061 if (GET_CODE (x) == PLUS)
3062 x = XEXP (x, 0);
3063
3064 if (GET_CODE (x) == SYMBOL_REF)
3065 fputs (section_for_sym (x), file);
3066 break;
3067
3068 case 't':
3069 case 'u':
3070 if (x_code == SUBREG)
3071 {
3072 machine_mode inner_mode = GET_MODE (SUBREG_REG (x));
3073 if (VECTOR_MODE_P (inner_mode)
3074 && (GET_MODE_SIZE (mode)
3075 <= GET_MODE_SIZE (GET_MODE_INNER (inner_mode))))
3076 mode = GET_MODE_INNER (inner_mode);
3077 else if (split_mode_p (inner_mode))
3078 mode = maybe_split_mode (inner_mode);
3079 else
3080 mode = inner_mode;
3081 }
3082 fprintf (file, "%s", nvptx_ptx_type_from_mode (mode, code == 't'));
3083 break;
3084
3085 case 'H':
3086 case 'L':
3087 {
3088 rtx inner_x = SUBREG_REG (x);
3089 machine_mode inner_mode = GET_MODE (inner_x);
3090 machine_mode split = maybe_split_mode (inner_mode);
3091
3092 output_reg (file, REGNO (inner_x), split,
3093 (code == 'H'
3094 ? GET_MODE_SIZE (inner_mode) / 2
3095 : 0));
3096 }
3097 break;
3098
3099 case 'S':
3100 {
3101 nvptx_shuffle_kind kind = (nvptx_shuffle_kind) UINTVAL (x);
3102 /* Same order as nvptx_shuffle_kind. */
3103 static const char *const kinds[] =
3104 {".up", ".down", ".bfly", ".idx"};
3105 fputs (kinds[kind], file);
3106 }
3107 break;
3108
3109 case 'T':
3110 fprintf (file, "%d", GET_MODE_BITSIZE (mode));
3111 break;
3112
3113 case 'j':
3114 fprintf (file, "@");
3115 goto common;
3116
3117 case 'J':
3118 fprintf (file, "@!");
3119 goto common;
3120
3121 case 'p':
3122 if (INTVAL (x) == 0)
3123 fprintf (file, "!");
3124 break;
3125
3126 case 'c':
3127 mode = GET_MODE (XEXP (x, 0));
3128 switch (x_code)
3129 {
3130 case EQ:
3131 fputs (".eq", file);
3132 break;
3133 case NE:
3134 if (FLOAT_MODE_P (mode))
3135 fputs (".neu", file);
3136 else
3137 fputs (".ne", file);
3138 break;
3139 case LE:
3140 case LEU:
3141 fputs (".le", file);
3142 break;
3143 case GE:
3144 case GEU:
3145 fputs (".ge", file);
3146 break;
3147 case LT:
3148 case LTU:
3149 fputs (".lt", file);
3150 break;
3151 case GT:
3152 case GTU:
3153 fputs (".gt", file);
3154 break;
3155 case LTGT:
3156 fputs (".ne", file);
3157 break;
3158 case UNEQ:
3159 fputs (".equ", file);
3160 break;
3161 case UNLE:
3162 fputs (".leu", file);
3163 break;
3164 case UNGE:
3165 fputs (".geu", file);
3166 break;
3167 case UNLT:
3168 fputs (".ltu", file);
3169 break;
3170 case UNGT:
3171 fputs (".gtu", file);
3172 break;
3173 case UNORDERED:
3174 fputs (".nan", file);
3175 break;
3176 case ORDERED:
3177 fputs (".num", file);
3178 break;
3179 default:
3180 gcc_unreachable ();
3181 }
3182 if (FLOAT_MODE_P (mode)
3183 || x_code == EQ || x_code == NE
3184 || x_code == GEU || x_code == GTU
3185 || x_code == LEU || x_code == LTU)
3186 fputs (nvptx_ptx_type_from_mode (mode, true), file);
3187 else
3188 fprintf (file, ".s%d", GET_MODE_BITSIZE (mode));
3189 break;
3190 default:
3191 common:
3192 switch (x_code)
3193 {
3194 case SUBREG:
3195 {
3196 rtx inner_x = SUBREG_REG (x);
3197 machine_mode inner_mode = GET_MODE (inner_x);
3198 machine_mode split = maybe_split_mode (inner_mode);
3199
3200 if (VECTOR_MODE_P (inner_mode)
3201 && (GET_MODE_SIZE (mode)
3202 <= GET_MODE_SIZE (GET_MODE_INNER (inner_mode))))
3203 {
3204 output_reg (file, REGNO (inner_x), VOIDmode);
3205 fprintf (file, ".%s", SUBREG_BYTE (x) == 0 ? "x" : "y");
3206 }
3207 else if (split_mode_p (inner_mode)
3208 && (GET_MODE_SIZE (inner_mode) == GET_MODE_SIZE (mode)))
3209 output_reg (file, REGNO (inner_x), split);
3210 else
3211 output_reg (file, REGNO (inner_x), split, SUBREG_BYTE (x));
3212 }
3213 break;
3214
3215 case REG:
3216 output_reg (file, REGNO (x), maybe_split_mode (mode));
3217 break;
3218
3219 case MEM:
3220 fputc ('[', file);
3221 nvptx_print_address_operand (file, XEXP (x, 0), mode);
3222 fputc (']', file);
3223 break;
3224
3225 case CONST_INT:
3226 output_addr_const (file, x);
3227 break;
3228
3229 case CONST:
3230 case SYMBOL_REF:
3231 case LABEL_REF:
3232 /* We could use output_addr_const, but that can print things like
3233 "x-8", which breaks ptxas. Need to ensure it is output as
3234 "x+-8". */
3235 nvptx_print_address_operand (file, x, VOIDmode);
3236 break;
3237
3238 case CONST_DOUBLE:
3239 long vals[2];
3240 real_to_target (vals, CONST_DOUBLE_REAL_VALUE (x), mode);
3241 vals[0] &= 0xffffffff;
3242 vals[1] &= 0xffffffff;
3243 if (mode == SFmode)
3244 fprintf (file, "0f%08lx", vals[0]);
3245 else
3246 fprintf (file, "0d%08lx%08lx", vals[1], vals[0]);
3247 break;
3248
3249 case CONST_VECTOR:
3250 {
3251 unsigned n = CONST_VECTOR_NUNITS (x);
3252 fprintf (file, "{ ");
3253 for (unsigned i = 0; i < n; ++i)
3254 {
3255 if (i != 0)
3256 fprintf (file, ", ");
3257
3258 rtx elem = CONST_VECTOR_ELT (x, i);
3259 output_addr_const (file, elem);
3260 }
3261 fprintf (file, " }");
3262 }
3263 break;
3264
3265 default:
3266 output_addr_const (file, x);
3267 }
3268 }
3269 }
3270
3271 /* Record replacement regs used to deal with subreg operands. */
3272 struct reg_replace
3273 {
3274 rtx replacement[MAX_RECOG_OPERANDS];
3275 machine_mode mode;
3276 int n_allocated;
3277 int n_in_use;
3278 };
3279
3280 /* Allocate or reuse a replacement in R and return the rtx. */
3281
3282 static rtx
3283 get_replacement (struct reg_replace *r)
3284 {
3285 if (r->n_allocated == r->n_in_use)
3286 r->replacement[r->n_allocated++] = gen_reg_rtx (r->mode);
3287 return r->replacement[r->n_in_use++];
3288 }
3289
3290 /* Clean up subreg operands. In ptx assembly, everything is typed, and
3291 the presence of subregs would break the rules for most instructions.
3292 Replace them with a suitable new register of the right size, plus
3293 conversion copyin/copyout instructions. */
3294
3295 static void
3296 nvptx_reorg_subreg (void)
3297 {
3298 struct reg_replace qiregs, hiregs, siregs, diregs;
3299 rtx_insn *insn, *next;
3300
3301 qiregs.n_allocated = 0;
3302 hiregs.n_allocated = 0;
3303 siregs.n_allocated = 0;
3304 diregs.n_allocated = 0;
3305 qiregs.mode = QImode;
3306 hiregs.mode = HImode;
3307 siregs.mode = SImode;
3308 diregs.mode = DImode;
3309
3310 for (insn = get_insns (); insn; insn = next)
3311 {
3312 next = NEXT_INSN (insn);
3313 if (!NONDEBUG_INSN_P (insn)
3314 || asm_noperands (PATTERN (insn)) >= 0
3315 || GET_CODE (PATTERN (insn)) == USE
3316 || GET_CODE (PATTERN (insn)) == CLOBBER)
3317 continue;
3318
3319 qiregs.n_in_use = 0;
3320 hiregs.n_in_use = 0;
3321 siregs.n_in_use = 0;
3322 diregs.n_in_use = 0;
3323 extract_insn (insn);
3324 enum attr_subregs_ok s_ok = get_attr_subregs_ok (insn);
3325
3326 for (int i = 0; i < recog_data.n_operands; i++)
3327 {
3328 rtx op = recog_data.operand[i];
3329 if (GET_CODE (op) != SUBREG)
3330 continue;
3331
3332 rtx inner = SUBREG_REG (op);
3333
3334 machine_mode outer_mode = GET_MODE (op);
3335 machine_mode inner_mode = GET_MODE (inner);
3336 gcc_assert (s_ok);
3337 if (s_ok
3338 && (GET_MODE_PRECISION (inner_mode)
3339 >= GET_MODE_PRECISION (outer_mode)))
3340 continue;
3341 gcc_assert (SCALAR_INT_MODE_P (outer_mode));
3342 struct reg_replace *r = (outer_mode == QImode ? &qiregs
3343 : outer_mode == HImode ? &hiregs
3344 : outer_mode == SImode ? &siregs
3345 : &diregs);
3346 rtx new_reg = get_replacement (r);
3347
3348 if (recog_data.operand_type[i] != OP_OUT)
3349 {
3350 enum rtx_code code;
3351 if (GET_MODE_PRECISION (inner_mode)
3352 < GET_MODE_PRECISION (outer_mode))
3353 code = ZERO_EXTEND;
3354 else
3355 code = TRUNCATE;
3356
3357 rtx pat = gen_rtx_SET (new_reg,
3358 gen_rtx_fmt_e (code, outer_mode, inner));
3359 emit_insn_before (pat, insn);
3360 }
3361
3362 if (recog_data.operand_type[i] != OP_IN)
3363 {
3364 enum rtx_code code;
3365 if (GET_MODE_PRECISION (inner_mode)
3366 < GET_MODE_PRECISION (outer_mode))
3367 code = TRUNCATE;
3368 else
3369 code = ZERO_EXTEND;
3370
3371 rtx pat = gen_rtx_SET (inner,
3372 gen_rtx_fmt_e (code, inner_mode, new_reg));
3373 emit_insn_after (pat, insn);
3374 }
3375 validate_change (insn, recog_data.operand_loc[i], new_reg, false);
3376 }
3377 }
3378 }
3379
3380 /* Return a SImode "master lane index" register for uniform-simt, allocating on
3381 first use. */
3382
3383 static rtx
3384 nvptx_get_unisimt_master ()
3385 {
3386 rtx &master = cfun->machine->unisimt_master;
3387 return master ? master : master = gen_reg_rtx (SImode);
3388 }
3389
3390 /* Return a BImode "predicate" register for uniform-simt, similar to above. */
3391
3392 static rtx
3393 nvptx_get_unisimt_predicate ()
3394 {
3395 rtx &pred = cfun->machine->unisimt_predicate;
3396 return pred ? pred : pred = gen_reg_rtx (BImode);
3397 }
3398
3399 static rtx
3400 nvptx_get_unisimt_outside_simt_predicate ()
3401 {
3402 rtx &pred = cfun->machine->unisimt_outside_simt_predicate;
3403 return pred ? pred : pred = gen_reg_rtx (BImode);
3404 }
3405
3406 /* Return true if given call insn references one of the functions provided by
3407 the CUDA runtime: malloc, free, vprintf. */
3408
3409 static bool
3410 nvptx_call_insn_is_syscall_p (rtx_insn *insn)
3411 {
3412 rtx pat = PATTERN (insn);
3413 gcc_checking_assert (GET_CODE (pat) == PARALLEL);
3414 pat = XVECEXP (pat, 0, 0);
3415 if (GET_CODE (pat) == SET)
3416 pat = SET_SRC (pat);
3417 gcc_checking_assert (GET_CODE (pat) == CALL
3418 && GET_CODE (XEXP (pat, 0)) == MEM);
3419 rtx addr = XEXP (XEXP (pat, 0), 0);
3420 if (GET_CODE (addr) != SYMBOL_REF)
3421 return false;
3422 const char *name = XSTR (addr, 0);
3423 /* Ordinary malloc/free are redirected to __nvptx_{malloc,free), so only the
3424 references with forced assembler name refer to PTX syscalls. For vprintf,
3425 accept both normal and forced-assembler-name references. */
3426 return (!strcmp (name, "vprintf") || !strcmp (name, "*vprintf")
3427 || !strcmp (name, "*malloc")
3428 || !strcmp (name, "*free"));
3429 }
3430
3431 /* If SET subexpression of INSN sets a register, emit a shuffle instruction to
3432 propagate its value from lane MASTER to current lane. */
3433
3434 static bool
3435 nvptx_unisimt_handle_set (rtx set, rtx_insn *insn, rtx master)
3436 {
3437 rtx reg;
3438 if (GET_CODE (set) == SET
3439 && REG_P (reg = SET_DEST (set))
3440 && find_reg_note (insn, REG_UNUSED, reg) == NULL_RTX)
3441 {
3442 emit_insn_after (nvptx_gen_shuffle (reg, reg, master, SHUFFLE_IDX),
3443 insn);
3444 return true;
3445 }
3446
3447 return false;
3448 }
3449
3450 static void
3451 predicate_insn (rtx_insn *insn, rtx pred)
3452 {
3453 rtx pat = PATTERN (insn);
3454 pred = gen_rtx_NE (BImode, pred, const0_rtx);
3455 pat = gen_rtx_COND_EXEC (VOIDmode, pred, pat);
3456 bool changed_p = validate_change (insn, &PATTERN (insn), pat, false);
3457 gcc_assert (changed_p);
3458 }
3459
3460 /* Adjust code for uniform-simt code generation variant by making atomics and
3461 "syscalls" conditionally executed, and inserting shuffle-based propagation
3462 for registers being set. */
3463
3464 static void
3465 nvptx_reorg_uniform_simt ()
3466 {
3467 rtx_insn *insn, *next;
3468
3469 for (insn = get_insns (); insn; insn = next)
3470 {
3471 next = NEXT_INSN (insn);
3472
3473 /* Skip NOTE, USE, etc. */
3474 if (!INSN_P (insn) || recog_memoized (insn) == -1)
3475 continue;
3476
3477 if (CALL_P (insn) && nvptx_call_insn_is_syscall_p (insn))
3478 {
3479 /* Handle syscall. */
3480 }
3481 else if (get_attr_atomic (insn))
3482 {
3483 /* Handle atomic insn. */
3484 }
3485 else
3486 continue;
3487
3488 rtx pat = PATTERN (insn);
3489 rtx master = nvptx_get_unisimt_master ();
3490 bool shuffle_p = false;
3491 switch (GET_CODE (pat))
3492 {
3493 case PARALLEL:
3494 for (int i = 0; i < XVECLEN (pat, 0); i++)
3495 shuffle_p
3496 |= nvptx_unisimt_handle_set (XVECEXP (pat, 0, i), insn, master);
3497 break;
3498 case SET:
3499 shuffle_p |= nvptx_unisimt_handle_set (pat, insn, master);
3500 break;
3501 default:
3502 gcc_unreachable ();
3503 }
3504
3505 if (shuffle_p && TARGET_PTX_6_0)
3506 {
3507 /* The shuffle is a sync, so uniformity is guaranteed. */
3508 }
3509 else
3510 {
3511 if (TARGET_PTX_6_0)
3512 {
3513 gcc_assert (!shuffle_p);
3514 /* Emit after the insn, to guarantee uniformity. */
3515 emit_insn_after (gen_nvptx_warpsync (), insn);
3516 }
3517 else
3518 {
3519 /* Emit after the insn (and before the shuffle, if there are any)
3520 to check uniformity. */
3521 emit_insn_after (gen_nvptx_uniform_warp_check (), insn);
3522 }
3523 }
3524
3525 rtx pred = nvptx_get_unisimt_predicate ();
3526 predicate_insn (insn, pred);
3527
3528 pred = NULL_RTX;
3529 for (rtx_insn *post = NEXT_INSN (insn); post != next;
3530 post = NEXT_INSN (post))
3531 {
3532 if (pred == NULL_RTX)
3533 pred = nvptx_get_unisimt_outside_simt_predicate ();
3534 predicate_insn (post, pred);
3535 }
3536 }
3537 }
3538
3539 /* Offloading function attributes. */
3540
3541 struct offload_attrs
3542 {
3543 unsigned mask;
3544 int num_gangs;
3545 int num_workers;
3546 int vector_length;
3547 };
3548
3549 /* Define entries for cfun->machine->axis_dim. */
3550
3551 #define MACH_VECTOR_LENGTH 0
3552 #define MACH_MAX_WORKERS 1
3553
3554 static void populate_offload_attrs (offload_attrs *oa);
3555
3556 static void
3557 init_axis_dim (void)
3558 {
3559 offload_attrs oa;
3560 int max_workers;
3561
3562 populate_offload_attrs (&oa);
3563
3564 if (oa.num_workers == 0)
3565 max_workers = PTX_CTA_SIZE / oa.vector_length;
3566 else
3567 max_workers = oa.num_workers;
3568
3569 cfun->machine->axis_dim[MACH_VECTOR_LENGTH] = oa.vector_length;
3570 cfun->machine->axis_dim[MACH_MAX_WORKERS] = max_workers;
3571 cfun->machine->axis_dim_init_p = true;
3572 }
3573
3574 static int ATTRIBUTE_UNUSED
3575 nvptx_mach_max_workers ()
3576 {
3577 if (!cfun->machine->axis_dim_init_p)
3578 init_axis_dim ();
3579 return cfun->machine->axis_dim[MACH_MAX_WORKERS];
3580 }
3581
3582 static int ATTRIBUTE_UNUSED
3583 nvptx_mach_vector_length ()
3584 {
3585 if (!cfun->machine->axis_dim_init_p)
3586 init_axis_dim ();
3587 return cfun->machine->axis_dim[MACH_VECTOR_LENGTH];
3588 }
3589
3590 /* Loop structure of the function. The entire function is described as
3591 a NULL loop. */
3592 /* See also 'gcc/omp-oacc-neuter-broadcast.cc:struct parallel_g'. */
3593
3594 struct parallel
3595 {
3596 /* Parent parallel. */
3597 parallel *parent;
3598
3599 /* Next sibling parallel. */
3600 parallel *next;
3601
3602 /* First child parallel. */
3603 parallel *inner;
3604
3605 /* Partitioning mask of the parallel. */
3606 unsigned mask;
3607
3608 /* Partitioning used within inner parallels. */
3609 unsigned inner_mask;
3610
3611 /* Location of parallel forked and join. The forked is the first
3612 block in the parallel and the join is the first block after of
3613 the partition. */
3614 basic_block forked_block;
3615 basic_block join_block;
3616
3617 rtx_insn *forked_insn;
3618 rtx_insn *join_insn;
3619
3620 rtx_insn *fork_insn;
3621 rtx_insn *joining_insn;
3622
3623 /* Basic blocks in this parallel, but not in child parallels. The
3624 FORKED and JOINING blocks are in the partition. The FORK and JOIN
3625 blocks are not. */
3626 auto_vec<basic_block> blocks;
3627
3628 public:
3629 parallel (parallel *parent, unsigned mode);
3630 ~parallel ();
3631 };
3632
3633 /* Constructor links the new parallel into it's parent's chain of
3634 children. */
3635
3636 parallel::parallel (parallel *parent_, unsigned mask_)
3637 :parent (parent_), next (0), inner (0), mask (mask_), inner_mask (0)
3638 {
3639 forked_block = join_block = 0;
3640 forked_insn = join_insn = 0;
3641 fork_insn = joining_insn = 0;
3642
3643 if (parent)
3644 {
3645 next = parent->inner;
3646 parent->inner = this;
3647 }
3648 }
3649
3650 parallel::~parallel ()
3651 {
3652 delete inner;
3653 delete next;
3654 }
3655
3656 /* Map of basic blocks to insns */
3657 typedef hash_map<basic_block, rtx_insn *> bb_insn_map_t;
3658
3659 /* A tuple of an insn of interest and the BB in which it resides. */
3660 typedef std::pair<rtx_insn *, basic_block> insn_bb_t;
3661 typedef auto_vec<insn_bb_t> insn_bb_vec_t;
3662
3663 /* Split basic blocks such that each forked and join unspecs are at
3664 the start of their basic blocks. Thus afterwards each block will
3665 have a single partitioning mode. We also do the same for return
3666 insns, as they are executed by every thread. Return the
3667 partitioning mode of the function as a whole. Populate MAP with
3668 head and tail blocks. We also clear the BB visited flag, which is
3669 used when finding partitions. */
3670 /* See also 'gcc/omp-oacc-neuter-broadcast.cc:omp_sese_split_blocks'. */
3671
3672 static void
3673 nvptx_split_blocks (bb_insn_map_t *map)
3674 {
3675 insn_bb_vec_t worklist;
3676 basic_block block;
3677 rtx_insn *insn;
3678
3679 /* Locate all the reorg instructions of interest. */
3680 FOR_ALL_BB_FN (block, cfun)
3681 {
3682 bool seen_insn = false;
3683
3684 /* Clear visited flag, for use by parallel locator */
3685 block->flags &= ~BB_VISITED;
3686
3687 FOR_BB_INSNS (block, insn)
3688 {
3689 if (!INSN_P (insn))
3690 continue;
3691 switch (recog_memoized (insn))
3692 {
3693 default:
3694 seen_insn = true;
3695 continue;
3696 case CODE_FOR_nvptx_forked:
3697 case CODE_FOR_nvptx_join:
3698 break;
3699
3700 case CODE_FOR_return:
3701 /* We also need to split just before return insns, as
3702 that insn needs executing by all threads, but the
3703 block it is in probably does not. */
3704 break;
3705 }
3706
3707 if (seen_insn)
3708 /* We've found an instruction that must be at the start of
3709 a block, but isn't. Add it to the worklist. */
3710 worklist.safe_push (insn_bb_t (insn, block));
3711 else
3712 /* It was already the first instruction. Just add it to
3713 the map. */
3714 map->get_or_insert (block) = insn;
3715 seen_insn = true;
3716 }
3717 }
3718
3719 /* Split blocks on the worklist. */
3720 unsigned ix;
3721 insn_bb_t *elt;
3722 basic_block remap = 0;
3723 for (ix = 0; worklist.iterate (ix, &elt); ix++)
3724 {
3725 if (remap != elt->second)
3726 {
3727 block = elt->second;
3728 remap = block;
3729 }
3730
3731 /* Split block before insn. The insn is in the new block */
3732 edge e = split_block (block, PREV_INSN (elt->first));
3733
3734 block = e->dest;
3735 map->get_or_insert (block) = elt->first;
3736 }
3737 }
3738
3739 /* Return true if MASK contains parallelism that requires shared
3740 memory to broadcast. */
3741
3742 static bool
3743 nvptx_needs_shared_bcast (unsigned mask)
3744 {
3745 bool worker = mask & GOMP_DIM_MASK (GOMP_DIM_WORKER);
3746 bool large_vector = (mask & GOMP_DIM_MASK (GOMP_DIM_VECTOR))
3747 && nvptx_mach_vector_length () != PTX_WARP_SIZE;
3748
3749 return worker || large_vector;
3750 }
3751
3752 /* BLOCK is a basic block containing a head or tail instruction.
3753 Locate the associated prehead or pretail instruction, which must be
3754 in the single predecessor block. */
3755
3756 static rtx_insn *
3757 nvptx_discover_pre (basic_block block, int expected)
3758 {
3759 gcc_assert (block->preds->length () == 1);
3760 basic_block pre_block = (*block->preds)[0]->src;
3761 rtx_insn *pre_insn;
3762
3763 for (pre_insn = BB_END (pre_block); !INSN_P (pre_insn);
3764 pre_insn = PREV_INSN (pre_insn))
3765 gcc_assert (pre_insn != BB_HEAD (pre_block));
3766
3767 gcc_assert (recog_memoized (pre_insn) == expected);
3768 return pre_insn;
3769 }
3770
3771 /* Dump this parallel and all its inner parallels. */
3772 /* See also 'gcc/omp-oacc-neuter-broadcast.cc:omp_sese_dump_pars'. */
3773
3774 static void
3775 nvptx_dump_pars (parallel *par, unsigned depth)
3776 {
3777 fprintf (dump_file, "%u: mask %d head=%d, tail=%d\n",
3778 depth, par->mask,
3779 par->forked_block ? par->forked_block->index : -1,
3780 par->join_block ? par->join_block->index : -1);
3781
3782 fprintf (dump_file, " blocks:");
3783
3784 basic_block block;
3785 for (unsigned ix = 0; par->blocks.iterate (ix, &block); ix++)
3786 fprintf (dump_file, " %d", block->index);
3787 fprintf (dump_file, "\n");
3788 if (par->inner)
3789 nvptx_dump_pars (par->inner, depth + 1);
3790
3791 if (par->next)
3792 nvptx_dump_pars (par->next, depth);
3793 }
3794
3795 /* If BLOCK contains a fork/join marker, process it to create or
3796 terminate a loop structure. Add this block to the current loop,
3797 and then walk successor blocks. */
3798 /* See also 'gcc/omp-oacc-neuter-broadcast.cc:omp_sese_find_par'. */
3799
3800 static parallel *
3801 nvptx_find_par (bb_insn_map_t *map, parallel *par, basic_block block)
3802 {
3803 if (block->flags & BB_VISITED)
3804 return par;
3805 block->flags |= BB_VISITED;
3806
3807 if (rtx_insn **endp = map->get (block))
3808 {
3809 rtx_insn *end = *endp;
3810
3811 /* This is a block head or tail, or return instruction. */
3812 switch (recog_memoized (end))
3813 {
3814 case CODE_FOR_return:
3815 /* Return instructions are in their own block, and we
3816 don't need to do anything more. */
3817 return par;
3818
3819 case CODE_FOR_nvptx_forked:
3820 /* Loop head, create a new inner loop and add it into
3821 our parent's child list. */
3822 {
3823 unsigned mask = UINTVAL (XVECEXP (PATTERN (end), 0, 0));
3824
3825 gcc_assert (mask);
3826 par = new parallel (par, mask);
3827 par->forked_block = block;
3828 par->forked_insn = end;
3829 if (nvptx_needs_shared_bcast (mask))
3830 par->fork_insn
3831 = nvptx_discover_pre (block, CODE_FOR_nvptx_fork);
3832 }
3833 break;
3834
3835 case CODE_FOR_nvptx_join:
3836 /* A loop tail. Finish the current loop and return to
3837 parent. */
3838 {
3839 unsigned mask = UINTVAL (XVECEXP (PATTERN (end), 0, 0));
3840
3841 gcc_assert (par->mask == mask);
3842 gcc_assert (par->join_block == NULL);
3843 par->join_block = block;
3844 par->join_insn = end;
3845 if (nvptx_needs_shared_bcast (mask))
3846 par->joining_insn
3847 = nvptx_discover_pre (block, CODE_FOR_nvptx_joining);
3848 par = par->parent;
3849 }
3850 break;
3851
3852 default:
3853 gcc_unreachable ();
3854 }
3855 }
3856
3857 if (par)
3858 /* Add this block onto the current loop's list of blocks. */
3859 par->blocks.safe_push (block);
3860 else
3861 /* This must be the entry block. Create a NULL parallel. */
3862 par = new parallel (0, 0);
3863
3864 /* Walk successor blocks. */
3865 edge e;
3866 edge_iterator ei;
3867
3868 FOR_EACH_EDGE (e, ei, block->succs)
3869 nvptx_find_par (map, par, e->dest);
3870
3871 return par;
3872 }
3873
3874 /* DFS walk the CFG looking for fork & join markers. Construct
3875 loop structures as we go. MAP is a mapping of basic blocks
3876 to head & tail markers, discovered when splitting blocks. This
3877 speeds up the discovery. We rely on the BB visited flag having
3878 been cleared when splitting blocks. */
3879 /* See also 'gcc/omp-oacc-neuter-broadcast.cc:omp_sese_discover_pars'. */
3880
3881 static parallel *
3882 nvptx_discover_pars (bb_insn_map_t *map)
3883 {
3884 basic_block block;
3885
3886 /* Mark exit blocks as visited. */
3887 block = EXIT_BLOCK_PTR_FOR_FN (cfun);
3888 block->flags |= BB_VISITED;
3889
3890 /* And entry block as not. */
3891 block = ENTRY_BLOCK_PTR_FOR_FN (cfun);
3892 block->flags &= ~BB_VISITED;
3893
3894 parallel *par = nvptx_find_par (map, 0, block);
3895
3896 if (dump_file)
3897 {
3898 fprintf (dump_file, "\nLoops\n");
3899 nvptx_dump_pars (par, 0);
3900 fprintf (dump_file, "\n");
3901 }
3902
3903 return par;
3904 }
3905
3906 /* Analyse a group of BBs within a partitioned region and create N
3907 Single-Entry-Single-Exit regions. Some of those regions will be
3908 trivial ones consisting of a single BB. The blocks of a
3909 partitioned region might form a set of disjoint graphs -- because
3910 the region encloses a differently partitoned sub region.
3911
3912 We use the linear time algorithm described in 'Finding Regions Fast:
3913 Single Entry Single Exit and control Regions in Linear Time'
3914 Johnson, Pearson & Pingali. That algorithm deals with complete
3915 CFGs, where a back edge is inserted from END to START, and thus the
3916 problem becomes one of finding equivalent loops.
3917
3918 In this case we have a partial CFG. We complete it by redirecting
3919 any incoming edge to the graph to be from an arbitrary external BB,
3920 and similarly redirecting any outgoing edge to be to that BB.
3921 Thus we end up with a closed graph.
3922
3923 The algorithm works by building a spanning tree of an undirected
3924 graph and keeping track of back edges from nodes further from the
3925 root in the tree to nodes nearer to the root in the tree. In the
3926 description below, the root is up and the tree grows downwards.
3927
3928 We avoid having to deal with degenerate back-edges to the same
3929 block, by splitting each BB into 3 -- one for input edges, one for
3930 the node itself and one for the output edges. Such back edges are
3931 referred to as 'Brackets'. Cycle equivalent nodes will have the
3932 same set of brackets.
3933
3934 Determining bracket equivalency is done by maintaining a list of
3935 brackets in such a manner that the list length and final bracket
3936 uniquely identify the set.
3937
3938 We use coloring to mark all BBs with cycle equivalency with the
3939 same color. This is the output of the 'Finding Regions Fast'
3940 algorithm. Notice it doesn't actually find the set of nodes within
3941 a particular region, just unorderd sets of nodes that are the
3942 entries and exits of SESE regions.
3943
3944 After determining cycle equivalency, we need to find the minimal
3945 set of SESE regions. Do this with a DFS coloring walk of the
3946 complete graph. We're either 'looking' or 'coloring'. When
3947 looking, and we're in the subgraph, we start coloring the color of
3948 the current node, and remember that node as the start of the
3949 current color's SESE region. Every time we go to a new node, we
3950 decrement the count of nodes with thet color. If it reaches zero,
3951 we remember that node as the end of the current color's SESE region
3952 and return to 'looking'. Otherwise we color the node the current
3953 color.
3954
3955 This way we end up with coloring the inside of non-trivial SESE
3956 regions with the color of that region. */
3957
3958 /* A pair of BBs. We use this to represent SESE regions. */
3959 typedef std::pair<basic_block, basic_block> bb_pair_t;
3960 typedef auto_vec<bb_pair_t> bb_pair_vec_t;
3961
3962 /* A node in the undirected CFG. The discriminator SECOND indicates just
3963 above or just below the BB idicated by FIRST. */
3964 typedef std::pair<basic_block, int> pseudo_node_t;
3965
3966 /* A bracket indicates an edge towards the root of the spanning tree of the
3967 undirected graph. Each bracket has a color, determined
3968 from the currrent set of brackets. */
3969 struct bracket
3970 {
3971 pseudo_node_t back; /* Back target */
3972
3973 /* Current color and size of set. */
3974 unsigned color;
3975 unsigned size;
3976
3977 bracket (pseudo_node_t back_)
3978 : back (back_), color (~0u), size (~0u)
3979 {
3980 }
3981
3982 unsigned get_color (auto_vec<unsigned> &color_counts, unsigned length)
3983 {
3984 if (length != size)
3985 {
3986 size = length;
3987 color = color_counts.length ();
3988 color_counts.quick_push (0);
3989 }
3990 color_counts[color]++;
3991 return color;
3992 }
3993 };
3994
3995 typedef auto_vec<bracket> bracket_vec_t;
3996
3997 /* Basic block info for finding SESE regions. */
3998
3999 struct bb_sese
4000 {
4001 int node; /* Node number in spanning tree. */
4002 int parent; /* Parent node number. */
4003
4004 /* The algorithm splits each node A into Ai, A', Ao. The incoming
4005 edges arrive at pseudo-node Ai and the outgoing edges leave at
4006 pseudo-node Ao. We have to remember which way we arrived at a
4007 particular node when generating the spanning tree. dir > 0 means
4008 we arrived at Ai, dir < 0 means we arrived at Ao. */
4009 int dir;
4010
4011 /* Lowest numbered pseudo-node reached via a backedge from thsis
4012 node, or any descendant. */
4013 pseudo_node_t high;
4014
4015 int color; /* Cycle-equivalence color */
4016
4017 /* Stack of brackets for this node. */
4018 bracket_vec_t brackets;
4019
4020 bb_sese (unsigned node_, unsigned p, int dir_)
4021 :node (node_), parent (p), dir (dir_)
4022 {
4023 }
4024 ~bb_sese ();
4025
4026 /* Push a bracket ending at BACK. */
4027 void push (const pseudo_node_t &back)
4028 {
4029 if (dump_file)
4030 fprintf (dump_file, "Pushing backedge %d:%+d\n",
4031 back.first ? back.first->index : 0, back.second);
4032 brackets.safe_push (bracket (back));
4033 }
4034
4035 void append (bb_sese *child);
4036 void remove (const pseudo_node_t &);
4037
4038 /* Set node's color. */
4039 void set_color (auto_vec<unsigned> &color_counts)
4040 {
4041 color = brackets.last ().get_color (color_counts, brackets.length ());
4042 }
4043 };
4044
4045 bb_sese::~bb_sese ()
4046 {
4047 }
4048
4049 /* Destructively append CHILD's brackets. */
4050
4051 void
4052 bb_sese::append (bb_sese *child)
4053 {
4054 if (int len = child->brackets.length ())
4055 {
4056 int ix;
4057
4058 if (dump_file)
4059 {
4060 for (ix = 0; ix < len; ix++)
4061 {
4062 const pseudo_node_t &pseudo = child->brackets[ix].back;
4063 fprintf (dump_file, "Appending (%d)'s backedge %d:%+d\n",
4064 child->node, pseudo.first ? pseudo.first->index : 0,
4065 pseudo.second);
4066 }
4067 }
4068 if (!brackets.length ())
4069 std::swap (brackets, child->brackets);
4070 else
4071 {
4072 brackets.reserve (len);
4073 for (ix = 0; ix < len; ix++)
4074 brackets.quick_push (child->brackets[ix]);
4075 }
4076 }
4077 }
4078
4079 /* Remove brackets that terminate at PSEUDO. */
4080
4081 void
4082 bb_sese::remove (const pseudo_node_t &pseudo)
4083 {
4084 unsigned removed = 0;
4085 int len = brackets.length ();
4086
4087 for (int ix = 0; ix < len; ix++)
4088 {
4089 if (brackets[ix].back == pseudo)
4090 {
4091 if (dump_file)
4092 fprintf (dump_file, "Removing backedge %d:%+d\n",
4093 pseudo.first ? pseudo.first->index : 0, pseudo.second);
4094 removed++;
4095 }
4096 else if (removed)
4097 brackets[ix-removed] = brackets[ix];
4098 }
4099 while (removed--)
4100 brackets.pop ();
4101 }
4102
4103 /* Accessors for BB's aux pointer. */
4104 #define BB_SET_SESE(B, S) ((B)->aux = (S))
4105 #define BB_GET_SESE(B) ((bb_sese *)(B)->aux)
4106
4107 /* DFS walk creating SESE data structures. Only cover nodes with
4108 BB_VISITED set. Append discovered blocks to LIST. We number in
4109 increments of 3 so that the above and below pseudo nodes can be
4110 implicitly numbered too. */
4111
4112 static int
4113 nvptx_sese_number (int n, int p, int dir, basic_block b,
4114 auto_vec<basic_block> *list)
4115 {
4116 if (BB_GET_SESE (b))
4117 return n;
4118
4119 if (dump_file)
4120 fprintf (dump_file, "Block %d(%d), parent (%d), orientation %+d\n",
4121 b->index, n, p, dir);
4122
4123 BB_SET_SESE (b, new bb_sese (n, p, dir));
4124 p = n;
4125
4126 n += 3;
4127 list->quick_push (b);
4128
4129 /* First walk the nodes on the 'other side' of this node, then walk
4130 the nodes on the same side. */
4131 for (unsigned ix = 2; ix; ix--)
4132 {
4133 vec<edge, va_gc> *edges = dir > 0 ? b->succs : b->preds;
4134 size_t offset = (dir > 0 ? offsetof (edge_def, dest)
4135 : offsetof (edge_def, src));
4136 edge e;
4137 edge_iterator ei;
4138
4139 FOR_EACH_EDGE (e, ei, edges)
4140 {
4141 basic_block target = *(basic_block *)((char *)e + offset);
4142
4143 if (target->flags & BB_VISITED)
4144 n = nvptx_sese_number (n, p, dir, target, list);
4145 }
4146 dir = -dir;
4147 }
4148 return n;
4149 }
4150
4151 /* Process pseudo node above (DIR < 0) or below (DIR > 0) ME.
4152 EDGES are the outgoing edges and OFFSET is the offset to the src
4153 or dst block on the edges. */
4154
4155 static void
4156 nvptx_sese_pseudo (basic_block me, bb_sese *sese, int depth, int dir,
4157 vec<edge, va_gc> *edges, size_t offset)
4158 {
4159 edge e;
4160 edge_iterator ei;
4161 int hi_back = depth;
4162 pseudo_node_t node_back (nullptr, depth);
4163 int hi_child = depth;
4164 pseudo_node_t node_child (nullptr, depth);
4165 basic_block child = NULL;
4166 unsigned num_children = 0;
4167 int usd = -dir * sese->dir;
4168
4169 if (dump_file)
4170 fprintf (dump_file, "\nProcessing %d(%d) %+d\n",
4171 me->index, sese->node, dir);
4172
4173 if (dir < 0)
4174 {
4175 /* This is the above pseudo-child. It has the BB itself as an
4176 additional child node. */
4177 node_child = sese->high;
4178 hi_child = node_child.second;
4179 if (node_child.first)
4180 hi_child += BB_GET_SESE (node_child.first)->node;
4181 num_children++;
4182 }
4183
4184 /* Examine each edge.
4185 - if it is a child (a) append its bracket list and (b) record
4186 whether it is the child with the highest reaching bracket.
4187 - if it is an edge to ancestor, record whether it's the highest
4188 reaching backlink. */
4189 FOR_EACH_EDGE (e, ei, edges)
4190 {
4191 basic_block target = *(basic_block *)((char *)e + offset);
4192
4193 if (bb_sese *t_sese = BB_GET_SESE (target))
4194 {
4195 if (t_sese->parent == sese->node && !(t_sese->dir + usd))
4196 {
4197 /* Child node. Append its bracket list. */
4198 num_children++;
4199 sese->append (t_sese);
4200
4201 /* Compare it's hi value. */
4202 int t_hi = t_sese->high.second;
4203
4204 if (basic_block child_hi_block = t_sese->high.first)
4205 t_hi += BB_GET_SESE (child_hi_block)->node;
4206
4207 if (hi_child > t_hi)
4208 {
4209 hi_child = t_hi;
4210 node_child = t_sese->high;
4211 child = target;
4212 }
4213 }
4214 else if (t_sese->node < sese->node + dir
4215 && !(dir < 0 && sese->parent == t_sese->node))
4216 {
4217 /* Non-parental ancestor node -- a backlink. */
4218 int d = usd * t_sese->dir;
4219 int back = t_sese->node + d;
4220
4221 if (hi_back > back)
4222 {
4223 hi_back = back;
4224 node_back = pseudo_node_t (target, d);
4225 }
4226 }
4227 }
4228 else
4229 { /* Fallen off graph, backlink to entry node. */
4230 hi_back = 0;
4231 node_back = pseudo_node_t (nullptr, 0);
4232 }
4233 }
4234
4235 /* Remove any brackets that terminate at this pseudo node. */
4236 sese->remove (pseudo_node_t (me, dir));
4237
4238 /* Now push any backlinks from this pseudo node. */
4239 FOR_EACH_EDGE (e, ei, edges)
4240 {
4241 basic_block target = *(basic_block *)((char *)e + offset);
4242 if (bb_sese *t_sese = BB_GET_SESE (target))
4243 {
4244 if (t_sese->node < sese->node + dir
4245 && !(dir < 0 && sese->parent == t_sese->node))
4246 /* Non-parental ancestor node - backedge from me. */
4247 sese->push (pseudo_node_t (target, usd * t_sese->dir));
4248 }
4249 else
4250 {
4251 /* back edge to entry node */
4252 sese->push (pseudo_node_t (nullptr, 0));
4253 }
4254 }
4255
4256 /* If this node leads directly or indirectly to a no-return region of
4257 the graph, then fake a backedge to entry node. */
4258 if (!sese->brackets.length () || !edges || !edges->length ())
4259 {
4260 hi_back = 0;
4261 node_back = pseudo_node_t (nullptr, 0);
4262 sese->push (node_back);
4263 }
4264
4265 /* Record the highest reaching backedge from us or a descendant. */
4266 sese->high = hi_back < hi_child ? node_back : node_child;
4267
4268 if (num_children > 1)
4269 {
4270 /* There is more than one child -- this is a Y shaped piece of
4271 spanning tree. We have to insert a fake backedge from this
4272 node to the highest ancestor reached by not-the-highest
4273 reaching child. Note that there may be multiple children
4274 with backedges to the same highest node. That's ok and we
4275 insert the edge to that highest node. */
4276 hi_child = depth;
4277 if (dir < 0 && child)
4278 {
4279 node_child = sese->high;
4280 hi_child = node_child.second;
4281 if (node_child.first)
4282 hi_child += BB_GET_SESE (node_child.first)->node;
4283 }
4284
4285 FOR_EACH_EDGE (e, ei, edges)
4286 {
4287 basic_block target = *(basic_block *)((char *)e + offset);
4288
4289 if (target == child)
4290 /* Ignore the highest child. */
4291 continue;
4292
4293 bb_sese *t_sese = BB_GET_SESE (target);
4294 if (!t_sese)
4295 continue;
4296 if (t_sese->parent != sese->node)
4297 /* Not a child. */
4298 continue;
4299
4300 /* Compare its hi value. */
4301 int t_hi = t_sese->high.second;
4302
4303 if (basic_block child_hi_block = t_sese->high.first)
4304 t_hi += BB_GET_SESE (child_hi_block)->node;
4305
4306 if (hi_child > t_hi)
4307 {
4308 hi_child = t_hi;
4309 node_child = t_sese->high;
4310 }
4311 }
4312
4313 sese->push (node_child);
4314 }
4315 }
4316
4317
4318 /* DFS walk of BB graph. Color node BLOCK according to COLORING then
4319 proceed to successors. Set SESE entry and exit nodes of
4320 REGIONS. */
4321
4322 static void
4323 nvptx_sese_color (auto_vec<unsigned> &color_counts, bb_pair_vec_t &regions,
4324 basic_block block, int coloring)
4325 {
4326 bb_sese *sese = BB_GET_SESE (block);
4327
4328 if (block->flags & BB_VISITED)
4329 {
4330 /* If we've already encountered this block, either we must not
4331 be coloring, or it must have been colored the current color. */
4332 gcc_assert (coloring < 0 || (sese && coloring == sese->color));
4333 return;
4334 }
4335
4336 block->flags |= BB_VISITED;
4337
4338 if (sese)
4339 {
4340 if (coloring < 0)
4341 {
4342 /* Start coloring a region. */
4343 regions[sese->color].first = block;
4344 coloring = sese->color;
4345 }
4346
4347 if (!--color_counts[sese->color] && sese->color == coloring)
4348 {
4349 /* Found final block of SESE region. */
4350 regions[sese->color].second = block;
4351 coloring = -1;
4352 }
4353 else
4354 /* Color the node, so we can assert on revisiting the node
4355 that the graph is indeed SESE. */
4356 sese->color = coloring;
4357 }
4358 else
4359 /* Fallen off the subgraph, we cannot be coloring. */
4360 gcc_assert (coloring < 0);
4361
4362 /* Walk each successor block. */
4363 if (block->succs && block->succs->length ())
4364 {
4365 edge e;
4366 edge_iterator ei;
4367
4368 FOR_EACH_EDGE (e, ei, block->succs)
4369 nvptx_sese_color (color_counts, regions, e->dest, coloring);
4370 }
4371 else
4372 gcc_assert (coloring < 0);
4373 }
4374
4375 /* Find minimal set of SESE regions covering BLOCKS. REGIONS might
4376 end up with NULL entries in it. */
4377
4378 static void
4379 nvptx_find_sese (auto_vec<basic_block> &blocks, bb_pair_vec_t &regions)
4380 {
4381 basic_block block;
4382 int ix;
4383
4384 /* First clear each BB of the whole function. */
4385 FOR_ALL_BB_FN (block, cfun)
4386 {
4387 block->flags &= ~BB_VISITED;
4388 BB_SET_SESE (block, 0);
4389 }
4390
4391 /* Mark blocks in the function that are in this graph. */
4392 for (ix = 0; blocks.iterate (ix, &block); ix++)
4393 block->flags |= BB_VISITED;
4394
4395 /* Counts of nodes assigned to each color. There cannot be more
4396 colors than blocks (and hopefully there will be fewer). */
4397 auto_vec<unsigned> color_counts;
4398 color_counts.reserve (blocks.length ());
4399
4400 /* Worklist of nodes in the spanning tree. Again, there cannot be
4401 more nodes in the tree than blocks (there will be fewer if the
4402 CFG of blocks is disjoint). */
4403 auto_vec<basic_block> spanlist;
4404 spanlist.reserve (blocks.length ());
4405
4406 /* Make sure every block has its cycle class determined. */
4407 for (ix = 0; blocks.iterate (ix, &block); ix++)
4408 {
4409 if (BB_GET_SESE (block))
4410 /* We already met this block in an earlier graph solve. */
4411 continue;
4412
4413 if (dump_file)
4414 fprintf (dump_file, "Searching graph starting at %d\n", block->index);
4415
4416 /* Number the nodes reachable from block initial DFS order. */
4417 int depth = nvptx_sese_number (2, 0, +1, block, &spanlist);
4418
4419 /* Now walk in reverse DFS order to find cycle equivalents. */
4420 while (spanlist.length ())
4421 {
4422 block = spanlist.pop ();
4423 bb_sese *sese = BB_GET_SESE (block);
4424
4425 /* Do the pseudo node below. */
4426 nvptx_sese_pseudo (block, sese, depth, +1,
4427 sese->dir > 0 ? block->succs : block->preds,
4428 (sese->dir > 0 ? offsetof (edge_def, dest)
4429 : offsetof (edge_def, src)));
4430 sese->set_color (color_counts);
4431 /* Do the pseudo node above. */
4432 nvptx_sese_pseudo (block, sese, depth, -1,
4433 sese->dir < 0 ? block->succs : block->preds,
4434 (sese->dir < 0 ? offsetof (edge_def, dest)
4435 : offsetof (edge_def, src)));
4436 }
4437 if (dump_file)
4438 fprintf (dump_file, "\n");
4439 }
4440
4441 if (dump_file)
4442 {
4443 unsigned count;
4444 const char *comma = "";
4445
4446 fprintf (dump_file, "Found %d cycle equivalents\n",
4447 color_counts.length ());
4448 for (ix = 0; color_counts.iterate (ix, &count); ix++)
4449 {
4450 fprintf (dump_file, "%s%d[%d]={", comma, ix, count);
4451
4452 comma = "";
4453 for (unsigned jx = 0; blocks.iterate (jx, &block); jx++)
4454 if (BB_GET_SESE (block)->color == ix)
4455 {
4456 block->flags |= BB_VISITED;
4457 fprintf (dump_file, "%s%d", comma, block->index);
4458 comma=",";
4459 }
4460 fprintf (dump_file, "}");
4461 comma = ", ";
4462 }
4463 fprintf (dump_file, "\n");
4464 }
4465
4466 /* Now we've colored every block in the subgraph. We now need to
4467 determine the minimal set of SESE regions that cover that
4468 subgraph. Do this with a DFS walk of the complete function.
4469 During the walk we're either 'looking' or 'coloring'. When we
4470 reach the last node of a particular color, we stop coloring and
4471 return to looking. */
4472
4473 /* There cannot be more SESE regions than colors. */
4474 regions.reserve (color_counts.length ());
4475 for (ix = color_counts.length (); ix--;)
4476 regions.quick_push (bb_pair_t (0, 0));
4477
4478 for (ix = 0; blocks.iterate (ix, &block); ix++)
4479 block->flags &= ~BB_VISITED;
4480
4481 nvptx_sese_color (color_counts, regions, ENTRY_BLOCK_PTR_FOR_FN (cfun), -1);
4482
4483 if (dump_file)
4484 {
4485 const char *comma = "";
4486 int len = regions.length ();
4487
4488 fprintf (dump_file, "SESE regions:");
4489 for (ix = 0; ix != len; ix++)
4490 {
4491 basic_block from = regions[ix].first;
4492 basic_block to = regions[ix].second;
4493
4494 if (from)
4495 {
4496 fprintf (dump_file, "%s %d{%d", comma, ix, from->index);
4497 if (to != from)
4498 fprintf (dump_file, "->%d", to->index);
4499
4500 int color = BB_GET_SESE (from)->color;
4501
4502 /* Print the blocks within the region (excluding ends). */
4503 FOR_EACH_BB_FN (block, cfun)
4504 {
4505 bb_sese *sese = BB_GET_SESE (block);
4506
4507 if (sese && sese->color == color
4508 && block != from && block != to)
4509 fprintf (dump_file, ".%d", block->index);
4510 }
4511 fprintf (dump_file, "}");
4512 }
4513 comma = ",";
4514 }
4515 fprintf (dump_file, "\n\n");
4516 }
4517
4518 for (ix = 0; blocks.iterate (ix, &block); ix++)
4519 delete BB_GET_SESE (block);
4520 }
4521
4522 #undef BB_SET_SESE
4523 #undef BB_GET_SESE
4524
4525 /* Propagate live state at the start of a partitioned region. IS_CALL
4526 indicates whether the propagation is for a (partitioned) call
4527 instruction. BLOCK provides the live register information, and
4528 might not contain INSN. Propagation is inserted just after INSN. RW
4529 indicates whether we are reading and/or writing state. This
4530 separation is needed for worker-level proppagation where we
4531 essentially do a spill & fill. FN is the underlying worker
4532 function to generate the propagation instructions for single
4533 register. DATA is user data.
4534
4535 Returns true if we didn't emit any instructions.
4536
4537 We propagate the live register set for non-calls and the entire
4538 frame for calls and non-calls. We could do better by (a)
4539 propagating just the live set that is used within the partitioned
4540 regions and (b) only propagating stack entries that are used. The
4541 latter might be quite hard to determine. */
4542
4543 typedef rtx (*propagator_fn) (rtx, propagate_mask, unsigned, void *, bool);
4544
4545 static bool
4546 nvptx_propagate (bool is_call, basic_block block, rtx_insn *insn,
4547 propagate_mask rw, propagator_fn fn, void *data, bool vector)
4548 {
4549 bitmap live = DF_LIVE_IN (block);
4550 bitmap_iterator iterator;
4551 unsigned ix;
4552 bool empty = true;
4553
4554 /* Copy the frame array. */
4555 HOST_WIDE_INT fs = get_frame_size ();
4556 if (fs)
4557 {
4558 rtx tmp = gen_reg_rtx (DImode);
4559 rtx idx = NULL_RTX;
4560 rtx ptr = gen_reg_rtx (Pmode);
4561 rtx pred = NULL_RTX;
4562 rtx_code_label *label = NULL;
4563
4564 empty = false;
4565 /* The frame size might not be DImode compatible, but the frame
4566 array's declaration will be. So it's ok to round up here. */
4567 fs = (fs + GET_MODE_SIZE (DImode) - 1) / GET_MODE_SIZE (DImode);
4568 /* Detect single iteration loop. */
4569 if (fs == 1)
4570 fs = 0;
4571
4572 start_sequence ();
4573 emit_insn (gen_rtx_SET (ptr, frame_pointer_rtx));
4574 if (fs)
4575 {
4576 idx = gen_reg_rtx (SImode);
4577 pred = gen_reg_rtx (BImode);
4578 label = gen_label_rtx ();
4579
4580 emit_insn (gen_rtx_SET (idx, GEN_INT (fs)));
4581 /* Allow worker function to initialize anything needed. */
4582 rtx init = fn (tmp, PM_loop_begin, fs, data, vector);
4583 if (init)
4584 emit_insn (init);
4585 emit_label (label);
4586 LABEL_NUSES (label)++;
4587 emit_insn (gen_addsi3 (idx, idx, GEN_INT (-1)));
4588 }
4589 if (rw & PM_read)
4590 emit_insn (gen_rtx_SET (tmp, gen_rtx_MEM (DImode, ptr)));
4591 emit_insn (fn (tmp, rw, fs, data, vector));
4592 if (rw & PM_write)
4593 emit_insn (gen_rtx_SET (gen_rtx_MEM (DImode, ptr), tmp));
4594 if (fs)
4595 {
4596 emit_insn (gen_rtx_SET (pred, gen_rtx_NE (BImode, idx, const0_rtx)));
4597 emit_insn (gen_adddi3 (ptr, ptr, GEN_INT (GET_MODE_SIZE (DImode))));
4598 emit_insn (gen_br_true_uni (pred, label));
4599 rtx fini = fn (tmp, PM_loop_end, fs, data, vector);
4600 if (fini)
4601 emit_insn (fini);
4602 emit_insn (gen_rtx_CLOBBER (GET_MODE (idx), idx));
4603 }
4604 emit_insn (gen_rtx_CLOBBER (GET_MODE (tmp), tmp));
4605 emit_insn (gen_rtx_CLOBBER (GET_MODE (ptr), ptr));
4606 rtx cpy = get_insns ();
4607 end_sequence ();
4608 insn = emit_insn_after (cpy, insn);
4609 }
4610
4611 if (!is_call)
4612 /* Copy live registers. */
4613 EXECUTE_IF_SET_IN_BITMAP (live, 0, ix, iterator)
4614 {
4615 rtx reg = regno_reg_rtx[ix];
4616
4617 if (REGNO (reg) >= FIRST_PSEUDO_REGISTER)
4618 {
4619 rtx bcast = fn (reg, rw, 0, data, vector);
4620
4621 insn = emit_insn_after (bcast, insn);
4622 empty = false;
4623 }
4624 }
4625 return empty;
4626 }
4627
4628 /* Worker for nvptx_warp_propagate. */
4629
4630 static rtx
4631 warp_prop_gen (rtx reg, propagate_mask pm,
4632 unsigned ARG_UNUSED (count), void *ARG_UNUSED (data),
4633 bool ARG_UNUSED (vector))
4634 {
4635 if (!(pm & PM_read_write))
4636 return 0;
4637
4638 return nvptx_gen_warp_bcast (reg);
4639 }
4640
4641 /* Propagate state that is live at start of BLOCK across the vectors
4642 of a single warp. Propagation is inserted just after INSN.
4643 IS_CALL and return as for nvptx_propagate. */
4644
4645 static bool
4646 nvptx_warp_propagate (bool is_call, basic_block block, rtx_insn *insn)
4647 {
4648 return nvptx_propagate (is_call, block, insn, PM_read_write,
4649 warp_prop_gen, 0, false);
4650 }
4651
4652 /* Worker for nvptx_shared_propagate. */
4653
4654 static rtx
4655 shared_prop_gen (rtx reg, propagate_mask pm, unsigned rep, void *data_,
4656 bool vector)
4657 {
4658 broadcast_data_t *data = (broadcast_data_t *)data_;
4659
4660 if (pm & PM_loop_begin)
4661 {
4662 /* Starting a loop, initialize pointer. */
4663 unsigned align = GET_MODE_ALIGNMENT (GET_MODE (reg)) / BITS_PER_UNIT;
4664
4665 oacc_bcast_align = MAX (oacc_bcast_align, align);
4666 data->offset = ROUND_UP (data->offset, align);
4667
4668 data->ptr = gen_reg_rtx (Pmode);
4669
4670 return gen_adddi3 (data->ptr, data->base, GEN_INT (data->offset));
4671 }
4672 else if (pm & PM_loop_end)
4673 {
4674 rtx clobber = gen_rtx_CLOBBER (GET_MODE (data->ptr), data->ptr);
4675 data->ptr = NULL_RTX;
4676 return clobber;
4677 }
4678 else
4679 return nvptx_gen_shared_bcast (reg, pm, rep, data, vector);
4680 }
4681
4682 /* Spill or fill live state that is live at start of BLOCK. PRE_P
4683 indicates if this is just before partitioned mode (do spill), or
4684 just after it starts (do fill). Sequence is inserted just after
4685 INSN. IS_CALL and return as for nvptx_propagate. */
4686
4687 static bool
4688 nvptx_shared_propagate (bool pre_p, bool is_call, basic_block block,
4689 rtx_insn *insn, bool vector)
4690 {
4691 broadcast_data_t data;
4692
4693 data.base = gen_reg_rtx (Pmode);
4694 data.offset = 0;
4695 data.ptr = NULL_RTX;
4696
4697 bool empty = nvptx_propagate (is_call, block, insn,
4698 pre_p ? PM_read : PM_write, shared_prop_gen,
4699 &data, vector);
4700 gcc_assert (empty == !data.offset);
4701 if (data.offset)
4702 {
4703 rtx bcast_sym = oacc_bcast_sym;
4704
4705 /* Stuff was emitted, initialize the base pointer now. */
4706 if (vector && nvptx_mach_max_workers () > 1)
4707 {
4708 if (!cfun->machine->bcast_partition)
4709 {
4710 /* It would be nice to place this register in
4711 DATA_AREA_SHARED. */
4712 cfun->machine->bcast_partition = gen_reg_rtx (DImode);
4713 }
4714 if (!cfun->machine->sync_bar)
4715 cfun->machine->sync_bar = gen_reg_rtx (SImode);
4716
4717 bcast_sym = cfun->machine->bcast_partition;
4718 }
4719
4720 rtx init = gen_rtx_SET (data.base, bcast_sym);
4721 emit_insn_after (init, insn);
4722
4723 unsigned int psize = ROUND_UP (data.offset, oacc_bcast_align);
4724 unsigned int pnum = (nvptx_mach_vector_length () > PTX_WARP_SIZE
4725 ? nvptx_mach_max_workers () + 1
4726 : 1);
4727
4728 oacc_bcast_partition = MAX (oacc_bcast_partition, psize);
4729 oacc_bcast_size = MAX (oacc_bcast_size, psize * pnum);
4730 }
4731 return empty;
4732 }
4733
4734 /* Emit a CTA-level synchronization barrier. LOCK is the barrier number,
4735 which is an integer or a register. THREADS is the number of threads
4736 controlled by the barrier. */
4737
4738 static rtx
4739 nvptx_cta_sync (rtx lock, int threads)
4740 {
4741 return gen_nvptx_barsync (lock, GEN_INT (threads));
4742 }
4743
4744 #if WORKAROUND_PTXJIT_BUG
4745 /* Return first real insn in BB, or return NULL_RTX if BB does not contain
4746 real insns. */
4747
4748 static rtx_insn *
4749 bb_first_real_insn (basic_block bb)
4750 {
4751 rtx_insn *insn;
4752
4753 /* Find first insn of from block. */
4754 FOR_BB_INSNS (bb, insn)
4755 if (INSN_P (insn))
4756 return insn;
4757
4758 return 0;
4759 }
4760 #endif
4761
4762 /* Return true if INSN needs neutering. */
4763
4764 static bool
4765 needs_neutering_p (rtx_insn *insn)
4766 {
4767 if (!INSN_P (insn))
4768 return false;
4769
4770 switch (recog_memoized (insn))
4771 {
4772 case CODE_FOR_nvptx_fork:
4773 case CODE_FOR_nvptx_forked:
4774 case CODE_FOR_nvptx_joining:
4775 case CODE_FOR_nvptx_join:
4776 case CODE_FOR_nvptx_barsync:
4777 return false;
4778 default:
4779 return true;
4780 }
4781 }
4782
4783 /* Verify position of VECTOR_{JUMP,LABEL} and WORKER_{JUMP,LABEL} in FROM. */
4784
4785 static bool
4786 verify_neutering_jumps (basic_block from,
4787 rtx_insn *vector_jump, rtx_insn *worker_jump,
4788 rtx_insn *vector_label, rtx_insn *worker_label)
4789 {
4790 basic_block bb = from;
4791 rtx_insn *insn = BB_HEAD (bb);
4792 bool seen_worker_jump = false;
4793 bool seen_vector_jump = false;
4794 bool seen_worker_label = false;
4795 bool seen_vector_label = false;
4796 bool worker_neutered = false;
4797 bool vector_neutered = false;
4798 while (true)
4799 {
4800 if (insn == worker_jump)
4801 {
4802 seen_worker_jump = true;
4803 worker_neutered = true;
4804 gcc_assert (!vector_neutered);
4805 }
4806 else if (insn == vector_jump)
4807 {
4808 seen_vector_jump = true;
4809 vector_neutered = true;
4810 }
4811 else if (insn == worker_label)
4812 {
4813 seen_worker_label = true;
4814 gcc_assert (worker_neutered);
4815 worker_neutered = false;
4816 }
4817 else if (insn == vector_label)
4818 {
4819 seen_vector_label = true;
4820 gcc_assert (vector_neutered);
4821 vector_neutered = false;
4822 }
4823 else if (INSN_P (insn))
4824 switch (recog_memoized (insn))
4825 {
4826 case CODE_FOR_nvptx_barsync:
4827 gcc_assert (!vector_neutered && !worker_neutered);
4828 break;
4829 default:
4830 break;
4831 }
4832
4833 if (insn != BB_END (bb))
4834 insn = NEXT_INSN (insn);
4835 else if (JUMP_P (insn) && single_succ_p (bb)
4836 && !seen_vector_jump && !seen_worker_jump)
4837 {
4838 bb = single_succ (bb);
4839 insn = BB_HEAD (bb);
4840 }
4841 else
4842 break;
4843 }
4844
4845 gcc_assert (!(vector_jump && !seen_vector_jump));
4846 gcc_assert (!(worker_jump && !seen_worker_jump));
4847
4848 if (seen_vector_label || seen_worker_label)
4849 {
4850 gcc_assert (!(vector_label && !seen_vector_label));
4851 gcc_assert (!(worker_label && !seen_worker_label));
4852
4853 return true;
4854 }
4855
4856 return false;
4857 }
4858
4859 /* Verify position of VECTOR_LABEL and WORKER_LABEL in TO. */
4860
4861 static void
4862 verify_neutering_labels (basic_block to, rtx_insn *vector_label,
4863 rtx_insn *worker_label)
4864 {
4865 basic_block bb = to;
4866 rtx_insn *insn = BB_END (bb);
4867 bool seen_worker_label = false;
4868 bool seen_vector_label = false;
4869 while (true)
4870 {
4871 if (insn == worker_label)
4872 {
4873 seen_worker_label = true;
4874 gcc_assert (!seen_vector_label);
4875 }
4876 else if (insn == vector_label)
4877 seen_vector_label = true;
4878 else if (INSN_P (insn))
4879 switch (recog_memoized (insn))
4880 {
4881 case CODE_FOR_nvptx_barsync:
4882 gcc_assert (!seen_vector_label && !seen_worker_label);
4883 break;
4884 }
4885
4886 if (insn != BB_HEAD (bb))
4887 insn = PREV_INSN (insn);
4888 else
4889 break;
4890 }
4891
4892 gcc_assert (!(vector_label && !seen_vector_label));
4893 gcc_assert (!(worker_label && !seen_worker_label));
4894 }
4895
4896 /* Single neutering according to MASK. FROM is the incoming block and
4897 TO is the outgoing block. These may be the same block. Insert at
4898 start of FROM:
4899
4900 if (tid.<axis>) goto end.
4901
4902 and insert before ending branch of TO (if there is such an insn):
4903
4904 end:
4905 <possibly-broadcast-cond>
4906 <branch>
4907
4908 We currently only use differnt FROM and TO when skipping an entire
4909 loop. We could do more if we detected superblocks. */
4910
4911 static void
4912 nvptx_single (unsigned mask, basic_block from, basic_block to)
4913 {
4914 rtx_insn *head = BB_HEAD (from);
4915 rtx_insn *tail = BB_END (to);
4916 unsigned skip_mask = mask;
4917
4918 while (true)
4919 {
4920 /* Find first insn of from block. */
4921 while (head != BB_END (from) && !needs_neutering_p (head))
4922 head = NEXT_INSN (head);
4923
4924 if (from == to)
4925 break;
4926
4927 if (!(JUMP_P (head) && single_succ_p (from)))
4928 break;
4929
4930 basic_block jump_target = single_succ (from);
4931 if (!single_pred_p (jump_target))
4932 break;
4933
4934 from = jump_target;
4935 head = BB_HEAD (from);
4936 }
4937
4938 /* Find last insn of to block */
4939 rtx_insn *limit = from == to ? head : BB_HEAD (to);
4940 while (tail != limit && !INSN_P (tail) && !LABEL_P (tail))
4941 tail = PREV_INSN (tail);
4942
4943 /* Detect if tail is a branch. */
4944 rtx tail_branch = NULL_RTX;
4945 rtx cond_branch = NULL_RTX;
4946 if (tail && INSN_P (tail))
4947 {
4948 tail_branch = PATTERN (tail);
4949 if (GET_CODE (tail_branch) != SET || SET_DEST (tail_branch) != pc_rtx)
4950 tail_branch = NULL_RTX;
4951 else
4952 {
4953 cond_branch = SET_SRC (tail_branch);
4954 if (GET_CODE (cond_branch) != IF_THEN_ELSE)
4955 cond_branch = NULL_RTX;
4956 }
4957 }
4958
4959 if (tail == head)
4960 {
4961 /* If this is empty, do nothing. */
4962 if (!head || !needs_neutering_p (head))
4963 return;
4964
4965 if (cond_branch)
4966 {
4967 /* If we're only doing vector single, there's no need to
4968 emit skip code because we'll not insert anything. */
4969 if (!(mask & GOMP_DIM_MASK (GOMP_DIM_VECTOR)))
4970 skip_mask = 0;
4971 }
4972 else if (tail_branch)
4973 /* Block with only unconditional branch. Nothing to do. */
4974 return;
4975 }
4976
4977 /* Insert the vector test inside the worker test. */
4978 unsigned mode;
4979 rtx_insn *before = tail;
4980 rtx_insn *neuter_start = NULL;
4981 rtx_insn *worker_label = NULL, *vector_label = NULL;
4982 rtx_insn *worker_jump = NULL, *vector_jump = NULL;
4983 rtx_insn *warp_sync = NULL;
4984 for (mode = GOMP_DIM_WORKER; mode <= GOMP_DIM_VECTOR; mode++)
4985 if (GOMP_DIM_MASK (mode) & skip_mask)
4986 {
4987 rtx_code_label *label = gen_label_rtx ();
4988 rtx pred = cfun->machine->axis_predicate[mode - GOMP_DIM_WORKER];
4989 rtx_insn **mode_jump
4990 = mode == GOMP_DIM_VECTOR ? &vector_jump : &worker_jump;
4991 rtx_insn **mode_label
4992 = mode == GOMP_DIM_VECTOR ? &vector_label : &worker_label;
4993
4994 if (!pred)
4995 {
4996 pred = gen_reg_rtx (BImode);
4997 cfun->machine->axis_predicate[mode - GOMP_DIM_WORKER] = pred;
4998 }
4999
5000 rtx br;
5001 if (mode == GOMP_DIM_VECTOR)
5002 br = gen_br_true (pred, label);
5003 else
5004 br = gen_br_true_uni (pred, label);
5005 if (neuter_start)
5006 neuter_start = emit_insn_after (br, neuter_start);
5007 else
5008 neuter_start = emit_insn_before (br, head);
5009 *mode_jump = neuter_start;
5010
5011 LABEL_NUSES (label)++;
5012 rtx_insn *label_insn;
5013 if (tail_branch)
5014 {
5015 label_insn = emit_label_before (label, before);
5016 if (mode == GOMP_DIM_VECTOR)
5017 {
5018 if (TARGET_PTX_6_0)
5019 warp_sync = emit_insn_after (gen_nvptx_warpsync (),
5020 label_insn);
5021 else
5022 warp_sync = emit_insn_after (gen_nvptx_uniform_warp_check (),
5023 label_insn);
5024 }
5025 before = label_insn;
5026 }
5027 else
5028 {
5029 label_insn = emit_label_after (label, tail);
5030 if (mode == GOMP_DIM_VECTOR)
5031 {
5032 if (TARGET_PTX_6_0)
5033 warp_sync = emit_insn_after (gen_nvptx_warpsync (),
5034 label_insn);
5035 else
5036 warp_sync = emit_insn_after (gen_nvptx_uniform_warp_check (),
5037 label_insn);
5038 }
5039 if ((mode == GOMP_DIM_VECTOR || mode == GOMP_DIM_WORKER)
5040 && CALL_P (tail) && find_reg_note (tail, REG_NORETURN, NULL))
5041 emit_insn_after (gen_exit (), label_insn);
5042 }
5043
5044 *mode_label = label_insn;
5045 }
5046
5047 /* Now deal with propagating the branch condition. */
5048 if (cond_branch)
5049 {
5050 rtx pvar = XEXP (XEXP (cond_branch, 0), 0);
5051
5052 if (GOMP_DIM_MASK (GOMP_DIM_VECTOR) == mask
5053 && nvptx_mach_vector_length () == PTX_WARP_SIZE)
5054 {
5055 /* Vector mode only, do a shuffle. */
5056 #if WORKAROUND_PTXJIT_BUG
5057 /* The branch condition %rcond is propagated like this:
5058
5059 {
5060 .reg .u32 %x;
5061 mov.u32 %x,%tid.x;
5062 setp.ne.u32 %rnotvzero,%x,0;
5063 }
5064
5065 @%rnotvzero bra Lskip;
5066 setp.<op>.<type> %rcond,op1,op2;
5067 Lskip:
5068 selp.u32 %rcondu32,1,0,%rcond;
5069 shfl.idx.b32 %rcondu32,%rcondu32,0,31;
5070 setp.ne.u32 %rcond,%rcondu32,0;
5071
5072 There seems to be a bug in the ptx JIT compiler (observed at driver
5073 version 381.22, at -O1 and higher for sm_61), that drops the shfl
5074 unless %rcond is initialized to something before 'bra Lskip'. The
5075 bug is not observed with ptxas from cuda 8.0.61.
5076
5077 It is true that the code is non-trivial: at Lskip, %rcond is
5078 uninitialized in threads 1-31, and after the selp the same holds
5079 for %rcondu32. But shfl propagates the defined value in thread 0
5080 to threads 1-31, so after the shfl %rcondu32 is defined in threads
5081 0-31, and after the setp.ne %rcond is defined in threads 0-31.
5082
5083 There is nothing in the PTX spec to suggest that this is wrong, or
5084 to explain why the extra initialization is needed. So, we classify
5085 it as a JIT bug, and the extra initialization as workaround:
5086
5087 {
5088 .reg .u32 %x;
5089 mov.u32 %x,%tid.x;
5090 setp.ne.u32 %rnotvzero,%x,0;
5091 }
5092
5093 +.reg .pred %rcond2;
5094 +setp.eq.u32 %rcond2, 1, 0;
5095
5096 @%rnotvzero bra Lskip;
5097 setp.<op>.<type> %rcond,op1,op2;
5098 +mov.pred %rcond2, %rcond;
5099 Lskip:
5100 +mov.pred %rcond, %rcond2;
5101 selp.u32 %rcondu32,1,0,%rcond;
5102 shfl.idx.b32 %rcondu32,%rcondu32,0,31;
5103 setp.ne.u32 %rcond,%rcondu32,0;
5104 */
5105 rtx_insn *label = PREV_INSN (tail);
5106 if (label == warp_sync)
5107 label = PREV_INSN (label);
5108 gcc_assert (label && LABEL_P (label));
5109 rtx tmp = gen_reg_rtx (BImode);
5110 emit_insn_before (gen_movbi (tmp, const0_rtx),
5111 bb_first_real_insn (from));
5112 emit_insn_before (gen_rtx_SET (tmp, pvar), label);
5113 emit_insn_before (gen_rtx_SET (pvar, tmp), tail);
5114 #endif
5115 emit_insn_before (nvptx_gen_warp_bcast (pvar), tail);
5116 }
5117 else
5118 {
5119 /* Includes worker mode, do spill & fill. By construction
5120 we should never have worker mode only. */
5121 broadcast_data_t data;
5122 unsigned size = GET_MODE_SIZE (SImode);
5123 bool vector = (GOMP_DIM_MASK (GOMP_DIM_VECTOR) == mask) != 0;
5124 bool worker = (GOMP_DIM_MASK (GOMP_DIM_WORKER) == mask) != 0;
5125 rtx barrier = GEN_INT (0);
5126 int threads = 0;
5127
5128 data.base = oacc_bcast_sym;
5129 data.ptr = 0;
5130
5131 bool use_partitioning_p = (vector && !worker
5132 && nvptx_mach_max_workers () > 1
5133 && cfun->machine->bcast_partition);
5134 if (use_partitioning_p)
5135 {
5136 data.base = cfun->machine->bcast_partition;
5137 barrier = cfun->machine->sync_bar;
5138 threads = nvptx_mach_vector_length ();
5139 }
5140 gcc_assert (data.base != NULL);
5141 gcc_assert (barrier);
5142
5143 unsigned int psize = ROUND_UP (size, oacc_bcast_align);
5144 unsigned int pnum = (nvptx_mach_vector_length () > PTX_WARP_SIZE
5145 ? nvptx_mach_max_workers () + 1
5146 : 1);
5147
5148 oacc_bcast_partition = MAX (oacc_bcast_partition, psize);
5149 oacc_bcast_size = MAX (oacc_bcast_size, psize * pnum);
5150
5151 data.offset = 0;
5152 emit_insn_before (nvptx_gen_shared_bcast (pvar, PM_read, 0, &data,
5153 vector),
5154 before);
5155
5156 /* Barrier so other workers can see the write. */
5157 emit_insn_before (nvptx_cta_sync (barrier, threads), tail);
5158 data.offset = 0;
5159 emit_insn_before (nvptx_gen_shared_bcast (pvar, PM_write, 0, &data,
5160 vector),
5161 tail);
5162 /* This barrier is needed to avoid worker zero clobbering
5163 the broadcast buffer before all the other workers have
5164 had a chance to read this instance of it. */
5165 emit_insn_before (nvptx_cta_sync (barrier, threads), tail);
5166 }
5167
5168 extract_insn (tail);
5169 rtx unsp = gen_rtx_UNSPEC (BImode, gen_rtvec (1, pvar),
5170 UNSPEC_BR_UNIFIED);
5171 validate_change (tail, recog_data.operand_loc[0], unsp, false);
5172 }
5173
5174 bool seen_label = verify_neutering_jumps (from, vector_jump, worker_jump,
5175 vector_label, worker_label);
5176 if (!seen_label)
5177 verify_neutering_labels (to, vector_label, worker_label);
5178 }
5179
5180 /* PAR is a parallel that is being skipped in its entirety according to
5181 MASK. Treat this as skipping a superblock starting at forked
5182 and ending at joining. */
5183
5184 static void
5185 nvptx_skip_par (unsigned mask, parallel *par)
5186 {
5187 basic_block tail = par->join_block;
5188 gcc_assert (tail->preds->length () == 1);
5189
5190 basic_block pre_tail = (*tail->preds)[0]->src;
5191 gcc_assert (pre_tail->succs->length () == 1);
5192
5193 nvptx_single (mask, par->forked_block, pre_tail);
5194 }
5195
5196 /* If PAR has a single inner parallel and PAR itself only contains
5197 empty entry and exit blocks, swallow the inner PAR. */
5198
5199 static void
5200 nvptx_optimize_inner (parallel *par)
5201 {
5202 parallel *inner = par->inner;
5203
5204 /* We mustn't be the outer dummy par. */
5205 if (!par->mask)
5206 return;
5207
5208 /* We must have a single inner par. */
5209 if (!inner || inner->next)
5210 return;
5211
5212 /* We must only contain 2 blocks ourselves -- the head and tail of
5213 the inner par. */
5214 if (par->blocks.length () != 2)
5215 return;
5216
5217 /* We must be disjoint partitioning. As we only have vector and
5218 worker partitioning, this is sufficient to guarantee the pars
5219 have adjacent partitioning. */
5220 if ((par->mask & inner->mask) & (GOMP_DIM_MASK (GOMP_DIM_MAX) - 1))
5221 /* This indicates malformed code generation. */
5222 return;
5223
5224 /* The outer forked insn should be immediately followed by the inner
5225 fork insn. */
5226 rtx_insn *forked = par->forked_insn;
5227 rtx_insn *fork = BB_END (par->forked_block);
5228
5229 if (NEXT_INSN (forked) != fork)
5230 return;
5231 gcc_checking_assert (recog_memoized (fork) == CODE_FOR_nvptx_fork);
5232
5233 /* The outer joining insn must immediately follow the inner join
5234 insn. */
5235 rtx_insn *joining = par->joining_insn;
5236 rtx_insn *join = inner->join_insn;
5237 if (NEXT_INSN (join) != joining)
5238 return;
5239
5240 /* Preconditions met. Swallow the inner par. */
5241 if (dump_file)
5242 fprintf (dump_file, "Merging loop %x [%d,%d] into %x [%d,%d]\n",
5243 inner->mask, inner->forked_block->index,
5244 inner->join_block->index,
5245 par->mask, par->forked_block->index, par->join_block->index);
5246
5247 par->mask |= inner->mask & (GOMP_DIM_MASK (GOMP_DIM_MAX) - 1);
5248
5249 par->blocks.reserve (inner->blocks.length ());
5250 while (inner->blocks.length ())
5251 par->blocks.quick_push (inner->blocks.pop ());
5252
5253 par->inner = inner->inner;
5254 inner->inner = NULL;
5255
5256 delete inner;
5257 }
5258
5259 /* Process the parallel PAR and all its contained
5260 parallels. We do everything but the neutering. Return mask of
5261 partitioned modes used within this parallel. */
5262
5263 static unsigned
5264 nvptx_process_pars (parallel *par)
5265 {
5266 if (nvptx_optimize)
5267 nvptx_optimize_inner (par);
5268
5269 unsigned inner_mask = par->mask;
5270
5271 /* Do the inner parallels first. */
5272 if (par->inner)
5273 {
5274 par->inner_mask = nvptx_process_pars (par->inner);
5275 inner_mask |= par->inner_mask;
5276 }
5277
5278 bool is_call = (par->mask & GOMP_DIM_MASK (GOMP_DIM_MAX)) != 0;
5279 bool worker = (par->mask & GOMP_DIM_MASK (GOMP_DIM_WORKER));
5280 bool large_vector = ((par->mask & GOMP_DIM_MASK (GOMP_DIM_VECTOR))
5281 && nvptx_mach_vector_length () > PTX_WARP_SIZE);
5282
5283 if (worker || large_vector)
5284 {
5285 nvptx_shared_propagate (false, is_call, par->forked_block,
5286 par->forked_insn, !worker);
5287 bool no_prop_p
5288 = nvptx_shared_propagate (true, is_call, par->forked_block,
5289 par->fork_insn, !worker);
5290 bool empty_loop_p
5291 = !is_call && (NEXT_INSN (par->forked_insn)
5292 && NEXT_INSN (par->forked_insn) == par->joining_insn);
5293 rtx barrier = GEN_INT (0);
5294 int threads = 0;
5295
5296 if (!worker && cfun->machine->sync_bar)
5297 {
5298 barrier = cfun->machine->sync_bar;
5299 threads = nvptx_mach_vector_length ();
5300 }
5301
5302 if (no_prop_p && empty_loop_p)
5303 ;
5304 else if (no_prop_p && is_call)
5305 ;
5306 else
5307 {
5308 /* Insert begin and end synchronizations. */
5309 emit_insn_before (nvptx_cta_sync (barrier, threads),
5310 par->forked_insn);
5311 emit_insn_before (nvptx_cta_sync (barrier, threads), par->join_insn);
5312 }
5313 }
5314 else if (par->mask & GOMP_DIM_MASK (GOMP_DIM_VECTOR))
5315 nvptx_warp_propagate (is_call, par->forked_block, par->forked_insn);
5316
5317 /* Now do siblings. */
5318 if (par->next)
5319 inner_mask |= nvptx_process_pars (par->next);
5320 return inner_mask;
5321 }
5322
5323 /* Neuter the parallel described by PAR. We recurse in depth-first
5324 order. MODES are the partitioning of the execution and OUTER is
5325 the partitioning of the parallels we are contained in. */
5326
5327 static void
5328 nvptx_neuter_pars (parallel *par, unsigned modes, unsigned outer)
5329 {
5330 unsigned me = (par->mask
5331 & (GOMP_DIM_MASK (GOMP_DIM_WORKER)
5332 | GOMP_DIM_MASK (GOMP_DIM_VECTOR)));
5333 unsigned skip_mask = 0, neuter_mask = 0;
5334
5335 if (par->inner)
5336 nvptx_neuter_pars (par->inner, modes, outer | me);
5337
5338 for (unsigned mode = GOMP_DIM_WORKER; mode <= GOMP_DIM_VECTOR; mode++)
5339 {
5340 if ((outer | me) & GOMP_DIM_MASK (mode))
5341 {} /* Mode is partitioned: no neutering. */
5342 else if (!(modes & GOMP_DIM_MASK (mode)))
5343 {} /* Mode is not used: nothing to do. */
5344 else if (par->inner_mask & GOMP_DIM_MASK (mode)
5345 || !par->forked_insn)
5346 /* Partitioned in inner parallels, or we're not a partitioned
5347 at all: neuter individual blocks. */
5348 neuter_mask |= GOMP_DIM_MASK (mode);
5349 else if (!par->parent || !par->parent->forked_insn
5350 || par->parent->inner_mask & GOMP_DIM_MASK (mode))
5351 /* Parent isn't a parallel or contains this paralleling: skip
5352 parallel at this level. */
5353 skip_mask |= GOMP_DIM_MASK (mode);
5354 else
5355 {} /* Parent will skip this parallel itself. */
5356 }
5357
5358 if (neuter_mask)
5359 {
5360 int ix, len;
5361
5362 if (nvptx_optimize)
5363 {
5364 /* Neuter whole SESE regions. */
5365 bb_pair_vec_t regions;
5366
5367 nvptx_find_sese (par->blocks, regions);
5368 len = regions.length ();
5369 for (ix = 0; ix != len; ix++)
5370 {
5371 basic_block from = regions[ix].first;
5372 basic_block to = regions[ix].second;
5373
5374 if (from)
5375 nvptx_single (neuter_mask, from, to);
5376 else
5377 gcc_assert (!to);
5378 }
5379 }
5380 else
5381 {
5382 /* Neuter each BB individually. */
5383 len = par->blocks.length ();
5384 for (ix = 0; ix != len; ix++)
5385 {
5386 basic_block block = par->blocks[ix];
5387
5388 nvptx_single (neuter_mask, block, block);
5389 }
5390 }
5391 }
5392
5393 if (skip_mask)
5394 nvptx_skip_par (skip_mask, par);
5395
5396 if (par->next)
5397 nvptx_neuter_pars (par->next, modes, outer);
5398 }
5399
5400 static void
5401 populate_offload_attrs (offload_attrs *oa)
5402 {
5403 tree attr = oacc_get_fn_attrib (current_function_decl);
5404 tree dims = TREE_VALUE (attr);
5405 unsigned ix;
5406
5407 oa->mask = 0;
5408
5409 for (ix = 0; ix != GOMP_DIM_MAX; ix++, dims = TREE_CHAIN (dims))
5410 {
5411 tree t = TREE_VALUE (dims);
5412 int size = (t == NULL_TREE) ? -1 : TREE_INT_CST_LOW (t);
5413 tree allowed = TREE_PURPOSE (dims);
5414
5415 if (size != 1 && !(allowed && integer_zerop (allowed)))
5416 oa->mask |= GOMP_DIM_MASK (ix);
5417
5418 switch (ix)
5419 {
5420 case GOMP_DIM_GANG:
5421 oa->num_gangs = size;
5422 break;
5423
5424 case GOMP_DIM_WORKER:
5425 oa->num_workers = size;
5426 break;
5427
5428 case GOMP_DIM_VECTOR:
5429 oa->vector_length = size;
5430 break;
5431 }
5432 }
5433 }
5434
5435 #if WORKAROUND_PTXJIT_BUG_2
5436 /* Variant of pc_set that only requires JUMP_P (INSN) if STRICT. This variant
5437 is needed in the nvptx target because the branches generated for
5438 parititioning are NONJUMP_INSN_P, not JUMP_P. */
5439
5440 static rtx
5441 nvptx_pc_set (const rtx_insn *insn, bool strict = true)
5442 {
5443 rtx pat;
5444 if ((strict && !JUMP_P (insn))
5445 || (!strict && !INSN_P (insn)))
5446 return NULL_RTX;
5447 pat = PATTERN (insn);
5448
5449 /* The set is allowed to appear either as the insn pattern or
5450 the first set in a PARALLEL. */
5451 if (GET_CODE (pat) == PARALLEL)
5452 pat = XVECEXP (pat, 0, 0);
5453 if (GET_CODE (pat) == SET && GET_CODE (SET_DEST (pat)) == PC)
5454 return pat;
5455
5456 return NULL_RTX;
5457 }
5458
5459 /* Variant of condjump_label that only requires JUMP_P (INSN) if STRICT. */
5460
5461 static rtx
5462 nvptx_condjump_label (const rtx_insn *insn, bool strict = true)
5463 {
5464 rtx x = nvptx_pc_set (insn, strict);
5465
5466 if (!x)
5467 return NULL_RTX;
5468 x = SET_SRC (x);
5469 if (GET_CODE (x) == LABEL_REF)
5470 return x;
5471 if (GET_CODE (x) != IF_THEN_ELSE)
5472 return NULL_RTX;
5473 if (XEXP (x, 2) == pc_rtx && GET_CODE (XEXP (x, 1)) == LABEL_REF)
5474 return XEXP (x, 1);
5475 if (XEXP (x, 1) == pc_rtx && GET_CODE (XEXP (x, 2)) == LABEL_REF)
5476 return XEXP (x, 2);
5477 return NULL_RTX;
5478 }
5479
5480 /* Insert a dummy ptx insn when encountering a branch to a label with no ptx
5481 insn inbetween the branch and the label. This works around a JIT bug
5482 observed at driver version 384.111, at -O0 for sm_50. */
5483
5484 static void
5485 prevent_branch_around_nothing (void)
5486 {
5487 rtx_insn *seen_label = NULL;
5488 for (rtx_insn *insn = get_insns (); insn; insn = NEXT_INSN (insn))
5489 {
5490 if (INSN_P (insn) && condjump_p (insn))
5491 {
5492 seen_label = label_ref_label (nvptx_condjump_label (insn, false));
5493 continue;
5494 }
5495
5496 if (seen_label == NULL)
5497 continue;
5498
5499 if (NOTE_P (insn) || DEBUG_INSN_P (insn))
5500 continue;
5501
5502 if (INSN_P (insn))
5503 switch (recog_memoized (insn))
5504 {
5505 case CODE_FOR_nvptx_fork:
5506 case CODE_FOR_nvptx_forked:
5507 case CODE_FOR_nvptx_joining:
5508 case CODE_FOR_nvptx_join:
5509 case CODE_FOR_nop:
5510 continue;
5511 case -1:
5512 /* Handle asm ("") and similar. */
5513 if (GET_CODE (PATTERN (insn)) == ASM_INPUT
5514 || GET_CODE (PATTERN (insn)) == ASM_OPERANDS
5515 || (GET_CODE (PATTERN (insn)) == PARALLEL
5516 && asm_noperands (PATTERN (insn)) >= 0))
5517 continue;
5518 /* FALLTHROUGH. */
5519 default:
5520 seen_label = NULL;
5521 continue;
5522 }
5523
5524 if (LABEL_P (insn) && insn == seen_label)
5525 emit_insn_before (gen_fake_nop (), insn);
5526
5527 seen_label = NULL;
5528 }
5529 }
5530 #endif
5531
5532 #ifdef WORKAROUND_PTXJIT_BUG_3
5533 /* Insert two membar.cta insns inbetween two subsequent bar.sync insns. This
5534 works around a hang observed at driver version 390.48 for sm_50. */
5535
5536 static void
5537 workaround_barsyncs (void)
5538 {
5539 bool seen_barsync = false;
5540 for (rtx_insn *insn = get_insns (); insn; insn = NEXT_INSN (insn))
5541 {
5542 if (INSN_P (insn) && recog_memoized (insn) == CODE_FOR_nvptx_barsync)
5543 {
5544 if (seen_barsync)
5545 {
5546 emit_insn_before (gen_nvptx_membar_cta (), insn);
5547 emit_insn_before (gen_nvptx_membar_cta (), insn);
5548 }
5549
5550 seen_barsync = true;
5551 continue;
5552 }
5553
5554 if (!seen_barsync)
5555 continue;
5556
5557 if (NOTE_P (insn) || DEBUG_INSN_P (insn))
5558 continue;
5559 else if (INSN_P (insn))
5560 switch (recog_memoized (insn))
5561 {
5562 case CODE_FOR_nvptx_fork:
5563 case CODE_FOR_nvptx_forked:
5564 case CODE_FOR_nvptx_joining:
5565 case CODE_FOR_nvptx_join:
5566 continue;
5567 default:
5568 break;
5569 }
5570
5571 seen_barsync = false;
5572 }
5573 }
5574 #endif
5575
5576 static rtx
5577 gen_comment (const char *s)
5578 {
5579 const char *sep = " ";
5580 size_t len = strlen (ASM_COMMENT_START) + strlen (sep) + strlen (s) + 1;
5581 char *comment = (char *) alloca (len);
5582 snprintf (comment, len, "%s%s%s", ASM_COMMENT_START, sep, s);
5583 return gen_rtx_ASM_INPUT_loc (VOIDmode, ggc_strdup (comment),
5584 DECL_SOURCE_LOCATION (cfun->decl));
5585 }
5586
5587 /* Initialize all declared regs at function entry.
5588 Advantage : Fool-proof.
5589 Disadvantage: Potentially creates a lot of long live ranges and adds a lot
5590 of insns. */
5591
5592 static void
5593 workaround_uninit_method_1 (void)
5594 {
5595 rtx_insn *first = get_insns ();
5596 rtx_insn *insert_here = NULL;
5597
5598 for (int ix = LAST_VIRTUAL_REGISTER + 1; ix < max_reg_num (); ix++)
5599 {
5600 rtx reg = regno_reg_rtx[ix];
5601
5602 /* Skip undeclared registers. */
5603 if (reg == const0_rtx)
5604 continue;
5605
5606 gcc_assert (CONST0_RTX (GET_MODE (reg)));
5607
5608 start_sequence ();
5609 if (nvptx_comment && first != NULL)
5610 emit_insn (gen_comment ("Start: Added by -minit-regs=1"));
5611 emit_move_insn (reg, CONST0_RTX (GET_MODE (reg)));
5612 rtx_insn *inits = get_insns ();
5613 end_sequence ();
5614
5615 if (dump_file && (dump_flags & TDF_DETAILS))
5616 for (rtx_insn *init = inits; init != NULL; init = NEXT_INSN (init))
5617 fprintf (dump_file, "Default init of reg %u inserted: insn %u\n",
5618 ix, INSN_UID (init));
5619
5620 if (first != NULL)
5621 {
5622 insert_here = emit_insn_before (inits, first);
5623 first = NULL;
5624 }
5625 else
5626 insert_here = emit_insn_after (inits, insert_here);
5627 }
5628
5629 if (nvptx_comment && insert_here != NULL)
5630 emit_insn_after (gen_comment ("End: Added by -minit-regs=1"), insert_here);
5631 }
5632
5633 /* Find uses of regs that are not defined on all incoming paths, and insert a
5634 corresponding def at function entry.
5635 Advantage : Simple.
5636 Disadvantage: Potentially creates long live ranges.
5637 May not catch all cases. F.i. a clobber cuts a live range in
5638 the compiler and may prevent entry_lr_in from being set for a
5639 reg, but the clobber does not translate to a ptx insn, so in
5640 ptx there still may be an uninitialized ptx reg. See f.i.
5641 gcc.c-torture/compile/20020926-1.c. */
5642
5643 static void
5644 workaround_uninit_method_2 (void)
5645 {
5646 auto_bitmap entry_pseudo_uninit;
5647 {
5648 auto_bitmap not_pseudo;
5649 bitmap_set_range (not_pseudo, 0, LAST_VIRTUAL_REGISTER);
5650
5651 bitmap entry_lr_in = DF_LR_IN (ENTRY_BLOCK_PTR_FOR_FN (cfun));
5652 bitmap_and_compl (entry_pseudo_uninit, entry_lr_in, not_pseudo);
5653 }
5654
5655 rtx_insn *first = get_insns ();
5656 rtx_insn *insert_here = NULL;
5657
5658 bitmap_iterator iterator;
5659 unsigned ix;
5660 EXECUTE_IF_SET_IN_BITMAP (entry_pseudo_uninit, 0, ix, iterator)
5661 {
5662 rtx reg = regno_reg_rtx[ix];
5663 gcc_assert (CONST0_RTX (GET_MODE (reg)));
5664
5665 start_sequence ();
5666 if (nvptx_comment && first != NULL)
5667 emit_insn (gen_comment ("Start: Added by -minit-regs=2:"));
5668 emit_move_insn (reg, CONST0_RTX (GET_MODE (reg)));
5669 rtx_insn *inits = get_insns ();
5670 end_sequence ();
5671
5672 if (dump_file && (dump_flags & TDF_DETAILS))
5673 for (rtx_insn *init = inits; init != NULL; init = NEXT_INSN (init))
5674 fprintf (dump_file, "Missing init of reg %u inserted: insn %u\n",
5675 ix, INSN_UID (init));
5676
5677 if (first != NULL)
5678 {
5679 insert_here = emit_insn_before (inits, first);
5680 first = NULL;
5681 }
5682 else
5683 insert_here = emit_insn_after (inits, insert_here);
5684 }
5685
5686 if (nvptx_comment && insert_here != NULL)
5687 emit_insn_after (gen_comment ("End: Added by -minit-regs=2"), insert_here);
5688 }
5689
5690 /* Find uses of regs that are not defined on all incoming paths, and insert a
5691 corresponding def on those.
5692 Advantage : Doesn't create long live ranges.
5693 Disadvantage: More complex, and potentially also more defs. */
5694
5695 static void
5696 workaround_uninit_method_3 (void)
5697 {
5698 auto_bitmap not_pseudo;
5699 bitmap_set_range (not_pseudo, 0, LAST_VIRTUAL_REGISTER);
5700
5701 basic_block bb;
5702 FOR_EACH_BB_FN (bb, cfun)
5703 {
5704 if (single_pred_p (bb))
5705 continue;
5706
5707 auto_bitmap bb_pseudo_uninit;
5708 bitmap_and_compl (bb_pseudo_uninit, DF_LIVE_IN (bb), DF_MIR_IN (bb));
5709 bitmap_and_compl_into (bb_pseudo_uninit, not_pseudo);
5710
5711 bitmap_iterator iterator;
5712 unsigned ix;
5713 EXECUTE_IF_SET_IN_BITMAP (bb_pseudo_uninit, 0, ix, iterator)
5714 {
5715 bool have_false = false;
5716 bool have_true = false;
5717
5718 edge e;
5719 edge_iterator ei;
5720 FOR_EACH_EDGE (e, ei, bb->preds)
5721 {
5722 if (bitmap_bit_p (DF_LIVE_OUT (e->src), ix))
5723 have_true = true;
5724 else
5725 have_false = true;
5726 }
5727 if (have_false ^ have_true)
5728 continue;
5729
5730 FOR_EACH_EDGE (e, ei, bb->preds)
5731 {
5732 if (bitmap_bit_p (DF_LIVE_OUT (e->src), ix))
5733 continue;
5734
5735 rtx reg = regno_reg_rtx[ix];
5736 gcc_assert (CONST0_RTX (GET_MODE (reg)));
5737
5738 start_sequence ();
5739 emit_move_insn (reg, CONST0_RTX (GET_MODE (reg)));
5740 rtx_insn *inits = get_insns ();
5741 end_sequence ();
5742
5743 if (dump_file && (dump_flags & TDF_DETAILS))
5744 for (rtx_insn *init = inits; init != NULL;
5745 init = NEXT_INSN (init))
5746 fprintf (dump_file,
5747 "Missing init of reg %u inserted on edge: %d -> %d:"
5748 " insn %u\n", ix, e->src->index, e->dest->index,
5749 INSN_UID (init));
5750
5751 insert_insn_on_edge (inits, e);
5752 }
5753 }
5754 }
5755
5756 if (nvptx_comment)
5757 FOR_EACH_BB_FN (bb, cfun)
5758 {
5759 if (single_pred_p (bb))
5760 continue;
5761
5762 edge e;
5763 edge_iterator ei;
5764 FOR_EACH_EDGE (e, ei, bb->preds)
5765 {
5766 if (e->insns.r == NULL_RTX)
5767 continue;
5768 start_sequence ();
5769 emit_insn (gen_comment ("Start: Added by -minit-regs=3:"));
5770 emit_insn (e->insns.r);
5771 emit_insn (gen_comment ("End: Added by -minit-regs=3:"));
5772 e->insns.r = get_insns ();
5773 end_sequence ();
5774 }
5775 }
5776
5777 commit_edge_insertions ();
5778 }
5779
5780 static void
5781 workaround_uninit (void)
5782 {
5783 switch (nvptx_init_regs)
5784 {
5785 case 0:
5786 /* Skip. */
5787 break;
5788 case 1:
5789 workaround_uninit_method_1 ();
5790 break;
5791 case 2:
5792 workaround_uninit_method_2 ();
5793 break;
5794 case 3:
5795 workaround_uninit_method_3 ();
5796 break;
5797 default:
5798 gcc_unreachable ();
5799 }
5800 }
5801
5802 /* PTX-specific reorganization
5803 - Split blocks at fork and join instructions
5804 - Compute live registers
5805 - Mark now-unused registers, so function begin doesn't declare
5806 unused registers.
5807 - Insert state propagation when entering partitioned mode
5808 - Insert neutering instructions when in single mode
5809 - Replace subregs with suitable sequences.
5810 */
5811
5812 static void
5813 nvptx_reorg (void)
5814 {
5815 /* We are freeing block_for_insn in the toplev to keep compatibility
5816 with old MDEP_REORGS that are not CFG based. Recompute it now. */
5817 compute_bb_for_insn ();
5818
5819 thread_prologue_and_epilogue_insns ();
5820
5821 /* Split blocks and record interesting unspecs. */
5822 bb_insn_map_t bb_insn_map;
5823
5824 nvptx_split_blocks (&bb_insn_map);
5825
5826 /* Compute live regs */
5827 df_clear_flags (DF_LR_RUN_DCE);
5828 df_set_flags (DF_NO_INSN_RESCAN | DF_NO_HARD_REGS);
5829 df_live_add_problem ();
5830 df_live_set_all_dirty ();
5831 if (nvptx_init_regs == 3)
5832 df_mir_add_problem ();
5833 df_analyze ();
5834 regstat_init_n_sets_and_refs ();
5835
5836 if (dump_file)
5837 df_dump (dump_file);
5838
5839 /* Mark unused regs as unused. */
5840 int max_regs = max_reg_num ();
5841 for (int i = LAST_VIRTUAL_REGISTER + 1; i < max_regs; i++)
5842 if (REG_N_SETS (i) == 0 && REG_N_REFS (i) == 0)
5843 regno_reg_rtx[i] = const0_rtx;
5844
5845 workaround_uninit ();
5846
5847 /* Determine launch dimensions of the function. If it is not an
5848 offloaded function (i.e. this is a regular compiler), the
5849 function has no neutering. */
5850 tree attr = oacc_get_fn_attrib (current_function_decl);
5851 if (attr)
5852 {
5853 /* If we determined this mask before RTL expansion, we could
5854 elide emission of some levels of forks and joins. */
5855 offload_attrs oa;
5856
5857 populate_offload_attrs (&oa);
5858
5859 /* If there is worker neutering, there must be vector
5860 neutering. Otherwise the hardware will fail. */
5861 gcc_assert (!(oa.mask & GOMP_DIM_MASK (GOMP_DIM_WORKER))
5862 || (oa.mask & GOMP_DIM_MASK (GOMP_DIM_VECTOR)));
5863
5864 /* Discover & process partitioned regions. */
5865 parallel *pars = nvptx_discover_pars (&bb_insn_map);
5866 nvptx_process_pars (pars);
5867 nvptx_neuter_pars (pars, oa.mask, 0);
5868 delete pars;
5869 }
5870
5871 /* Replace subregs. */
5872 nvptx_reorg_subreg ();
5873
5874 if (TARGET_UNIFORM_SIMT)
5875 nvptx_reorg_uniform_simt ();
5876
5877 #if WORKAROUND_PTXJIT_BUG_2
5878 prevent_branch_around_nothing ();
5879 #endif
5880
5881 #ifdef WORKAROUND_PTXJIT_BUG_3
5882 workaround_barsyncs ();
5883 #endif
5884
5885 regstat_free_n_sets_and_refs ();
5886
5887 df_finish_pass (true);
5888 }
5889
5890 /* Handle a "kernel" attribute; arguments as in
5891 struct attribute_spec.handler. */
5892
5893 static tree
5894 nvptx_handle_kernel_attribute (tree *node, tree name, tree ARG_UNUSED (args),
5895 int ARG_UNUSED (flags), bool *no_add_attrs)
5896 {
5897 tree decl = *node;
5898
5899 if (TREE_CODE (decl) != FUNCTION_DECL)
5900 {
5901 error ("%qE attribute only applies to functions", name);
5902 *no_add_attrs = true;
5903 }
5904 else if (!VOID_TYPE_P (TREE_TYPE (TREE_TYPE (decl))))
5905 {
5906 error ("%qE attribute requires a void return type", name);
5907 *no_add_attrs = true;
5908 }
5909
5910 return NULL_TREE;
5911 }
5912
5913 /* Handle a "shared" attribute; arguments as in
5914 struct attribute_spec.handler. */
5915
5916 static tree
5917 nvptx_handle_shared_attribute (tree *node, tree name, tree ARG_UNUSED (args),
5918 int ARG_UNUSED (flags), bool *no_add_attrs)
5919 {
5920 tree decl = *node;
5921
5922 if (TREE_CODE (decl) != VAR_DECL)
5923 {
5924 error ("%qE attribute only applies to variables", name);
5925 *no_add_attrs = true;
5926 }
5927 else if (!(TREE_PUBLIC (decl) || TREE_STATIC (decl)))
5928 {
5929 error ("%qE attribute not allowed with auto storage class", name);
5930 *no_add_attrs = true;
5931 }
5932
5933 return NULL_TREE;
5934 }
5935
5936 /* Table of valid machine attributes. */
5937 TARGET_GNU_ATTRIBUTES (nvptx_attribute_table,
5938 {
5939 /* { name, min_len, max_len, decl_req, type_req, fn_type_req,
5940 affects_type_identity, handler, exclude } */
5941 { "kernel", 0, 0, true, false, false, false, nvptx_handle_kernel_attribute,
5942 NULL },
5943 { "shared", 0, 0, true, false, false, false, nvptx_handle_shared_attribute,
5944 NULL }
5945 });
5946
5947 /* Limit vector alignments to BIGGEST_ALIGNMENT. */
5948
5949 static HOST_WIDE_INT
5950 nvptx_vector_alignment (const_tree type)
5951 {
5952 unsigned HOST_WIDE_INT align;
5953 tree size = TYPE_SIZE (type);
5954
5955 /* Ensure align is not bigger than BIGGEST_ALIGNMENT. */
5956 if (tree_fits_uhwi_p (size))
5957 {
5958 align = tree_to_uhwi (size);
5959 align = MIN (align, BIGGEST_ALIGNMENT);
5960 }
5961 else
5962 align = BIGGEST_ALIGNMENT;
5963
5964 /* Ensure align is not smaller than mode alignment. */
5965 align = MAX (align, GET_MODE_ALIGNMENT (TYPE_MODE (type)));
5966
5967 return align;
5968 }
5969
5970 /* Indicate that INSN cannot be duplicated. */
5971
5972 static bool
5973 nvptx_cannot_copy_insn_p (rtx_insn *insn)
5974 {
5975 switch (recog_memoized (insn))
5976 {
5977 case CODE_FOR_nvptx_shufflesi:
5978 case CODE_FOR_nvptx_shufflesf:
5979 case CODE_FOR_nvptx_barsync:
5980 case CODE_FOR_nvptx_fork:
5981 case CODE_FOR_nvptx_forked:
5982 case CODE_FOR_nvptx_joining:
5983 case CODE_FOR_nvptx_join:
5984 return true;
5985 default:
5986 return false;
5987 }
5988 }
5989
5990 /* Section anchors do not work. Initialization for flag_section_anchor
5991 probes the existence of the anchoring target hooks and prevents
5992 anchoring if they don't exist. However, we may be being used with
5993 a host-side compiler that does support anchoring, and hence see
5994 the anchor flag set (as it's not recalculated). So provide an
5995 implementation denying anchoring. */
5996
5997 static bool
5998 nvptx_use_anchors_for_symbol_p (const_rtx ARG_UNUSED (a))
5999 {
6000 return false;
6001 }
6002
6003 /* Record a symbol for mkoffload to enter into the mapping table. */
6004
6005 static void
6006 nvptx_record_offload_symbol (tree decl)
6007 {
6008 switch (TREE_CODE (decl))
6009 {
6010 case VAR_DECL:
6011 fprintf (asm_out_file, "//:VAR_MAP \"%s\"\n",
6012 IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl)));
6013 break;
6014
6015 case FUNCTION_DECL:
6016 {
6017 tree attr = oacc_get_fn_attrib (decl);
6018 /* OpenMP offloading does not set this attribute. */
6019 tree dims = attr ? TREE_VALUE (attr) : NULL_TREE;
6020
6021 fprintf (asm_out_file, "//:");
6022 if (lookup_attribute ("omp declare target indirect",
6023 DECL_ATTRIBUTES (decl)))
6024 fprintf (asm_out_file, "IND_FUNC_MAP");
6025 else
6026 fprintf (asm_out_file, "FUNC_MAP");
6027 fprintf (asm_out_file, " \"%s\"",
6028 IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl)));
6029
6030 for (; dims; dims = TREE_CHAIN (dims))
6031 {
6032 int size = TREE_INT_CST_LOW (TREE_VALUE (dims));
6033
6034 gcc_assert (!TREE_PURPOSE (dims));
6035 fprintf (asm_out_file, ", %#x", size);
6036 }
6037
6038 fprintf (asm_out_file, "\n");
6039 }
6040 break;
6041
6042 default:
6043 gcc_unreachable ();
6044 }
6045 }
6046
6047 /* Fake "sections support", just for 'exception_section'. */
6048
6049 static void
6050 nvptx_output_section_asm_op (const char *directive)
6051 {
6052 static char prev_section = '?';
6053
6054 gcc_checking_assert (directive[1] == '\0');
6055 const char new_section = directive[0];
6056 gcc_checking_assert (new_section != prev_section);
6057 switch (new_section)
6058 {
6059 case 'T':
6060 case 'D':
6061 if (prev_section == 'E')
6062 /* We're leaving the 'exception_section'. End the comment block. */
6063 fprintf (asm_out_file, "\tEND '.gcc_except_table' */\n");
6064 break;
6065 case 'E':
6066 /* We're entering the 'exception_section'. Put into a comment block
6067 whatever GCC decides to emit. We assume:
6068 - No nested comment blocks.
6069 - Going to leave 'exception_section' before end of file.
6070 Should any of these ever get violated, this will result in PTX-level
6071 syntax errors. */
6072 fprintf (asm_out_file, "\t/* BEGIN '.gcc_except_table'\n");
6073 break;
6074 default:
6075 gcc_unreachable ();
6076 }
6077 prev_section = new_section;
6078 }
6079
6080 static void
6081 nvptx_asm_init_sections (void)
6082 {
6083 /* Like '#define TEXT_SECTION_ASM_OP ""', just with different 'callback'. */
6084 text_section = get_unnamed_section (SECTION_CODE,
6085 nvptx_output_section_asm_op, "T");
6086 /* Like '#define DATA_SECTION_ASM_OP ""', just with different 'callback'. */
6087 data_section = get_unnamed_section (SECTION_WRITE,
6088 nvptx_output_section_asm_op, "D");
6089 /* In order to later be able to recognize the 'exception_section', we set it
6090 up here, instead of letting 'gcc/except.cc:switch_to_exception_section'
6091 pick the 'data_section'. */
6092 exception_section = get_unnamed_section (0,
6093 nvptx_output_section_asm_op, "E");
6094 }
6095
6096 /* Implement TARGET_ASM_FILE_START. Write the kinds of things ptxas expects
6097 at the start of a file. */
6098
6099 static void
6100 nvptx_file_start (void)
6101 {
6102 fputs ("// BEGIN PREAMBLE\n", asm_out_file);
6103
6104 fputs ("\t.version\t", asm_out_file);
6105 fputs (ptx_version_to_string (ptx_version_option), asm_out_file);
6106 fputs ("\n", asm_out_file);
6107
6108 fputs ("\t.target\tsm_", asm_out_file);
6109 fputs (sm_version_to_string (ptx_isa_option), asm_out_file);
6110 fputs ("\n", asm_out_file);
6111
6112 fprintf (asm_out_file, "\t.address_size %d\n", GET_MODE_BITSIZE (Pmode));
6113
6114 fputs ("// END PREAMBLE\n", asm_out_file);
6115 }
6116
6117 /* Emit a declaration for a worker and vector-level buffer in .shared
6118 memory. */
6119
6120 static void
6121 write_shared_buffer (FILE *file, rtx sym, unsigned align, unsigned size)
6122 {
6123 const char *name = XSTR (sym, 0);
6124
6125 write_var_marker (file, true, false, name);
6126 fprintf (file, ".shared .align %d .u8 %s[%d];\n",
6127 align, name, size);
6128 }
6129
6130 /* Write out the function declarations we've collected and declare storage
6131 for the broadcast buffer. */
6132
6133 static void
6134 nvptx_file_end (void)
6135 {
6136 hash_table<tree_hasher>::iterator iter;
6137 tree decl;
6138 FOR_EACH_HASH_TABLE_ELEMENT (*needed_fndecls_htab, decl, tree, iter)
6139 nvptx_record_fndecl (decl);
6140 fputs (func_decls.str().c_str(), asm_out_file);
6141
6142 if (oacc_bcast_size)
6143 write_shared_buffer (asm_out_file, oacc_bcast_sym,
6144 oacc_bcast_align, oacc_bcast_size);
6145
6146 if (worker_red_size)
6147 write_shared_buffer (asm_out_file, worker_red_sym,
6148 worker_red_align, worker_red_size);
6149
6150 if (vector_red_size)
6151 write_shared_buffer (asm_out_file, vector_red_sym,
6152 vector_red_align, vector_red_size);
6153
6154 if (gang_private_shared_size)
6155 write_shared_buffer (asm_out_file, gang_private_shared_sym,
6156 gang_private_shared_align, gang_private_shared_size);
6157
6158 if (need_softstack_decl)
6159 {
6160 write_var_marker (asm_out_file, false, true, "__nvptx_stacks");
6161 /* 32 is the maximum number of warps in a block. Even though it's an
6162 external declaration, emit the array size explicitly; otherwise, it
6163 may fail at PTX JIT time if the definition is later in link order. */
6164 fprintf (asm_out_file, ".extern .shared .u%d __nvptx_stacks[32];\n",
6165 POINTER_SIZE);
6166 }
6167 if (need_unisimt_decl)
6168 {
6169 write_var_marker (asm_out_file, false, true, "__nvptx_uni");
6170 fprintf (asm_out_file, ".extern .shared .u32 __nvptx_uni[32];\n");
6171 }
6172 }
6173
6174 /* Expander for the shuffle builtins. */
6175
6176 static rtx
6177 nvptx_expand_shuffle (tree exp, rtx target, machine_mode mode, int ignore)
6178 {
6179 if (ignore)
6180 return target;
6181
6182 rtx src = expand_expr (CALL_EXPR_ARG (exp, 0),
6183 NULL_RTX, mode, EXPAND_NORMAL);
6184 if (!REG_P (src))
6185 src = copy_to_mode_reg (mode, src);
6186
6187 rtx idx = expand_expr (CALL_EXPR_ARG (exp, 1),
6188 NULL_RTX, SImode, EXPAND_NORMAL);
6189 rtx op = expand_expr (CALL_EXPR_ARG (exp, 2),
6190 NULL_RTX, SImode, EXPAND_NORMAL);
6191
6192 if (!REG_P (idx) && GET_CODE (idx) != CONST_INT)
6193 idx = copy_to_mode_reg (SImode, idx);
6194
6195 rtx pat = nvptx_gen_shuffle (target, src, idx,
6196 (nvptx_shuffle_kind) INTVAL (op));
6197 if (pat)
6198 emit_insn (pat);
6199
6200 return target;
6201 }
6202
6203 /* Expander for the bit reverse builtins. */
6204
6205 static rtx
6206 nvptx_expand_brev (tree exp, rtx target, machine_mode mode, int ignore)
6207 {
6208 if (ignore)
6209 return target;
6210
6211 rtx arg = expand_expr (CALL_EXPR_ARG (exp, 0),
6212 NULL_RTX, mode, EXPAND_NORMAL);
6213 if (!REG_P (arg))
6214 arg = copy_to_mode_reg (mode, arg);
6215 if (!target)
6216 target = gen_reg_rtx (mode);
6217 rtx pat;
6218 if (mode == SImode)
6219 pat = gen_bitrevsi2 (target, arg);
6220 else
6221 pat = gen_bitrevdi2 (target, arg);
6222 emit_insn (pat);
6223 return target;
6224 }
6225
6226 const char *
6227 nvptx_output_red_partition (rtx dst, rtx offset)
6228 {
6229 const char *zero_offset = "\t\tmov.u64\t%%r%d, %%r%d; // vred buffer\n";
6230 const char *with_offset = "\t\tadd.u64\t%%r%d, %%r%d, %d; // vred buffer\n";
6231
6232 if (offset == const0_rtx)
6233 fprintf (asm_out_file, zero_offset, REGNO (dst),
6234 REGNO (cfun->machine->red_partition));
6235 else
6236 fprintf (asm_out_file, with_offset, REGNO (dst),
6237 REGNO (cfun->machine->red_partition), UINTVAL (offset));
6238
6239 return "";
6240 }
6241
6242 /* Shared-memory reduction address expander. */
6243
6244 static rtx
6245 nvptx_expand_shared_addr (tree exp, rtx target,
6246 machine_mode ARG_UNUSED (mode), int ignore,
6247 int vector)
6248 {
6249 if (ignore)
6250 return target;
6251
6252 unsigned align = TREE_INT_CST_LOW (CALL_EXPR_ARG (exp, 2));
6253 unsigned offset = TREE_INT_CST_LOW (CALL_EXPR_ARG (exp, 0));
6254 unsigned size = TREE_INT_CST_LOW (CALL_EXPR_ARG (exp, 1));
6255 rtx addr = worker_red_sym;
6256
6257 if (vector)
6258 {
6259 offload_attrs oa;
6260
6261 populate_offload_attrs (&oa);
6262
6263 unsigned int psize = ROUND_UP (size + offset, align);
6264 unsigned int pnum = nvptx_mach_max_workers ();
6265 vector_red_partition = MAX (vector_red_partition, psize);
6266 vector_red_size = MAX (vector_red_size, psize * pnum);
6267 vector_red_align = MAX (vector_red_align, align);
6268
6269 if (cfun->machine->red_partition == NULL)
6270 cfun->machine->red_partition = gen_reg_rtx (Pmode);
6271
6272 addr = gen_reg_rtx (Pmode);
6273 emit_insn (gen_nvptx_red_partition (addr, GEN_INT (offset)));
6274 }
6275 else
6276 {
6277 worker_red_align = MAX (worker_red_align, align);
6278 worker_red_size = MAX (worker_red_size, size + offset);
6279
6280 if (offset)
6281 {
6282 addr = gen_rtx_PLUS (Pmode, addr, GEN_INT (offset));
6283 addr = gen_rtx_CONST (Pmode, addr);
6284 }
6285 }
6286
6287 emit_move_insn (target, addr);
6288 return target;
6289 }
6290
6291 /* Expand the CMP_SWAP PTX builtins. We have our own versions that do
6292 not require taking the address of any object, other than the memory
6293 cell being operated on. */
6294
6295 static rtx
6296 nvptx_expand_cmp_swap (tree exp, rtx target,
6297 machine_mode ARG_UNUSED (m), int ARG_UNUSED (ignore))
6298 {
6299 machine_mode mode = TYPE_MODE (TREE_TYPE (exp));
6300
6301 if (!target)
6302 target = gen_reg_rtx (mode);
6303
6304 rtx mem = expand_expr (CALL_EXPR_ARG (exp, 0),
6305 NULL_RTX, Pmode, EXPAND_NORMAL);
6306 rtx cmp = expand_expr (CALL_EXPR_ARG (exp, 1),
6307 NULL_RTX, mode, EXPAND_NORMAL);
6308 rtx src = expand_expr (CALL_EXPR_ARG (exp, 2),
6309 NULL_RTX, mode, EXPAND_NORMAL);
6310 rtx pat;
6311
6312 mem = gen_rtx_MEM (mode, mem);
6313 if (!REG_P (cmp))
6314 cmp = copy_to_mode_reg (mode, cmp);
6315 if (!REG_P (src))
6316 src = copy_to_mode_reg (mode, src);
6317
6318 if (mode == SImode)
6319 pat = gen_atomic_compare_and_swapsi_1 (target, mem, cmp, src, const0_rtx);
6320 else
6321 pat = gen_atomic_compare_and_swapdi_1 (target, mem, cmp, src, const0_rtx);
6322
6323 emit_insn (pat);
6324
6325 return target;
6326 }
6327
6328
6329 /* Codes for all the NVPTX builtins. */
6330 enum nvptx_builtins
6331 {
6332 NVPTX_BUILTIN_SHUFFLE,
6333 NVPTX_BUILTIN_SHUFFLELL,
6334 NVPTX_BUILTIN_WORKER_ADDR,
6335 NVPTX_BUILTIN_VECTOR_ADDR,
6336 NVPTX_BUILTIN_CMP_SWAP,
6337 NVPTX_BUILTIN_CMP_SWAPLL,
6338 NVPTX_BUILTIN_MEMBAR_GL,
6339 NVPTX_BUILTIN_MEMBAR_CTA,
6340 NVPTX_BUILTIN_BAR_RED_AND,
6341 NVPTX_BUILTIN_BAR_RED_OR,
6342 NVPTX_BUILTIN_BAR_RED_POPC,
6343 NVPTX_BUILTIN_BREV,
6344 NVPTX_BUILTIN_BREVLL,
6345 NVPTX_BUILTIN_MAX
6346 };
6347
6348 /* Expander for 'bar.red' instruction builtins. */
6349
6350 static rtx
6351 nvptx_expand_bar_red (tree exp, rtx target,
6352 machine_mode ARG_UNUSED (m), int ARG_UNUSED (ignore))
6353 {
6354 int code = DECL_MD_FUNCTION_CODE (TREE_OPERAND (CALL_EXPR_FN (exp), 0));
6355 machine_mode mode = TYPE_MODE (TREE_TYPE (exp));
6356
6357 if (!target)
6358 target = gen_reg_rtx (mode);
6359
6360 rtx pred, dst;
6361 rtx bar = expand_expr (CALL_EXPR_ARG (exp, 0),
6362 NULL_RTX, SImode, EXPAND_NORMAL);
6363 rtx nthr = expand_expr (CALL_EXPR_ARG (exp, 1),
6364 NULL_RTX, SImode, EXPAND_NORMAL);
6365 rtx cpl = expand_expr (CALL_EXPR_ARG (exp, 2),
6366 NULL_RTX, SImode, EXPAND_NORMAL);
6367 rtx redop = expand_expr (CALL_EXPR_ARG (exp, 3),
6368 NULL_RTX, SImode, EXPAND_NORMAL);
6369 if (CONST_INT_P (bar))
6370 {
6371 if (INTVAL (bar) < 0 || INTVAL (bar) > 15)
6372 {
6373 error_at (EXPR_LOCATION (exp),
6374 "barrier value must be within [0,15]");
6375 return const0_rtx;
6376 }
6377 }
6378 else if (!REG_P (bar))
6379 bar = copy_to_mode_reg (SImode, bar);
6380
6381 if (!CONST_INT_P (nthr) && !REG_P (nthr))
6382 nthr = copy_to_mode_reg (SImode, nthr);
6383
6384 if (!CONST_INT_P (cpl))
6385 {
6386 error_at (EXPR_LOCATION (exp),
6387 "complement argument must be constant");
6388 return const0_rtx;
6389 }
6390
6391 pred = gen_reg_rtx (BImode);
6392 if (!REG_P (redop))
6393 redop = copy_to_mode_reg (SImode, redop);
6394 emit_insn (gen_rtx_SET (pred, gen_rtx_NE (BImode, redop, GEN_INT (0))));
6395 redop = pred;
6396
6397 rtx pat;
6398 switch (code)
6399 {
6400 case NVPTX_BUILTIN_BAR_RED_AND:
6401 dst = gen_reg_rtx (BImode);
6402 pat = gen_nvptx_barred_and (dst, bar, nthr, cpl, redop);
6403 break;
6404 case NVPTX_BUILTIN_BAR_RED_OR:
6405 dst = gen_reg_rtx (BImode);
6406 pat = gen_nvptx_barred_or (dst, bar, nthr, cpl, redop);
6407 break;
6408 case NVPTX_BUILTIN_BAR_RED_POPC:
6409 dst = gen_reg_rtx (SImode);
6410 pat = gen_nvptx_barred_popc (dst, bar, nthr, cpl, redop);
6411 break;
6412 default:
6413 gcc_unreachable ();
6414 }
6415 emit_insn (pat);
6416 if (GET_MODE (dst) == BImode)
6417 {
6418 rtx tmp = gen_reg_rtx (mode);
6419 emit_insn (gen_rtx_SET (tmp, gen_rtx_NE (mode, dst, GEN_INT (0))));
6420 dst = tmp;
6421 }
6422 emit_move_insn (target, dst);
6423 return target;
6424 }
6425
6426 static GTY(()) tree nvptx_builtin_decls[NVPTX_BUILTIN_MAX];
6427
6428 /* Return the NVPTX builtin for CODE. */
6429
6430 static tree
6431 nvptx_builtin_decl (unsigned code, bool ARG_UNUSED (initialize_p))
6432 {
6433 if (code >= NVPTX_BUILTIN_MAX)
6434 return error_mark_node;
6435
6436 return nvptx_builtin_decls[code];
6437 }
6438
6439 /* Set up all builtin functions for this target. */
6440
6441 static void
6442 nvptx_init_builtins (void)
6443 {
6444 #define DEF(ID, NAME, T) \
6445 (nvptx_builtin_decls[NVPTX_BUILTIN_ ## ID] \
6446 = add_builtin_function ("__builtin_nvptx_" NAME, \
6447 build_function_type_list T, \
6448 NVPTX_BUILTIN_ ## ID, BUILT_IN_MD, NULL, NULL))
6449 #define ST sizetype
6450 #define UINT unsigned_type_node
6451 #define LLUINT long_long_unsigned_type_node
6452 #define PTRVOID ptr_type_node
6453 #define VOID void_type_node
6454
6455 DEF (SHUFFLE, "shuffle", (UINT, UINT, UINT, UINT, NULL_TREE));
6456 DEF (SHUFFLELL, "shufflell", (LLUINT, LLUINT, UINT, UINT, NULL_TREE));
6457 DEF (WORKER_ADDR, "worker_addr",
6458 (PTRVOID, ST, UINT, UINT, NULL_TREE));
6459 DEF (VECTOR_ADDR, "vector_addr",
6460 (PTRVOID, ST, UINT, UINT, NULL_TREE));
6461 DEF (CMP_SWAP, "cmp_swap", (UINT, PTRVOID, UINT, UINT, NULL_TREE));
6462 DEF (CMP_SWAPLL, "cmp_swapll", (LLUINT, PTRVOID, LLUINT, LLUINT, NULL_TREE));
6463 DEF (MEMBAR_GL, "membar_gl", (VOID, VOID, NULL_TREE));
6464 DEF (MEMBAR_CTA, "membar_cta", (VOID, VOID, NULL_TREE));
6465
6466 DEF (BAR_RED_AND, "bar_red_and",
6467 (UINT, UINT, UINT, UINT, UINT, NULL_TREE));
6468 DEF (BAR_RED_OR, "bar_red_or",
6469 (UINT, UINT, UINT, UINT, UINT, NULL_TREE));
6470 DEF (BAR_RED_POPC, "bar_red_popc",
6471 (UINT, UINT, UINT, UINT, UINT, NULL_TREE));
6472
6473 DEF (BREV, "brev", (UINT, UINT, NULL_TREE));
6474 DEF (BREVLL, "brevll", (LLUINT, LLUINT, NULL_TREE));
6475
6476 #undef DEF
6477 #undef ST
6478 #undef UINT
6479 #undef LLUINT
6480 #undef PTRVOID
6481 }
6482
6483 /* Expand an expression EXP that calls a built-in function,
6484 with result going to TARGET if that's convenient
6485 (and in mode MODE if that's convenient).
6486 SUBTARGET may be used as the target for computing one of EXP's operands.
6487 IGNORE is nonzero if the value is to be ignored. */
6488
6489 static rtx
6490 nvptx_expand_builtin (tree exp, rtx target, rtx ARG_UNUSED (subtarget),
6491 machine_mode mode, int ignore)
6492 {
6493 tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
6494 switch (DECL_MD_FUNCTION_CODE (fndecl))
6495 {
6496 case NVPTX_BUILTIN_SHUFFLE:
6497 case NVPTX_BUILTIN_SHUFFLELL:
6498 return nvptx_expand_shuffle (exp, target, mode, ignore);
6499
6500 case NVPTX_BUILTIN_WORKER_ADDR:
6501 return nvptx_expand_shared_addr (exp, target, mode, ignore, false);
6502
6503 case NVPTX_BUILTIN_VECTOR_ADDR:
6504 return nvptx_expand_shared_addr (exp, target, mode, ignore, true);
6505
6506 case NVPTX_BUILTIN_CMP_SWAP:
6507 case NVPTX_BUILTIN_CMP_SWAPLL:
6508 return nvptx_expand_cmp_swap (exp, target, mode, ignore);
6509
6510 case NVPTX_BUILTIN_MEMBAR_GL:
6511 emit_insn (gen_nvptx_membar_gl ());
6512 return NULL_RTX;
6513
6514 case NVPTX_BUILTIN_MEMBAR_CTA:
6515 emit_insn (gen_nvptx_membar_cta ());
6516 return NULL_RTX;
6517
6518 case NVPTX_BUILTIN_BAR_RED_AND:
6519 case NVPTX_BUILTIN_BAR_RED_OR:
6520 case NVPTX_BUILTIN_BAR_RED_POPC:
6521 return nvptx_expand_bar_red (exp, target, mode, ignore);
6522
6523 case NVPTX_BUILTIN_BREV:
6524 case NVPTX_BUILTIN_BREVLL:
6525 return nvptx_expand_brev (exp, target, mode, ignore);
6526
6527 default: gcc_unreachable ();
6528 }
6529 }
6530
6531 /* Implement TARGET_SIMT_VF target hook: number of threads in a warp. */
6532
6533 static int
6534 nvptx_simt_vf ()
6535 {
6536 return PTX_WARP_SIZE;
6537 }
6538
6539 /* Return 1 if TRAIT NAME is present in the OpenMP context's
6540 device trait set, return 0 if not present in any OpenMP context in the
6541 whole translation unit, or -1 if not present in the current OpenMP context
6542 but might be present in another OpenMP context in the same TU. */
6543
6544 int
6545 nvptx_omp_device_kind_arch_isa (enum omp_device_kind_arch_isa trait,
6546 const char *name)
6547 {
6548 switch (trait)
6549 {
6550 case omp_device_kind:
6551 return strcmp (name, "gpu") == 0;
6552 case omp_device_arch:
6553 return (strcmp (name, "nvptx") == 0
6554 || (TARGET_ABI64 && strcmp (name, "nvptx64") == 0));
6555 case omp_device_isa:
6556 #define NVPTX_SM(XX, SEP) \
6557 { \
6558 if (strcmp (name, "sm_" #XX) == 0) \
6559 return ptx_isa_option == PTX_ISA_SM ## XX; \
6560 }
6561 #include "nvptx-sm.def"
6562 #undef NVPTX_SM
6563 return 0;
6564 default:
6565 gcc_unreachable ();
6566 }
6567 }
6568
6569 static bool
6570 nvptx_welformed_vector_length_p (int l)
6571 {
6572 gcc_assert (l > 0);
6573 return l % PTX_WARP_SIZE == 0;
6574 }
6575
6576 static void
6577 nvptx_apply_dim_limits (int dims[])
6578 {
6579 /* Check that the vector_length is not too large. */
6580 if (dims[GOMP_DIM_VECTOR] > PTX_MAX_VECTOR_LENGTH)
6581 dims[GOMP_DIM_VECTOR] = PTX_MAX_VECTOR_LENGTH;
6582
6583 /* Check that the number of workers is not too large. */
6584 if (dims[GOMP_DIM_WORKER] > PTX_WORKER_LENGTH)
6585 dims[GOMP_DIM_WORKER] = PTX_WORKER_LENGTH;
6586
6587 /* Ensure that num_worker * vector_length <= cta size. */
6588 if (dims[GOMP_DIM_WORKER] > 0 && dims[GOMP_DIM_VECTOR] > 0
6589 && dims[GOMP_DIM_WORKER] * dims[GOMP_DIM_VECTOR] > PTX_CTA_SIZE)
6590 dims[GOMP_DIM_VECTOR] = PTX_WARP_SIZE;
6591
6592 /* If we need a per-worker barrier ... . */
6593 if (dims[GOMP_DIM_WORKER] > 0 && dims[GOMP_DIM_VECTOR] > 0
6594 && dims[GOMP_DIM_VECTOR] > PTX_WARP_SIZE)
6595 /* Don't use more barriers than available. */
6596 dims[GOMP_DIM_WORKER] = MIN (dims[GOMP_DIM_WORKER],
6597 PTX_NUM_PER_WORKER_BARRIERS);
6598 }
6599
6600 /* Return true if FNDECL contains calls to vector-partitionable routines. */
6601
6602 static bool
6603 has_vector_partitionable_routine_calls_p (tree fndecl)
6604 {
6605 if (!fndecl)
6606 return false;
6607
6608 basic_block bb;
6609 FOR_EACH_BB_FN (bb, DECL_STRUCT_FUNCTION (fndecl))
6610 for (gimple_stmt_iterator i = gsi_start_bb (bb); !gsi_end_p (i);
6611 gsi_next_nondebug (&i))
6612 {
6613 gimple *stmt = gsi_stmt (i);
6614 if (gimple_code (stmt) != GIMPLE_CALL)
6615 continue;
6616
6617 tree callee = gimple_call_fndecl (stmt);
6618 if (!callee)
6619 continue;
6620
6621 tree attrs = oacc_get_fn_attrib (callee);
6622 if (attrs == NULL_TREE)
6623 return false;
6624
6625 int partition_level = oacc_fn_attrib_level (attrs);
6626 bool seq_routine_p = partition_level == GOMP_DIM_MAX;
6627 if (!seq_routine_p)
6628 return true;
6629 }
6630
6631 return false;
6632 }
6633
6634 /* As nvptx_goacc_validate_dims, but does not return bool to indicate whether
6635 DIMS has changed. */
6636
6637 static void
6638 nvptx_goacc_validate_dims_1 (tree decl, int dims[], int fn_level, unsigned used)
6639 {
6640 bool oacc_default_dims_p = false;
6641 bool oacc_min_dims_p = false;
6642 bool offload_region_p = false;
6643 bool routine_p = false;
6644 bool routine_seq_p = false;
6645 int default_vector_length = -1;
6646
6647 if (decl == NULL_TREE)
6648 {
6649 if (fn_level == -1)
6650 oacc_default_dims_p = true;
6651 else if (fn_level == -2)
6652 oacc_min_dims_p = true;
6653 else
6654 gcc_unreachable ();
6655 }
6656 else if (fn_level == -1)
6657 offload_region_p = true;
6658 else if (0 <= fn_level && fn_level <= GOMP_DIM_MAX)
6659 {
6660 routine_p = true;
6661 routine_seq_p = fn_level == GOMP_DIM_MAX;
6662 }
6663 else
6664 gcc_unreachable ();
6665
6666 if (oacc_min_dims_p)
6667 {
6668 gcc_assert (dims[GOMP_DIM_VECTOR] == 1);
6669 gcc_assert (dims[GOMP_DIM_WORKER] == 1);
6670 gcc_assert (dims[GOMP_DIM_GANG] == 1);
6671
6672 dims[GOMP_DIM_VECTOR] = PTX_WARP_SIZE;
6673 return;
6674 }
6675
6676 if (routine_p)
6677 {
6678 if (!routine_seq_p)
6679 dims[GOMP_DIM_VECTOR] = PTX_WARP_SIZE;
6680
6681 return;
6682 }
6683
6684 if (oacc_default_dims_p)
6685 {
6686 /* -1 : not set
6687 0 : set at runtime, f.i. -fopenacc-dims=-
6688 >= 1: set at compile time, f.i. -fopenacc-dims=1. */
6689 gcc_assert (dims[GOMP_DIM_VECTOR] >= -1);
6690 gcc_assert (dims[GOMP_DIM_WORKER] >= -1);
6691 gcc_assert (dims[GOMP_DIM_GANG] >= -1);
6692
6693 /* But -fopenacc-dims=- is not yet supported on trunk. */
6694 gcc_assert (dims[GOMP_DIM_VECTOR] != 0);
6695 gcc_assert (dims[GOMP_DIM_WORKER] != 0);
6696 gcc_assert (dims[GOMP_DIM_GANG] != 0);
6697 }
6698
6699 if (offload_region_p)
6700 {
6701 /* -1 : not set
6702 0 : set using variable, f.i. num_gangs (n)
6703 >= 1: set using constant, f.i. num_gangs (1). */
6704 gcc_assert (dims[GOMP_DIM_VECTOR] >= -1);
6705 gcc_assert (dims[GOMP_DIM_WORKER] >= -1);
6706 gcc_assert (dims[GOMP_DIM_GANG] >= -1);
6707 }
6708
6709 if (offload_region_p)
6710 default_vector_length = oacc_get_default_dim (GOMP_DIM_VECTOR);
6711 else
6712 /* oacc_default_dims_p. */
6713 default_vector_length = PTX_DEFAULT_VECTOR_LENGTH;
6714
6715 int old_dims[GOMP_DIM_MAX];
6716 unsigned int i;
6717 for (i = 0; i < GOMP_DIM_MAX; ++i)
6718 old_dims[i] = dims[i];
6719
6720 const char *vector_reason = NULL;
6721 if (offload_region_p && has_vector_partitionable_routine_calls_p (decl))
6722 {
6723 default_vector_length = PTX_WARP_SIZE;
6724
6725 if (dims[GOMP_DIM_VECTOR] > PTX_WARP_SIZE)
6726 {
6727 vector_reason = G_("using %<vector_length (%d)%> due to call to"
6728 " vector-partitionable routine, ignoring %d");
6729 dims[GOMP_DIM_VECTOR] = PTX_WARP_SIZE;
6730 }
6731 }
6732
6733 if (dims[GOMP_DIM_VECTOR] == 0)
6734 {
6735 vector_reason = G_("using %<vector_length (%d)%>, ignoring runtime setting");
6736 dims[GOMP_DIM_VECTOR] = default_vector_length;
6737 }
6738
6739 if (dims[GOMP_DIM_VECTOR] > 0
6740 && !nvptx_welformed_vector_length_p (dims[GOMP_DIM_VECTOR]))
6741 dims[GOMP_DIM_VECTOR] = default_vector_length;
6742
6743 nvptx_apply_dim_limits (dims);
6744
6745 if (dims[GOMP_DIM_VECTOR] != old_dims[GOMP_DIM_VECTOR])
6746 warning_at (decl ? DECL_SOURCE_LOCATION (decl) : UNKNOWN_LOCATION, 0,
6747 vector_reason != NULL
6748 ? vector_reason
6749 : G_("using %<vector_length (%d)%>, ignoring %d"),
6750 dims[GOMP_DIM_VECTOR], old_dims[GOMP_DIM_VECTOR]);
6751
6752 if (dims[GOMP_DIM_WORKER] != old_dims[GOMP_DIM_WORKER])
6753 warning_at (decl ? DECL_SOURCE_LOCATION (decl) : UNKNOWN_LOCATION, 0,
6754 G_("using %<num_workers (%d)%>, ignoring %d"),
6755 dims[GOMP_DIM_WORKER], old_dims[GOMP_DIM_WORKER]);
6756
6757 if (oacc_default_dims_p)
6758 {
6759 if (dims[GOMP_DIM_VECTOR] < 0)
6760 dims[GOMP_DIM_VECTOR] = default_vector_length;
6761 if (dims[GOMP_DIM_WORKER] < 0)
6762 dims[GOMP_DIM_WORKER] = PTX_DEFAULT_RUNTIME_DIM;
6763 if (dims[GOMP_DIM_GANG] < 0)
6764 dims[GOMP_DIM_GANG] = PTX_DEFAULT_RUNTIME_DIM;
6765 nvptx_apply_dim_limits (dims);
6766 }
6767
6768 if (offload_region_p)
6769 {
6770 for (i = 0; i < GOMP_DIM_MAX; i++)
6771 {
6772 if (!(dims[i] < 0))
6773 continue;
6774
6775 if ((used & GOMP_DIM_MASK (i)) == 0)
6776 /* Function oacc_validate_dims will apply the minimal dimension. */
6777 continue;
6778
6779 dims[i] = (i == GOMP_DIM_VECTOR
6780 ? default_vector_length
6781 : oacc_get_default_dim (i));
6782 }
6783
6784 nvptx_apply_dim_limits (dims);
6785 }
6786 }
6787
6788 /* Validate compute dimensions of an OpenACC offload or routine, fill
6789 in non-unity defaults. FN_LEVEL indicates the level at which a
6790 routine might spawn a loop. It is negative for non-routines. If
6791 DECL is null, we are validating the default dimensions. */
6792
6793 static bool
6794 nvptx_goacc_validate_dims (tree decl, int dims[], int fn_level, unsigned used)
6795 {
6796 int old_dims[GOMP_DIM_MAX];
6797 unsigned int i;
6798
6799 for (i = 0; i < GOMP_DIM_MAX; ++i)
6800 old_dims[i] = dims[i];
6801
6802 nvptx_goacc_validate_dims_1 (decl, dims, fn_level, used);
6803
6804 gcc_assert (dims[GOMP_DIM_VECTOR] != 0);
6805 if (dims[GOMP_DIM_WORKER] > 0 && dims[GOMP_DIM_VECTOR] > 0)
6806 gcc_assert (dims[GOMP_DIM_WORKER] * dims[GOMP_DIM_VECTOR] <= PTX_CTA_SIZE);
6807
6808 for (i = 0; i < GOMP_DIM_MAX; ++i)
6809 if (old_dims[i] != dims[i])
6810 return true;
6811
6812 return false;
6813 }
6814
6815 /* Return maximum dimension size, or zero for unbounded. */
6816
6817 static int
6818 nvptx_dim_limit (int axis)
6819 {
6820 switch (axis)
6821 {
6822 case GOMP_DIM_VECTOR:
6823 return PTX_MAX_VECTOR_LENGTH;
6824
6825 default:
6826 break;
6827 }
6828 return 0;
6829 }
6830
6831 /* Determine whether fork & joins are needed. */
6832
6833 static bool
6834 nvptx_goacc_fork_join (gcall *call, const int dims[],
6835 bool ARG_UNUSED (is_fork))
6836 {
6837 tree arg = gimple_call_arg (call, 2);
6838 unsigned axis = TREE_INT_CST_LOW (arg);
6839
6840 /* We only care about worker and vector partitioning. */
6841 if (axis < GOMP_DIM_WORKER)
6842 return false;
6843
6844 /* If the size is 1, there's no partitioning. */
6845 if (dims[axis] == 1)
6846 return false;
6847
6848 return true;
6849 }
6850
6851 /* Generate a PTX builtin function call that returns the address in
6852 the worker reduction buffer at OFFSET. TYPE is the type of the
6853 data at that location. */
6854
6855 static tree
6856 nvptx_get_shared_red_addr (tree type, tree offset, bool vector)
6857 {
6858 enum nvptx_builtins addr_dim = NVPTX_BUILTIN_WORKER_ADDR;
6859 if (vector)
6860 addr_dim = NVPTX_BUILTIN_VECTOR_ADDR;
6861 machine_mode mode = TYPE_MODE (type);
6862 tree fndecl = nvptx_builtin_decl (addr_dim, true);
6863 tree size = build_int_cst (unsigned_type_node, GET_MODE_SIZE (mode));
6864 tree align = build_int_cst (unsigned_type_node,
6865 GET_MODE_ALIGNMENT (mode) / BITS_PER_UNIT);
6866 tree call = build_call_expr (fndecl, 3, offset, size, align);
6867
6868 return fold_convert (build_pointer_type (type), call);
6869 }
6870
6871 /* Emit a SHFL.DOWN using index SHFL of VAR into DEST_VAR. This function
6872 will cast the variable if necessary. */
6873
6874 static void
6875 nvptx_generate_vector_shuffle (location_t loc,
6876 tree dest_var, tree var, unsigned shift,
6877 gimple_seq *seq)
6878 {
6879 unsigned fn = NVPTX_BUILTIN_SHUFFLE;
6880 tree_code code = NOP_EXPR;
6881 tree arg_type = unsigned_type_node;
6882 tree var_type = TREE_TYPE (var);
6883 tree dest_type = var_type;
6884
6885 if (TREE_CODE (var_type) == COMPLEX_TYPE)
6886 var_type = TREE_TYPE (var_type);
6887
6888 if (SCALAR_FLOAT_TYPE_P (var_type))
6889 code = VIEW_CONVERT_EXPR;
6890
6891 if (TYPE_SIZE (var_type)
6892 == TYPE_SIZE (long_long_unsigned_type_node))
6893 {
6894 fn = NVPTX_BUILTIN_SHUFFLELL;
6895 arg_type = long_long_unsigned_type_node;
6896 }
6897
6898 tree call = nvptx_builtin_decl (fn, true);
6899 tree bits = build_int_cst (unsigned_type_node, shift);
6900 tree kind = build_int_cst (unsigned_type_node, SHUFFLE_DOWN);
6901 tree expr;
6902
6903 if (var_type != dest_type)
6904 {
6905 /* Do real and imaginary parts separately. */
6906 tree real = fold_build1 (REALPART_EXPR, var_type, var);
6907 real = fold_build1 (code, arg_type, real);
6908 real = build_call_expr_loc (loc, call, 3, real, bits, kind);
6909 real = fold_build1 (code, var_type, real);
6910
6911 tree imag = fold_build1 (IMAGPART_EXPR, var_type, var);
6912 imag = fold_build1 (code, arg_type, imag);
6913 imag = build_call_expr_loc (loc, call, 3, imag, bits, kind);
6914 imag = fold_build1 (code, var_type, imag);
6915
6916 expr = fold_build2 (COMPLEX_EXPR, dest_type, real, imag);
6917 }
6918 else
6919 {
6920 expr = fold_build1 (code, arg_type, var);
6921 expr = build_call_expr_loc (loc, call, 3, expr, bits, kind);
6922 expr = fold_build1 (code, dest_type, expr);
6923 }
6924
6925 gimplify_assign (dest_var, expr, seq);
6926 }
6927
6928 /* Lazily generate the global lock var decl and return its address. */
6929
6930 static tree
6931 nvptx_global_lock_addr ()
6932 {
6933 tree v = global_lock_var;
6934
6935 if (!v)
6936 {
6937 tree name = get_identifier ("__reduction_lock");
6938 tree type = build_qualified_type (unsigned_type_node,
6939 TYPE_QUAL_VOLATILE);
6940 v = build_decl (BUILTINS_LOCATION, VAR_DECL, name, type);
6941 global_lock_var = v;
6942 DECL_ARTIFICIAL (v) = 1;
6943 DECL_EXTERNAL (v) = 1;
6944 TREE_STATIC (v) = 1;
6945 TREE_PUBLIC (v) = 1;
6946 TREE_USED (v) = 1;
6947 mark_addressable (v);
6948 mark_decl_referenced (v);
6949 }
6950
6951 return build_fold_addr_expr (v);
6952 }
6953
6954 /* Insert code to locklessly update *PTR with *PTR OP VAR just before
6955 GSI. We use a lockless scheme for nearly all case, which looks
6956 like:
6957 actual = initval(OP);
6958 do {
6959 guess = actual;
6960 write = guess OP myval;
6961 actual = cmp&swap (ptr, guess, write)
6962 } while (actual bit-different-to guess);
6963 return write;
6964
6965 This relies on a cmp&swap instruction, which is available for 32-
6966 and 64-bit types. Larger types must use a locking scheme. */
6967
6968 static tree
6969 nvptx_lockless_update (location_t loc, gimple_stmt_iterator *gsi,
6970 tree ptr, tree var, tree_code op)
6971 {
6972 unsigned fn = NVPTX_BUILTIN_CMP_SWAP;
6973 tree_code code = NOP_EXPR;
6974 tree arg_type = unsigned_type_node;
6975 tree var_type = TREE_TYPE (var);
6976
6977 if (TREE_CODE (var_type) == COMPLEX_TYPE
6978 || SCALAR_FLOAT_TYPE_P (var_type))
6979 code = VIEW_CONVERT_EXPR;
6980
6981 if (TYPE_SIZE (var_type) == TYPE_SIZE (long_long_unsigned_type_node))
6982 {
6983 arg_type = long_long_unsigned_type_node;
6984 fn = NVPTX_BUILTIN_CMP_SWAPLL;
6985 }
6986
6987 tree swap_fn = nvptx_builtin_decl (fn, true);
6988
6989 gimple_seq init_seq = NULL;
6990 tree init_var = make_ssa_name (arg_type);
6991 tree init_expr = omp_reduction_init_op (loc, op, var_type);
6992 init_expr = fold_build1 (code, arg_type, init_expr);
6993 gimplify_assign (init_var, init_expr, &init_seq);
6994 gimple *init_end = gimple_seq_last (init_seq);
6995
6996 gsi_insert_seq_before (gsi, init_seq, GSI_SAME_STMT);
6997
6998 /* Split the block just after the init stmts. */
6999 basic_block pre_bb = gsi_bb (*gsi);
7000 edge pre_edge = split_block (pre_bb, init_end);
7001 basic_block loop_bb = pre_edge->dest;
7002 pre_bb = pre_edge->src;
7003 /* Reset the iterator. */
7004 *gsi = gsi_for_stmt (gsi_stmt (*gsi));
7005
7006 tree expect_var = make_ssa_name (arg_type);
7007 tree actual_var = make_ssa_name (arg_type);
7008 tree write_var = make_ssa_name (arg_type);
7009
7010 /* Build and insert the reduction calculation. */
7011 gimple_seq red_seq = NULL;
7012 tree write_expr = fold_build1 (code, var_type, expect_var);
7013 write_expr = fold_build2 (op, var_type, write_expr, var);
7014 write_expr = fold_build1 (code, arg_type, write_expr);
7015 gimplify_assign (write_var, write_expr, &red_seq);
7016
7017 gsi_insert_seq_before (gsi, red_seq, GSI_SAME_STMT);
7018
7019 /* Build & insert the cmp&swap sequence. */
7020 gimple_seq latch_seq = NULL;
7021 tree swap_expr = build_call_expr_loc (loc, swap_fn, 3,
7022 ptr, expect_var, write_var);
7023 gimplify_assign (actual_var, swap_expr, &latch_seq);
7024
7025 gcond *cond = gimple_build_cond (EQ_EXPR, actual_var, expect_var,
7026 NULL_TREE, NULL_TREE);
7027 gimple_seq_add_stmt (&latch_seq, cond);
7028
7029 gimple *latch_end = gimple_seq_last (latch_seq);
7030 gsi_insert_seq_before (gsi, latch_seq, GSI_SAME_STMT);
7031
7032 /* Split the block just after the latch stmts. */
7033 edge post_edge = split_block (loop_bb, latch_end);
7034 basic_block post_bb = post_edge->dest;
7035 loop_bb = post_edge->src;
7036 *gsi = gsi_for_stmt (gsi_stmt (*gsi));
7037
7038 post_edge->flags ^= EDGE_TRUE_VALUE | EDGE_FALLTHRU;
7039 post_edge->probability = profile_probability::even ();
7040 edge loop_edge = make_edge (loop_bb, loop_bb, EDGE_FALSE_VALUE);
7041 loop_edge->probability = profile_probability::even ();
7042 set_immediate_dominator (CDI_DOMINATORS, loop_bb, pre_bb);
7043 set_immediate_dominator (CDI_DOMINATORS, post_bb, loop_bb);
7044
7045 gphi *phi = create_phi_node (expect_var, loop_bb);
7046 add_phi_arg (phi, init_var, pre_edge, loc);
7047 add_phi_arg (phi, actual_var, loop_edge, loc);
7048
7049 loop *loop = alloc_loop ();
7050 loop->header = loop_bb;
7051 loop->latch = loop_bb;
7052 add_loop (loop, loop_bb->loop_father);
7053
7054 return fold_build1 (code, var_type, write_var);
7055 }
7056
7057 /* Insert code to lockfully update *PTR with *PTR OP VAR just before
7058 GSI. This is necessary for types larger than 64 bits, where there
7059 is no cmp&swap instruction to implement a lockless scheme. We use
7060 a lock variable in global memory.
7061
7062 while (cmp&swap (&lock_var, 0, 1))
7063 continue;
7064 T accum = *ptr;
7065 accum = accum OP var;
7066 *ptr = accum;
7067 cmp&swap (&lock_var, 1, 0);
7068 return accum;
7069
7070 A lock in global memory is necessary to force execution engine
7071 descheduling and avoid resource starvation that can occur if the
7072 lock is in .shared memory. */
7073
7074 static tree
7075 nvptx_lockfull_update (location_t loc, gimple_stmt_iterator *gsi,
7076 tree ptr, tree var, tree_code op, int level)
7077 {
7078 tree var_type = TREE_TYPE (var);
7079 tree swap_fn = nvptx_builtin_decl (NVPTX_BUILTIN_CMP_SWAP, true);
7080 tree uns_unlocked = build_int_cst (unsigned_type_node, 0);
7081 tree uns_locked = build_int_cst (unsigned_type_node, 1);
7082
7083 /* Split the block just before the gsi. Insert a gimple nop to make
7084 this easier. */
7085 gimple *nop = gimple_build_nop ();
7086 gsi_insert_before (gsi, nop, GSI_SAME_STMT);
7087 basic_block entry_bb = gsi_bb (*gsi);
7088 edge entry_edge = split_block (entry_bb, nop);
7089 basic_block lock_bb = entry_edge->dest;
7090 /* Reset the iterator. */
7091 *gsi = gsi_for_stmt (gsi_stmt (*gsi));
7092
7093 /* Build and insert the locking sequence. */
7094 gimple_seq lock_seq = NULL;
7095 tree lock_var = make_ssa_name (unsigned_type_node);
7096 tree lock_expr = nvptx_global_lock_addr ();
7097 lock_expr = build_call_expr_loc (loc, swap_fn, 3, lock_expr,
7098 uns_unlocked, uns_locked);
7099 gimplify_assign (lock_var, lock_expr, &lock_seq);
7100 gcond *cond = gimple_build_cond (EQ_EXPR, lock_var, uns_unlocked,
7101 NULL_TREE, NULL_TREE);
7102 gimple_seq_add_stmt (&lock_seq, cond);
7103 gimple *lock_end = gimple_seq_last (lock_seq);
7104 gsi_insert_seq_before (gsi, lock_seq, GSI_SAME_STMT);
7105
7106 /* Split the block just after the lock sequence. */
7107 edge locked_edge = split_block (lock_bb, lock_end);
7108 basic_block update_bb = locked_edge->dest;
7109 lock_bb = locked_edge->src;
7110 *gsi = gsi_for_stmt (gsi_stmt (*gsi));
7111
7112 /* Create the lock loop ... */
7113 locked_edge->flags ^= EDGE_TRUE_VALUE | EDGE_FALLTHRU;
7114 locked_edge->probability = profile_probability::even ();
7115 edge loop_edge = make_edge (lock_bb, lock_bb, EDGE_FALSE_VALUE);
7116 loop_edge->probability = profile_probability::even ();
7117 set_immediate_dominator (CDI_DOMINATORS, lock_bb, entry_bb);
7118 set_immediate_dominator (CDI_DOMINATORS, update_bb, lock_bb);
7119
7120 /* ... and the loop structure. */
7121 loop *lock_loop = alloc_loop ();
7122 lock_loop->header = lock_bb;
7123 lock_loop->latch = lock_bb;
7124 lock_loop->nb_iterations_estimate = 1;
7125 lock_loop->any_estimate = true;
7126 add_loop (lock_loop, entry_bb->loop_father);
7127
7128 /* Build the pre-barrier. */
7129 gimple_seq red_seq = NULL;
7130 enum nvptx_builtins barrier_builtin
7131 = (level == GOMP_DIM_GANG
7132 ? NVPTX_BUILTIN_MEMBAR_GL
7133 : NVPTX_BUILTIN_MEMBAR_CTA);
7134 tree barrier_fn = nvptx_builtin_decl (barrier_builtin, true);
7135 tree barrier_expr = build_call_expr_loc (loc, barrier_fn, 0);
7136 gimplify_stmt (&barrier_expr, &red_seq);
7137
7138 /* Build the reduction calculation. */
7139 tree acc_in = make_ssa_name (var_type);
7140 tree ref_in = build_simple_mem_ref (ptr);
7141 TREE_THIS_VOLATILE (ref_in) = 1;
7142 gimplify_assign (acc_in, ref_in, &red_seq);
7143
7144 tree acc_out = make_ssa_name (var_type);
7145 tree update_expr = fold_build2 (op, var_type, ref_in, var);
7146 gimplify_assign (acc_out, update_expr, &red_seq);
7147
7148 tree ref_out = build_simple_mem_ref (ptr);
7149 TREE_THIS_VOLATILE (ref_out) = 1;
7150 gimplify_assign (ref_out, acc_out, &red_seq);
7151
7152 /* Build the post-barrier. */
7153 barrier_expr = build_call_expr_loc (loc, barrier_fn, 0);
7154 gimplify_stmt (&barrier_expr, &red_seq);
7155
7156 /* Insert the reduction calculation. */
7157 gsi_insert_seq_before (gsi, red_seq, GSI_SAME_STMT);
7158
7159 /* Build & insert the unlock sequence. */
7160 gimple_seq unlock_seq = NULL;
7161 tree unlock_expr = nvptx_global_lock_addr ();
7162 unlock_expr = build_call_expr_loc (loc, swap_fn, 3, unlock_expr,
7163 uns_locked, uns_unlocked);
7164 gimplify_and_add (unlock_expr, &unlock_seq);
7165 gsi_insert_seq_before (gsi, unlock_seq, GSI_SAME_STMT);
7166
7167 return acc_out;
7168 }
7169
7170 /* Emit a sequence to update a reduction accumlator at *PTR with the
7171 value held in VAR using operator OP. Return the updated value.
7172
7173 TODO: optimize for atomic ops and indepedent complex ops. */
7174
7175 static tree
7176 nvptx_reduction_update (location_t loc, gimple_stmt_iterator *gsi,
7177 tree ptr, tree var, tree_code op, int level)
7178 {
7179 tree type = TREE_TYPE (var);
7180 tree size = TYPE_SIZE (type);
7181
7182 if (size == TYPE_SIZE (unsigned_type_node)
7183 || size == TYPE_SIZE (long_long_unsigned_type_node))
7184 return nvptx_lockless_update (loc, gsi, ptr, var, op);
7185 else
7186 return nvptx_lockfull_update (loc, gsi, ptr, var, op, level);
7187 }
7188
7189 /* NVPTX implementation of GOACC_REDUCTION_SETUP. */
7190
7191 static void
7192 nvptx_goacc_reduction_setup (gcall *call, offload_attrs *oa)
7193 {
7194 gimple_stmt_iterator gsi = gsi_for_stmt (call);
7195 tree lhs = gimple_call_lhs (call);
7196 tree var = gimple_call_arg (call, 2);
7197 int level = TREE_INT_CST_LOW (gimple_call_arg (call, 3));
7198 gimple_seq seq = NULL;
7199
7200 push_gimplify_context (true);
7201
7202 if (level != GOMP_DIM_GANG)
7203 {
7204 /* Copy the receiver object. */
7205 tree ref_to_res = gimple_call_arg (call, 1);
7206
7207 if (!integer_zerop (ref_to_res))
7208 var = build_simple_mem_ref (ref_to_res);
7209 }
7210
7211 if (level == GOMP_DIM_WORKER
7212 || (level == GOMP_DIM_VECTOR && oa->vector_length > PTX_WARP_SIZE))
7213 {
7214 /* Store incoming value to worker reduction buffer. */
7215 tree offset = gimple_call_arg (call, 5);
7216 tree call = nvptx_get_shared_red_addr (TREE_TYPE (var), offset,
7217 level == GOMP_DIM_VECTOR);
7218 tree ptr = make_ssa_name (TREE_TYPE (call));
7219
7220 gimplify_assign (ptr, call, &seq);
7221 tree ref = build_simple_mem_ref (ptr);
7222 TREE_THIS_VOLATILE (ref) = 1;
7223 gimplify_assign (ref, var, &seq);
7224 }
7225
7226 if (lhs)
7227 gimplify_assign (lhs, var, &seq);
7228
7229 pop_gimplify_context (NULL);
7230 gsi_replace_with_seq (&gsi, seq, true);
7231 }
7232
7233 /* NVPTX implementation of GOACC_REDUCTION_INIT. */
7234
7235 static void
7236 nvptx_goacc_reduction_init (gcall *call, offload_attrs *oa)
7237 {
7238 gimple_stmt_iterator gsi = gsi_for_stmt (call);
7239 tree lhs = gimple_call_lhs (call);
7240 tree var = gimple_call_arg (call, 2);
7241 int level = TREE_INT_CST_LOW (gimple_call_arg (call, 3));
7242 enum tree_code rcode
7243 = (enum tree_code)TREE_INT_CST_LOW (gimple_call_arg (call, 4));
7244 tree init = omp_reduction_init_op (gimple_location (call), rcode,
7245 TREE_TYPE (var));
7246 gimple_seq seq = NULL;
7247
7248 push_gimplify_context (true);
7249
7250 if (level == GOMP_DIM_VECTOR && oa->vector_length == PTX_WARP_SIZE)
7251 {
7252 /* Initialize vector-non-zeroes to INIT_VAL (OP). */
7253 tree tid = make_ssa_name (integer_type_node);
7254 tree dim_vector = gimple_call_arg (call, 3);
7255 gimple *tid_call = gimple_build_call_internal (IFN_GOACC_DIM_POS, 1,
7256 dim_vector);
7257 gimple *cond_stmt = gimple_build_cond (NE_EXPR, tid, integer_zero_node,
7258 NULL_TREE, NULL_TREE);
7259
7260 gimple_call_set_lhs (tid_call, tid);
7261 gimple_seq_add_stmt (&seq, tid_call);
7262 gimple_seq_add_stmt (&seq, cond_stmt);
7263
7264 /* Split the block just after the call. */
7265 edge init_edge = split_block (gsi_bb (gsi), call);
7266 basic_block init_bb = init_edge->dest;
7267 basic_block call_bb = init_edge->src;
7268
7269 /* Fixup flags from call_bb to init_bb. */
7270 init_edge->flags ^= EDGE_FALLTHRU | EDGE_TRUE_VALUE;
7271 init_edge->probability = profile_probability::even ();
7272
7273 /* Set the initialization stmts. */
7274 gimple_seq init_seq = NULL;
7275 tree init_var = make_ssa_name (TREE_TYPE (var));
7276 gimplify_assign (init_var, init, &init_seq);
7277 gsi = gsi_start_bb (init_bb);
7278 gsi_insert_seq_before (&gsi, init_seq, GSI_SAME_STMT);
7279
7280 /* Split block just after the init stmt. */
7281 gsi_prev (&gsi);
7282 edge inited_edge = split_block (gsi_bb (gsi), gsi_stmt (gsi));
7283 basic_block dst_bb = inited_edge->dest;
7284
7285 /* Create false edge from call_bb to dst_bb. */
7286 edge nop_edge = make_edge (call_bb, dst_bb, EDGE_FALSE_VALUE);
7287 nop_edge->probability = profile_probability::even ();
7288
7289 /* Create phi node in dst block. */
7290 gphi *phi = create_phi_node (lhs, dst_bb);
7291 add_phi_arg (phi, init_var, inited_edge, gimple_location (call));
7292 add_phi_arg (phi, var, nop_edge, gimple_location (call));
7293
7294 /* Reset dominator of dst bb. */
7295 set_immediate_dominator (CDI_DOMINATORS, dst_bb, call_bb);
7296
7297 /* Reset the gsi. */
7298 gsi = gsi_for_stmt (call);
7299 }
7300 else
7301 {
7302 if (level == GOMP_DIM_GANG)
7303 {
7304 /* If there's no receiver object, propagate the incoming VAR. */
7305 tree ref_to_res = gimple_call_arg (call, 1);
7306 if (integer_zerop (ref_to_res))
7307 init = var;
7308 }
7309
7310 if (lhs != NULL_TREE)
7311 gimplify_assign (lhs, init, &seq);
7312 }
7313
7314 pop_gimplify_context (NULL);
7315 gsi_replace_with_seq (&gsi, seq, true);
7316 }
7317
7318 /* NVPTX implementation of GOACC_REDUCTION_FINI. */
7319
7320 static void
7321 nvptx_goacc_reduction_fini (gcall *call, offload_attrs *oa)
7322 {
7323 gimple_stmt_iterator gsi = gsi_for_stmt (call);
7324 tree lhs = gimple_call_lhs (call);
7325 tree ref_to_res = gimple_call_arg (call, 1);
7326 tree var = gimple_call_arg (call, 2);
7327 int level = TREE_INT_CST_LOW (gimple_call_arg (call, 3));
7328 enum tree_code op
7329 = (enum tree_code)TREE_INT_CST_LOW (gimple_call_arg (call, 4));
7330 gimple_seq seq = NULL;
7331 tree r = NULL_TREE;
7332
7333 push_gimplify_context (true);
7334
7335 if (level == GOMP_DIM_VECTOR && oa->vector_length == PTX_WARP_SIZE)
7336 {
7337 /* Emit binary shuffle tree. TODO. Emit this as an actual loop,
7338 but that requires a method of emitting a unified jump at the
7339 gimple level. */
7340 for (int shfl = PTX_WARP_SIZE / 2; shfl > 0; shfl = shfl >> 1)
7341 {
7342 tree other_var = make_ssa_name (TREE_TYPE (var));
7343 nvptx_generate_vector_shuffle (gimple_location (call),
7344 other_var, var, shfl, &seq);
7345
7346 r = make_ssa_name (TREE_TYPE (var));
7347 gimplify_assign (r, fold_build2 (op, TREE_TYPE (var),
7348 var, other_var), &seq);
7349 var = r;
7350 }
7351 }
7352 else
7353 {
7354 tree accum = NULL_TREE;
7355
7356 if (level == GOMP_DIM_WORKER || level == GOMP_DIM_VECTOR)
7357 {
7358 /* Get reduction buffer address. */
7359 tree offset = gimple_call_arg (call, 5);
7360 tree call = nvptx_get_shared_red_addr (TREE_TYPE (var), offset,
7361 level == GOMP_DIM_VECTOR);
7362 tree ptr = make_ssa_name (TREE_TYPE (call));
7363
7364 gimplify_assign (ptr, call, &seq);
7365 accum = ptr;
7366 }
7367 else if (integer_zerop (ref_to_res))
7368 r = var;
7369 else
7370 accum = ref_to_res;
7371
7372 if (accum)
7373 {
7374 /* UPDATE the accumulator. */
7375 gsi_insert_seq_before (&gsi, seq, GSI_SAME_STMT);
7376 seq = NULL;
7377 r = nvptx_reduction_update (gimple_location (call), &gsi,
7378 accum, var, op, level);
7379 }
7380 }
7381
7382 if (lhs)
7383 gimplify_assign (lhs, r, &seq);
7384 pop_gimplify_context (NULL);
7385
7386 gsi_replace_with_seq (&gsi, seq, true);
7387 }
7388
7389 /* NVPTX implementation of GOACC_REDUCTION_TEARDOWN. */
7390
7391 static void
7392 nvptx_goacc_reduction_teardown (gcall *call, offload_attrs *oa)
7393 {
7394 gimple_stmt_iterator gsi = gsi_for_stmt (call);
7395 tree lhs = gimple_call_lhs (call);
7396 tree var = gimple_call_arg (call, 2);
7397 int level = TREE_INT_CST_LOW (gimple_call_arg (call, 3));
7398 gimple_seq seq = NULL;
7399
7400 push_gimplify_context (true);
7401 if (level == GOMP_DIM_WORKER
7402 || (level == GOMP_DIM_VECTOR && oa->vector_length > PTX_WARP_SIZE))
7403 {
7404 /* Read the worker reduction buffer. */
7405 tree offset = gimple_call_arg (call, 5);
7406 tree call = nvptx_get_shared_red_addr (TREE_TYPE (var), offset,
7407 level == GOMP_DIM_VECTOR);
7408 tree ptr = make_ssa_name (TREE_TYPE (call));
7409
7410 gimplify_assign (ptr, call, &seq);
7411 var = build_simple_mem_ref (ptr);
7412 TREE_THIS_VOLATILE (var) = 1;
7413 }
7414
7415 if (level != GOMP_DIM_GANG)
7416 {
7417 /* Write to the receiver object. */
7418 tree ref_to_res = gimple_call_arg (call, 1);
7419
7420 if (!integer_zerop (ref_to_res))
7421 gimplify_assign (build_simple_mem_ref (ref_to_res), var, &seq);
7422 }
7423
7424 if (lhs)
7425 gimplify_assign (lhs, var, &seq);
7426
7427 pop_gimplify_context (NULL);
7428
7429 gsi_replace_with_seq (&gsi, seq, true);
7430 }
7431
7432 /* NVPTX reduction expander. */
7433
7434 static void
7435 nvptx_goacc_reduction (gcall *call)
7436 {
7437 unsigned code = (unsigned)TREE_INT_CST_LOW (gimple_call_arg (call, 0));
7438 offload_attrs oa;
7439
7440 populate_offload_attrs (&oa);
7441
7442 switch (code)
7443 {
7444 case IFN_GOACC_REDUCTION_SETUP:
7445 nvptx_goacc_reduction_setup (call, &oa);
7446 break;
7447
7448 case IFN_GOACC_REDUCTION_INIT:
7449 nvptx_goacc_reduction_init (call, &oa);
7450 break;
7451
7452 case IFN_GOACC_REDUCTION_FINI:
7453 nvptx_goacc_reduction_fini (call, &oa);
7454 break;
7455
7456 case IFN_GOACC_REDUCTION_TEARDOWN:
7457 nvptx_goacc_reduction_teardown (call, &oa);
7458 break;
7459
7460 default:
7461 gcc_unreachable ();
7462 }
7463 }
7464
7465 static bool
7466 nvptx_cannot_force_const_mem (machine_mode mode ATTRIBUTE_UNUSED,
7467 rtx x ATTRIBUTE_UNUSED)
7468 {
7469 return true;
7470 }
7471
7472 static bool
7473 nvptx_scalar_mode_supported_p (scalar_mode mode)
7474 {
7475 if (nvptx_experimental && mode == HFmode && TARGET_SM53)
7476 return true;
7477
7478 return default_scalar_mode_supported_p (mode);
7479 }
7480
7481 static bool
7482 nvptx_libgcc_floating_mode_supported_p (scalar_float_mode mode)
7483 {
7484 if (nvptx_experimental && mode == HFmode && TARGET_SM53)
7485 return true;
7486
7487 return default_libgcc_floating_mode_supported_p (mode);
7488 }
7489
7490 static bool
7491 nvptx_vector_mode_supported (machine_mode mode)
7492 {
7493 return (mode == V2SImode
7494 || mode == V2DImode);
7495 }
7496
7497 /* Return the preferred mode for vectorizing scalar MODE. */
7498
7499 static machine_mode
7500 nvptx_preferred_simd_mode (scalar_mode mode)
7501 {
7502 switch (mode)
7503 {
7504 case E_DImode:
7505 return V2DImode;
7506 case E_SImode:
7507 return V2SImode;
7508
7509 default:
7510 return default_preferred_simd_mode (mode);
7511 }
7512 }
7513
7514 unsigned int
7515 nvptx_data_alignment (const_tree type, unsigned int basic_align)
7516 {
7517 if (TREE_CODE (type) == INTEGER_TYPE)
7518 {
7519 unsigned HOST_WIDE_INT size = tree_to_uhwi (TYPE_SIZE_UNIT (type));
7520 if (size == GET_MODE_SIZE (TImode))
7521 return GET_MODE_BITSIZE (maybe_split_mode (TImode));
7522 }
7523
7524 return basic_align;
7525 }
7526
7527 /* Implement TARGET_MODES_TIEABLE_P. */
7528
7529 static bool
7530 nvptx_modes_tieable_p (machine_mode, machine_mode)
7531 {
7532 return false;
7533 }
7534
7535 /* Implement TARGET_HARD_REGNO_NREGS. */
7536
7537 static unsigned int
7538 nvptx_hard_regno_nregs (unsigned int, machine_mode)
7539 {
7540 return 1;
7541 }
7542
7543 /* Implement TARGET_CAN_CHANGE_MODE_CLASS. */
7544
7545 static bool
7546 nvptx_can_change_mode_class (machine_mode, machine_mode, reg_class_t)
7547 {
7548 return false;
7549 }
7550
7551 /* Implement TARGET_TRULY_NOOP_TRUNCATION. */
7552
7553 static bool
7554 nvptx_truly_noop_truncation (poly_uint64, poly_uint64)
7555 {
7556 return false;
7557 }
7558
7559 /* Implement TARGET_GOACC_ADJUST_PRIVATE_DECL. */
7560
7561 static tree
7562 nvptx_goacc_adjust_private_decl (location_t loc, tree decl, int level)
7563 {
7564 gcc_checking_assert (!lookup_attribute ("oacc gang-private",
7565 DECL_ATTRIBUTES (decl)));
7566
7567 /* Set "oacc gang-private" attribute for gang-private variable
7568 declarations. */
7569 if (level == GOMP_DIM_GANG)
7570 {
7571 tree id = get_identifier ("oacc gang-private");
7572 /* For later diagnostic purposes, pass LOC as VALUE (wrapped as a
7573 TREE). */
7574 tree loc_tree = build_empty_stmt (loc);
7575 DECL_ATTRIBUTES (decl)
7576 = tree_cons (id, loc_tree, DECL_ATTRIBUTES (decl));
7577 }
7578
7579 return decl;
7580 }
7581
7582 /* Implement TARGET_GOACC_EXPAND_VAR_DECL. */
7583
7584 static rtx
7585 nvptx_goacc_expand_var_decl (tree var)
7586 {
7587 /* Place "oacc gang-private" variables in shared memory. */
7588 if (tree attr = lookup_attribute ("oacc gang-private",
7589 DECL_ATTRIBUTES (var)))
7590 {
7591 gcc_checking_assert (VAR_P (var));
7592
7593 unsigned int offset, *poffset;
7594 poffset = gang_private_shared_hmap.get (var);
7595 if (poffset)
7596 offset = *poffset;
7597 else
7598 {
7599 unsigned HOST_WIDE_INT align = DECL_ALIGN (var);
7600 gang_private_shared_size
7601 = (gang_private_shared_size + align - 1) & ~(align - 1);
7602 if (gang_private_shared_align < align)
7603 gang_private_shared_align = align;
7604
7605 offset = gang_private_shared_size;
7606 bool existed = gang_private_shared_hmap.put (var, offset);
7607 gcc_checking_assert (!existed);
7608 gang_private_shared_size += tree_to_uhwi (DECL_SIZE_UNIT (var));
7609
7610 location_t loc = EXPR_LOCATION (TREE_VALUE (attr));
7611 #if 0 /* For some reason, this doesn't work. */
7612 if (dump_enabled_p ())
7613 {
7614 dump_flags_t l_dump_flags
7615 = get_openacc_privatization_dump_flags ();
7616
7617 const dump_user_location_t d_u_loc
7618 = dump_user_location_t::from_location_t (loc);
7619 /* PR100695 "Format decoder, quoting in 'dump_printf' etc." */
7620 #if __GNUC__ >= 10
7621 # pragma GCC diagnostic push
7622 # pragma GCC diagnostic ignored "-Wformat"
7623 #endif
7624 dump_printf_loc (l_dump_flags, d_u_loc,
7625 "variable %<%T%> adjusted for OpenACC"
7626 " privatization level: %qs\n",
7627 var, "gang");
7628 #if __GNUC__ >= 10
7629 # pragma GCC diagnostic pop
7630 #endif
7631 }
7632 #else /* ..., thus emulate that, good enough for testsuite usage. */
7633 if (param_openacc_privatization != OPENACC_PRIVATIZATION_QUIET)
7634 inform (loc,
7635 "variable %qD adjusted for OpenACC privatization level:"
7636 " %qs",
7637 var, "gang");
7638 if (dump_file && (dump_flags & TDF_DETAILS))
7639 {
7640 /* 'dumpfile.cc:dump_loc' */
7641 fprintf (dump_file, "%s:%d:%d: ", LOCATION_FILE (loc),
7642 LOCATION_LINE (loc), LOCATION_COLUMN (loc));
7643 fprintf (dump_file, "%s: ", "note");
7644
7645 fprintf (dump_file,
7646 "variable '");
7647 print_generic_expr (dump_file, var, TDF_SLIM);
7648 fprintf (dump_file,
7649 "' adjusted for OpenACC privatization level: '%s'\n",
7650 "gang");
7651 }
7652 #endif
7653 }
7654 rtx addr = plus_constant (Pmode, gang_private_shared_sym, offset);
7655 return gen_rtx_MEM (TYPE_MODE (TREE_TYPE (var)), addr);
7656 }
7657
7658 return NULL_RTX;
7659 }
7660
7661 static GTY(()) tree nvptx_previous_fndecl;
7662
7663 static void
7664 nvptx_set_current_function (tree fndecl)
7665 {
7666 if (!fndecl || fndecl == nvptx_previous_fndecl)
7667 return;
7668
7669 gang_private_shared_hmap.empty ();
7670 nvptx_previous_fndecl = fndecl;
7671 vector_red_partition = 0;
7672 oacc_bcast_partition = 0;
7673 }
7674
7675 /* Implement TARGET_LIBC_HAS_FUNCTION. */
7676
7677 bool
7678 nvptx_libc_has_function (enum function_class fn_class, tree type)
7679 {
7680 if (fn_class == function_sincos)
7681 {
7682 if (type != NULL_TREE)
7683 /* Currently, newlib does not support sincosl. */
7684 return type == float_type_node || type == double_type_node;
7685 else
7686 return true;
7687 }
7688
7689 return default_libc_has_function (fn_class, type);
7690 }
7691
7692 bool
7693 nvptx_mem_local_p (rtx mem)
7694 {
7695 gcc_assert (GET_CODE (mem) == MEM);
7696
7697 struct address_info info;
7698 decompose_mem_address (&info, mem);
7699
7700 if (info.base != NULL && REG_P (*info.base)
7701 && REGNO_PTR_FRAME_P (REGNO (*info.base)))
7702 {
7703 if (TARGET_SOFT_STACK)
7704 {
7705 /* Frame-related doesn't mean local. */
7706 }
7707 else
7708 return true;
7709 }
7710
7711 return false;
7712 }
7713
7714 /* Define locally, for use in NVPTX_ASM_OUTPUT_DEF. */
7715 #define SET_ASM_OP ".alias "
7716
7717 /* Define locally, for use in nvptx_asm_output_def_from_decls. Add NVPTX_
7718 prefix to avoid clash with ASM_OUTPUT_DEF from nvptx.h.
7719 Copy of ASM_OUTPUT_DEF from defaults.h, with added terminating
7720 semicolon. */
7721 #define NVPTX_ASM_OUTPUT_DEF(FILE,LABEL1,LABEL2) \
7722 do \
7723 { \
7724 fprintf ((FILE), "%s", SET_ASM_OP); \
7725 assemble_name (FILE, LABEL1); \
7726 fprintf (FILE, ","); \
7727 assemble_name (FILE, LABEL2); \
7728 fprintf (FILE, ";\n"); \
7729 } \
7730 while (0)
7731
7732 void
7733 nvptx_asm_output_def_from_decls (FILE *stream, tree name,
7734 tree value ATTRIBUTE_UNUSED)
7735 {
7736 if (nvptx_alias == 0 || !TARGET_PTX_6_3)
7737 {
7738 /* Symbol aliases are not supported here. */
7739
7740 #ifdef ACCEL_COMPILER
7741 if (DECL_CXX_CONSTRUCTOR_P (name)
7742 || DECL_CXX_DESTRUCTOR_P (name))
7743 {
7744 /* ..., but symbol aliases are supported and used in the host system,
7745 via 'gcc/cp/optimize.cc:can_alias_cdtor'. */
7746
7747 gcc_assert (!lookup_attribute ("weak", DECL_ATTRIBUTES (name)));
7748 gcc_assert (TREE_CODE (name) == FUNCTION_DECL);
7749
7750 /* In this specific case, use PTX '.alias', if available, even for
7751 (default) '-mno-alias'. */
7752 if (TARGET_PTX_6_3)
7753 {
7754 DECL_ATTRIBUTES (name)
7755 = tree_cons (get_identifier ("symbol alias handled"),
7756 NULL_TREE, DECL_ATTRIBUTES (name));
7757 goto emit_ptx_alias;
7758 }
7759 }
7760 #endif
7761
7762 /* Copied from assemble_alias. */
7763 error_at (DECL_SOURCE_LOCATION (name),
7764 "alias definitions not supported in this configuration");
7765 TREE_ASM_WRITTEN (name) = 1;
7766 return;
7767 }
7768
7769 if (lookup_attribute ("weak", DECL_ATTRIBUTES (name)))
7770 {
7771 /* Prevent execution FAILs for gcc.dg/globalalias.c and
7772 gcc.dg/pr77587.c. */
7773 error_at (DECL_SOURCE_LOCATION (name),
7774 "weak alias definitions not supported in this configuration");
7775 TREE_ASM_WRITTEN (name) = 1;
7776 return;
7777 }
7778
7779 /* Ptx also doesn't support value having weak linkage, but we can't detect
7780 that here, so we'll end up with:
7781 "error: Function test with .weak scope cannot be aliased".
7782 See gcc.dg/localalias.c. */
7783
7784 if (TREE_CODE (name) != FUNCTION_DECL)
7785 {
7786 error_at (DECL_SOURCE_LOCATION (name),
7787 "non-function alias definitions not supported"
7788 " in this configuration");
7789 TREE_ASM_WRITTEN (name) = 1;
7790 return;
7791 }
7792
7793 #ifdef ACCEL_COMPILER
7794 emit_ptx_alias:
7795 #endif
7796
7797 cgraph_node *cnode = cgraph_node::get (name);
7798 #ifdef ACCEL_COMPILER
7799 /* For nvptx offloading, make sure to emit C++ constructor, destructor aliases [PR97106]
7800
7801 For some reason (yet to be analyzed), they're not 'cnode->referred_to_p ()'.
7802 (..., or that's not the right approach at all;
7803 <https://inbox.sourceware.org/[email protected]>
7804 "Re: [committed][nvptx] Use .alias directive for mptx >= 6.3"). */
7805 if (DECL_CXX_CONSTRUCTOR_P (name)
7806 || DECL_CXX_DESTRUCTOR_P (name))
7807 ;
7808 else
7809 #endif
7810 if (!cnode->referred_to_p ())
7811 /* Prevent "Internal error: reference to deleted section". */
7812 return;
7813
7814 std::stringstream s;
7815 write_fn_proto (s, false, get_fnname_from_decl (name), name);
7816 fputs (s.str ().c_str (), stream);
7817
7818 tree id = DECL_ASSEMBLER_NAME (name);
7819
7820 /* Walk alias chain to get reference callgraph node.
7821 The rationale of using ultimate_alias_target here is that
7822 PTX's .alias directive only supports 1-level aliasing where
7823 aliasee is function defined in same module.
7824
7825 So for the following case:
7826 int foo() { return 42; }
7827 int bar () __attribute__((alias ("foo")));
7828 int baz () __attribute__((alias ("bar")));
7829
7830 should resolve baz to foo:
7831 .visible .func (.param.u32 %value_out) baz;
7832 .alias baz,foo; */
7833 symtab_node *alias_target_node = cnode->ultimate_alias_target ();
7834 tree alias_target_id = DECL_ASSEMBLER_NAME (alias_target_node->decl);
7835 std::stringstream s_def;
7836 write_fn_marker (s_def, true, TREE_PUBLIC (name), IDENTIFIER_POINTER (id));
7837 fputs (s_def.str ().c_str (), stream);
7838 NVPTX_ASM_OUTPUT_DEF (stream, IDENTIFIER_POINTER (id),
7839 IDENTIFIER_POINTER (alias_target_id));
7840 }
7841
7842 #undef NVPTX_ASM_OUTPUT_DEF
7843 #undef SET_ASM_OP
7844
7845 #undef TARGET_OPTION_OVERRIDE
7846 #define TARGET_OPTION_OVERRIDE nvptx_option_override
7847
7848 #undef TARGET_ATTRIBUTE_TABLE
7849 #define TARGET_ATTRIBUTE_TABLE nvptx_attribute_table
7850
7851 #undef TARGET_LEGITIMATE_ADDRESS_P
7852 #define TARGET_LEGITIMATE_ADDRESS_P nvptx_legitimate_address_p
7853
7854 #undef TARGET_PROMOTE_FUNCTION_MODE
7855 #define TARGET_PROMOTE_FUNCTION_MODE nvptx_promote_function_mode
7856
7857 #undef TARGET_FUNCTION_ARG
7858 #define TARGET_FUNCTION_ARG nvptx_function_arg
7859 #undef TARGET_FUNCTION_INCOMING_ARG
7860 #define TARGET_FUNCTION_INCOMING_ARG nvptx_function_incoming_arg
7861 #undef TARGET_FUNCTION_ARG_ADVANCE
7862 #define TARGET_FUNCTION_ARG_ADVANCE nvptx_function_arg_advance
7863 #undef TARGET_FUNCTION_ARG_BOUNDARY
7864 #define TARGET_FUNCTION_ARG_BOUNDARY nvptx_function_arg_boundary
7865 #undef TARGET_PASS_BY_REFERENCE
7866 #define TARGET_PASS_BY_REFERENCE nvptx_pass_by_reference
7867 #undef TARGET_FUNCTION_VALUE_REGNO_P
7868 #define TARGET_FUNCTION_VALUE_REGNO_P nvptx_function_value_regno_p
7869 #undef TARGET_FUNCTION_VALUE
7870 #define TARGET_FUNCTION_VALUE nvptx_function_value
7871 #undef TARGET_LIBCALL_VALUE
7872 #define TARGET_LIBCALL_VALUE nvptx_libcall_value
7873 #undef TARGET_FUNCTION_OK_FOR_SIBCALL
7874 #define TARGET_FUNCTION_OK_FOR_SIBCALL nvptx_function_ok_for_sibcall
7875 #undef TARGET_GET_DRAP_RTX
7876 #define TARGET_GET_DRAP_RTX nvptx_get_drap_rtx
7877 #undef TARGET_SPLIT_COMPLEX_ARG
7878 #define TARGET_SPLIT_COMPLEX_ARG hook_bool_const_tree_true
7879 #undef TARGET_RETURN_IN_MEMORY
7880 #define TARGET_RETURN_IN_MEMORY nvptx_return_in_memory
7881 #undef TARGET_OMIT_STRUCT_RETURN_REG
7882 #define TARGET_OMIT_STRUCT_RETURN_REG true
7883 #undef TARGET_STRICT_ARGUMENT_NAMING
7884 #define TARGET_STRICT_ARGUMENT_NAMING nvptx_strict_argument_naming
7885 #undef TARGET_CALL_ARGS
7886 #define TARGET_CALL_ARGS nvptx_call_args
7887 #undef TARGET_END_CALL_ARGS
7888 #define TARGET_END_CALL_ARGS nvptx_end_call_args
7889
7890 #undef TARGET_ASM_INIT_SECTIONS
7891 #define TARGET_ASM_INIT_SECTIONS nvptx_asm_init_sections
7892 #undef TARGET_ASM_FILE_START
7893 #define TARGET_ASM_FILE_START nvptx_file_start
7894 #undef TARGET_ASM_FILE_END
7895 #define TARGET_ASM_FILE_END nvptx_file_end
7896 #undef TARGET_ASM_GLOBALIZE_LABEL
7897 #define TARGET_ASM_GLOBALIZE_LABEL nvptx_globalize_label
7898 #undef TARGET_ASM_ASSEMBLE_UNDEFINED_DECL
7899 #define TARGET_ASM_ASSEMBLE_UNDEFINED_DECL nvptx_assemble_undefined_decl
7900 #undef TARGET_PRINT_OPERAND
7901 #define TARGET_PRINT_OPERAND nvptx_print_operand
7902 #undef TARGET_PRINT_OPERAND_ADDRESS
7903 #define TARGET_PRINT_OPERAND_ADDRESS nvptx_print_operand_address
7904 #undef TARGET_PRINT_OPERAND_PUNCT_VALID_P
7905 #define TARGET_PRINT_OPERAND_PUNCT_VALID_P nvptx_print_operand_punct_valid_p
7906 #undef TARGET_ASM_INTEGER
7907 #define TARGET_ASM_INTEGER nvptx_assemble_integer
7908 #undef TARGET_ASM_DECL_END
7909 #define TARGET_ASM_DECL_END nvptx_assemble_decl_end
7910 #undef TARGET_ASM_DECLARE_CONSTANT_NAME
7911 #define TARGET_ASM_DECLARE_CONSTANT_NAME nvptx_asm_declare_constant_name
7912 #undef TARGET_USE_BLOCKS_FOR_CONSTANT_P
7913 #define TARGET_USE_BLOCKS_FOR_CONSTANT_P hook_bool_mode_const_rtx_true
7914
7915 #undef TARGET_MACHINE_DEPENDENT_REORG
7916 #define TARGET_MACHINE_DEPENDENT_REORG nvptx_reorg
7917 #undef TARGET_NO_REGISTER_ALLOCATION
7918 #define TARGET_NO_REGISTER_ALLOCATION true
7919
7920 #undef TARGET_ENCODE_SECTION_INFO
7921 #define TARGET_ENCODE_SECTION_INFO nvptx_encode_section_info
7922 #undef TARGET_RECORD_OFFLOAD_SYMBOL
7923 #define TARGET_RECORD_OFFLOAD_SYMBOL nvptx_record_offload_symbol
7924
7925 #undef TARGET_VECTOR_ALIGNMENT
7926 #define TARGET_VECTOR_ALIGNMENT nvptx_vector_alignment
7927
7928 #undef TARGET_CANNOT_COPY_INSN_P
7929 #define TARGET_CANNOT_COPY_INSN_P nvptx_cannot_copy_insn_p
7930
7931 #undef TARGET_USE_ANCHORS_FOR_SYMBOL_P
7932 #define TARGET_USE_ANCHORS_FOR_SYMBOL_P nvptx_use_anchors_for_symbol_p
7933
7934 #undef TARGET_INIT_BUILTINS
7935 #define TARGET_INIT_BUILTINS nvptx_init_builtins
7936 #undef TARGET_EXPAND_BUILTIN
7937 #define TARGET_EXPAND_BUILTIN nvptx_expand_builtin
7938 #undef TARGET_BUILTIN_DECL
7939 #define TARGET_BUILTIN_DECL nvptx_builtin_decl
7940
7941 #undef TARGET_SIMT_VF
7942 #define TARGET_SIMT_VF nvptx_simt_vf
7943
7944 #undef TARGET_OMP_DEVICE_KIND_ARCH_ISA
7945 #define TARGET_OMP_DEVICE_KIND_ARCH_ISA nvptx_omp_device_kind_arch_isa
7946
7947 #undef TARGET_GOACC_VALIDATE_DIMS
7948 #define TARGET_GOACC_VALIDATE_DIMS nvptx_goacc_validate_dims
7949
7950 #undef TARGET_GOACC_DIM_LIMIT
7951 #define TARGET_GOACC_DIM_LIMIT nvptx_dim_limit
7952
7953 #undef TARGET_GOACC_FORK_JOIN
7954 #define TARGET_GOACC_FORK_JOIN nvptx_goacc_fork_join
7955
7956 #undef TARGET_GOACC_REDUCTION
7957 #define TARGET_GOACC_REDUCTION nvptx_goacc_reduction
7958
7959 #undef TARGET_CANNOT_FORCE_CONST_MEM
7960 #define TARGET_CANNOT_FORCE_CONST_MEM nvptx_cannot_force_const_mem
7961
7962 #undef TARGET_SCALAR_MODE_SUPPORTED_P
7963 #define TARGET_SCALAR_MODE_SUPPORTED_P nvptx_scalar_mode_supported_p
7964
7965 #undef TARGET_LIBGCC_FLOATING_MODE_SUPPORTED_P
7966 #define TARGET_LIBGCC_FLOATING_MODE_SUPPORTED_P \
7967 nvptx_libgcc_floating_mode_supported_p
7968
7969 #undef TARGET_VECTOR_MODE_SUPPORTED_P
7970 #define TARGET_VECTOR_MODE_SUPPORTED_P nvptx_vector_mode_supported
7971
7972 #undef TARGET_VECTORIZE_PREFERRED_SIMD_MODE
7973 #define TARGET_VECTORIZE_PREFERRED_SIMD_MODE \
7974 nvptx_preferred_simd_mode
7975
7976 #undef TARGET_MODES_TIEABLE_P
7977 #define TARGET_MODES_TIEABLE_P nvptx_modes_tieable_p
7978
7979 #undef TARGET_HARD_REGNO_NREGS
7980 #define TARGET_HARD_REGNO_NREGS nvptx_hard_regno_nregs
7981
7982 #undef TARGET_CAN_CHANGE_MODE_CLASS
7983 #define TARGET_CAN_CHANGE_MODE_CLASS nvptx_can_change_mode_class
7984
7985 #undef TARGET_TRULY_NOOP_TRUNCATION
7986 #define TARGET_TRULY_NOOP_TRUNCATION nvptx_truly_noop_truncation
7987
7988 #undef TARGET_HAVE_SPECULATION_SAFE_VALUE
7989 #define TARGET_HAVE_SPECULATION_SAFE_VALUE speculation_safe_value_not_needed
7990
7991 #undef TARGET_GOACC_ADJUST_PRIVATE_DECL
7992 #define TARGET_GOACC_ADJUST_PRIVATE_DECL nvptx_goacc_adjust_private_decl
7993
7994 #undef TARGET_GOACC_EXPAND_VAR_DECL
7995 #define TARGET_GOACC_EXPAND_VAR_DECL nvptx_goacc_expand_var_decl
7996
7997 #undef TARGET_SET_CURRENT_FUNCTION
7998 #define TARGET_SET_CURRENT_FUNCTION nvptx_set_current_function
7999
8000 #undef TARGET_LIBC_HAS_FUNCTION
8001 #define TARGET_LIBC_HAS_FUNCTION nvptx_libc_has_function
8002
8003 #undef TARGET_HAVE_STRUB_SUPPORT_FOR
8004 #define TARGET_HAVE_STRUB_SUPPORT_FOR hook_bool_tree_false
8005
8006 #undef TARGET_DOCUMENTATION_NAME
8007 #define TARGET_DOCUMENTATION_NAME "Nvidia PTX"
8008
8009 struct gcc_target targetm = TARGET_INITIALIZER;
8010
8011 #include "gt-nvptx.h"