S/390: arch12: Support new vector floating point modes.
[platform/upstream/gcc.git] / gcc / config / s390 / s390.c
1 /* Subroutines used for code generation on IBM S/390 and zSeries
2    Copyright (C) 1999-2017 Free Software Foundation, Inc.
3    Contributed by Hartmut Penner (hpenner@de.ibm.com) and
4                   Ulrich Weigand (uweigand@de.ibm.com) and
5                   Andreas Krebbel (Andreas.Krebbel@de.ibm.com).
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "backend.h"
27 #include "target.h"
28 #include "target-globals.h"
29 #include "rtl.h"
30 #include "tree.h"
31 #include "gimple.h"
32 #include "cfghooks.h"
33 #include "cfgloop.h"
34 #include "df.h"
35 #include "memmodel.h"
36 #include "tm_p.h"
37 #include "stringpool.h"
38 #include "expmed.h"
39 #include "optabs.h"
40 #include "regs.h"
41 #include "emit-rtl.h"
42 #include "recog.h"
43 #include "cgraph.h"
44 #include "diagnostic-core.h"
45 #include "diagnostic.h"
46 #include "alias.h"
47 #include "fold-const.h"
48 #include "print-tree.h"
49 #include "stor-layout.h"
50 #include "varasm.h"
51 #include "calls.h"
52 #include "conditions.h"
53 #include "output.h"
54 #include "insn-attr.h"
55 #include "flags.h"
56 #include "except.h"
57 #include "dojump.h"
58 #include "explow.h"
59 #include "stmt.h"
60 #include "expr.h"
61 #include "reload.h"
62 #include "cfgrtl.h"
63 #include "cfganal.h"
64 #include "lcm.h"
65 #include "cfgbuild.h"
66 #include "cfgcleanup.h"
67 #include "debug.h"
68 #include "langhooks.h"
69 #include "internal-fn.h"
70 #include "gimple-fold.h"
71 #include "tree-eh.h"
72 #include "gimplify.h"
73 #include "params.h"
74 #include "opts.h"
75 #include "tree-pass.h"
76 #include "context.h"
77 #include "builtins.h"
78 #include "rtl-iter.h"
79 #include "intl.h"
80 #include "tm-constrs.h"
81
82 /* This file should be included last.  */
83 #include "target-def.h"
84
85 /* Remember the last target of s390_set_current_function.  */
86 static GTY(()) tree s390_previous_fndecl;
87
88 /* Define the specific costs for a given cpu.  */
89
90 struct processor_costs
91 {
92   /* multiplication */
93   const int m;        /* cost of an M instruction.  */
94   const int mghi;     /* cost of an MGHI instruction.  */
95   const int mh;       /* cost of an MH instruction.  */
96   const int mhi;      /* cost of an MHI instruction.  */
97   const int ml;       /* cost of an ML instruction.  */
98   const int mr;       /* cost of an MR instruction.  */
99   const int ms;       /* cost of an MS instruction.  */
100   const int msg;      /* cost of an MSG instruction.  */
101   const int msgf;     /* cost of an MSGF instruction.  */
102   const int msgfr;    /* cost of an MSGFR instruction.  */
103   const int msgr;     /* cost of an MSGR instruction.  */
104   const int msr;      /* cost of an MSR instruction.  */
105   const int mult_df;  /* cost of multiplication in DFmode.  */
106   const int mxbr;
107   /* square root */
108   const int sqxbr;    /* cost of square root in TFmode.  */
109   const int sqdbr;    /* cost of square root in DFmode.  */
110   const int sqebr;    /* cost of square root in SFmode.  */
111   /* multiply and add */
112   const int madbr;    /* cost of multiply and add in DFmode.  */
113   const int maebr;    /* cost of multiply and add in SFmode.  */
114   /* division */
115   const int dxbr;
116   const int ddbr;
117   const int debr;
118   const int dlgr;
119   const int dlr;
120   const int dr;
121   const int dsgfr;
122   const int dsgr;
123 };
124
125 #define s390_cost ((const struct processor_costs *)(s390_cost_pointer))
126
127 static const
128 struct processor_costs z900_cost =
129 {
130   COSTS_N_INSNS (5),     /* M     */
131   COSTS_N_INSNS (10),    /* MGHI  */
132   COSTS_N_INSNS (5),     /* MH    */
133   COSTS_N_INSNS (4),     /* MHI   */
134   COSTS_N_INSNS (5),     /* ML    */
135   COSTS_N_INSNS (5),     /* MR    */
136   COSTS_N_INSNS (4),     /* MS    */
137   COSTS_N_INSNS (15),    /* MSG   */
138   COSTS_N_INSNS (7),     /* MSGF  */
139   COSTS_N_INSNS (7),     /* MSGFR */
140   COSTS_N_INSNS (10),    /* MSGR  */
141   COSTS_N_INSNS (4),     /* MSR   */
142   COSTS_N_INSNS (7),     /* multiplication in DFmode */
143   COSTS_N_INSNS (13),    /* MXBR */
144   COSTS_N_INSNS (136),   /* SQXBR */
145   COSTS_N_INSNS (44),    /* SQDBR */
146   COSTS_N_INSNS (35),    /* SQEBR */
147   COSTS_N_INSNS (18),    /* MADBR */
148   COSTS_N_INSNS (13),    /* MAEBR */
149   COSTS_N_INSNS (134),   /* DXBR */
150   COSTS_N_INSNS (30),    /* DDBR */
151   COSTS_N_INSNS (27),    /* DEBR */
152   COSTS_N_INSNS (220),   /* DLGR */
153   COSTS_N_INSNS (34),    /* DLR */
154   COSTS_N_INSNS (34),    /* DR */
155   COSTS_N_INSNS (32),    /* DSGFR */
156   COSTS_N_INSNS (32),    /* DSGR */
157 };
158
159 static const
160 struct processor_costs z990_cost =
161 {
162   COSTS_N_INSNS (4),     /* M     */
163   COSTS_N_INSNS (2),     /* MGHI  */
164   COSTS_N_INSNS (2),     /* MH    */
165   COSTS_N_INSNS (2),     /* MHI   */
166   COSTS_N_INSNS (4),     /* ML    */
167   COSTS_N_INSNS (4),     /* MR    */
168   COSTS_N_INSNS (5),     /* MS    */
169   COSTS_N_INSNS (6),     /* MSG   */
170   COSTS_N_INSNS (4),     /* MSGF  */
171   COSTS_N_INSNS (4),     /* MSGFR */
172   COSTS_N_INSNS (4),     /* MSGR  */
173   COSTS_N_INSNS (4),     /* MSR   */
174   COSTS_N_INSNS (1),     /* multiplication in DFmode */
175   COSTS_N_INSNS (28),    /* MXBR */
176   COSTS_N_INSNS (130),   /* SQXBR */
177   COSTS_N_INSNS (66),    /* SQDBR */
178   COSTS_N_INSNS (38),    /* SQEBR */
179   COSTS_N_INSNS (1),     /* MADBR */
180   COSTS_N_INSNS (1),     /* MAEBR */
181   COSTS_N_INSNS (60),    /* DXBR */
182   COSTS_N_INSNS (40),    /* DDBR */
183   COSTS_N_INSNS (26),    /* DEBR */
184   COSTS_N_INSNS (176),   /* DLGR */
185   COSTS_N_INSNS (31),    /* DLR */
186   COSTS_N_INSNS (31),    /* DR */
187   COSTS_N_INSNS (31),    /* DSGFR */
188   COSTS_N_INSNS (31),    /* DSGR */
189 };
190
191 static const
192 struct processor_costs z9_109_cost =
193 {
194   COSTS_N_INSNS (4),     /* M     */
195   COSTS_N_INSNS (2),     /* MGHI  */
196   COSTS_N_INSNS (2),     /* MH    */
197   COSTS_N_INSNS (2),     /* MHI   */
198   COSTS_N_INSNS (4),     /* ML    */
199   COSTS_N_INSNS (4),     /* MR    */
200   COSTS_N_INSNS (5),     /* MS    */
201   COSTS_N_INSNS (6),     /* MSG   */
202   COSTS_N_INSNS (4),     /* MSGF  */
203   COSTS_N_INSNS (4),     /* MSGFR */
204   COSTS_N_INSNS (4),     /* MSGR  */
205   COSTS_N_INSNS (4),     /* MSR   */
206   COSTS_N_INSNS (1),     /* multiplication in DFmode */
207   COSTS_N_INSNS (28),    /* MXBR */
208   COSTS_N_INSNS (130),   /* SQXBR */
209   COSTS_N_INSNS (66),    /* SQDBR */
210   COSTS_N_INSNS (38),    /* SQEBR */
211   COSTS_N_INSNS (1),     /* MADBR */
212   COSTS_N_INSNS (1),     /* MAEBR */
213   COSTS_N_INSNS (60),    /* DXBR */
214   COSTS_N_INSNS (40),    /* DDBR */
215   COSTS_N_INSNS (26),    /* DEBR */
216   COSTS_N_INSNS (30),    /* DLGR */
217   COSTS_N_INSNS (23),    /* DLR */
218   COSTS_N_INSNS (23),    /* DR */
219   COSTS_N_INSNS (24),    /* DSGFR */
220   COSTS_N_INSNS (24),    /* DSGR */
221 };
222
223 static const
224 struct processor_costs z10_cost =
225 {
226   COSTS_N_INSNS (10),    /* M     */
227   COSTS_N_INSNS (10),    /* MGHI  */
228   COSTS_N_INSNS (10),    /* MH    */
229   COSTS_N_INSNS (10),    /* MHI   */
230   COSTS_N_INSNS (10),    /* ML    */
231   COSTS_N_INSNS (10),    /* MR    */
232   COSTS_N_INSNS (10),    /* MS    */
233   COSTS_N_INSNS (10),    /* MSG   */
234   COSTS_N_INSNS (10),    /* MSGF  */
235   COSTS_N_INSNS (10),    /* MSGFR */
236   COSTS_N_INSNS (10),    /* MSGR  */
237   COSTS_N_INSNS (10),    /* MSR   */
238   COSTS_N_INSNS (1) ,    /* multiplication in DFmode */
239   COSTS_N_INSNS (50),    /* MXBR */
240   COSTS_N_INSNS (120),   /* SQXBR */
241   COSTS_N_INSNS (52),    /* SQDBR */
242   COSTS_N_INSNS (38),    /* SQEBR */
243   COSTS_N_INSNS (1),     /* MADBR */
244   COSTS_N_INSNS (1),     /* MAEBR */
245   COSTS_N_INSNS (111),   /* DXBR */
246   COSTS_N_INSNS (39),    /* DDBR */
247   COSTS_N_INSNS (32),    /* DEBR */
248   COSTS_N_INSNS (160),   /* DLGR */
249   COSTS_N_INSNS (71),    /* DLR */
250   COSTS_N_INSNS (71),    /* DR */
251   COSTS_N_INSNS (71),    /* DSGFR */
252   COSTS_N_INSNS (71),    /* DSGR */
253 };
254
255 static const
256 struct processor_costs z196_cost =
257 {
258   COSTS_N_INSNS (7),     /* M     */
259   COSTS_N_INSNS (5),     /* MGHI  */
260   COSTS_N_INSNS (5),     /* MH    */
261   COSTS_N_INSNS (5),     /* MHI   */
262   COSTS_N_INSNS (7),     /* ML    */
263   COSTS_N_INSNS (7),     /* MR    */
264   COSTS_N_INSNS (6),     /* MS    */
265   COSTS_N_INSNS (8),     /* MSG   */
266   COSTS_N_INSNS (6),     /* MSGF  */
267   COSTS_N_INSNS (6),     /* MSGFR */
268   COSTS_N_INSNS (8),     /* MSGR  */
269   COSTS_N_INSNS (6),     /* MSR   */
270   COSTS_N_INSNS (1) ,    /* multiplication in DFmode */
271   COSTS_N_INSNS (40),    /* MXBR B+40 */
272   COSTS_N_INSNS (100),   /* SQXBR B+100 */
273   COSTS_N_INSNS (42),    /* SQDBR B+42 */
274   COSTS_N_INSNS (28),    /* SQEBR B+28 */
275   COSTS_N_INSNS (1),     /* MADBR B */
276   COSTS_N_INSNS (1),     /* MAEBR B */
277   COSTS_N_INSNS (101),   /* DXBR B+101 */
278   COSTS_N_INSNS (29),    /* DDBR */
279   COSTS_N_INSNS (22),    /* DEBR */
280   COSTS_N_INSNS (160),   /* DLGR cracked */
281   COSTS_N_INSNS (160),   /* DLR cracked */
282   COSTS_N_INSNS (160),   /* DR expanded */
283   COSTS_N_INSNS (160),   /* DSGFR cracked */
284   COSTS_N_INSNS (160),   /* DSGR cracked */
285 };
286
287 static const
288 struct processor_costs zEC12_cost =
289 {
290   COSTS_N_INSNS (7),     /* M     */
291   COSTS_N_INSNS (5),     /* MGHI  */
292   COSTS_N_INSNS (5),     /* MH    */
293   COSTS_N_INSNS (5),     /* MHI   */
294   COSTS_N_INSNS (7),     /* ML    */
295   COSTS_N_INSNS (7),     /* MR    */
296   COSTS_N_INSNS (6),     /* MS    */
297   COSTS_N_INSNS (8),     /* MSG   */
298   COSTS_N_INSNS (6),     /* MSGF  */
299   COSTS_N_INSNS (6),     /* MSGFR */
300   COSTS_N_INSNS (8),     /* MSGR  */
301   COSTS_N_INSNS (6),     /* MSR   */
302   COSTS_N_INSNS (1) ,    /* multiplication in DFmode */
303   COSTS_N_INSNS (40),    /* MXBR B+40 */
304   COSTS_N_INSNS (100),   /* SQXBR B+100 */
305   COSTS_N_INSNS (42),    /* SQDBR B+42 */
306   COSTS_N_INSNS (28),    /* SQEBR B+28 */
307   COSTS_N_INSNS (1),     /* MADBR B */
308   COSTS_N_INSNS (1),     /* MAEBR B */
309   COSTS_N_INSNS (131),   /* DXBR B+131 */
310   COSTS_N_INSNS (29),    /* DDBR */
311   COSTS_N_INSNS (22),    /* DEBR */
312   COSTS_N_INSNS (160),   /* DLGR cracked */
313   COSTS_N_INSNS (160),   /* DLR cracked */
314   COSTS_N_INSNS (160),   /* DR expanded */
315   COSTS_N_INSNS (160),   /* DSGFR cracked */
316   COSTS_N_INSNS (160),   /* DSGR cracked */
317 };
318
319 static struct
320 {
321   const char *const name;
322   const enum processor_type processor;
323   const struct processor_costs *cost;
324 }
325 const processor_table[] =
326 {
327   { "g5",     PROCESSOR_9672_G5,     &z900_cost },
328   { "g6",     PROCESSOR_9672_G6,     &z900_cost },
329   { "z900",   PROCESSOR_2064_Z900,   &z900_cost },
330   { "z990",   PROCESSOR_2084_Z990,   &z990_cost },
331   { "z9-109", PROCESSOR_2094_Z9_109, &z9_109_cost },
332   { "z9-ec",  PROCESSOR_2094_Z9_EC,  &z9_109_cost },
333   { "z10",    PROCESSOR_2097_Z10,    &z10_cost },
334   { "z196",   PROCESSOR_2817_Z196,   &z196_cost },
335   { "zEC12",  PROCESSOR_2827_ZEC12,  &zEC12_cost },
336   { "z13",    PROCESSOR_2964_Z13,    &zEC12_cost },
337   { "arch12", PROCESSOR_ARCH12,      &zEC12_cost },
338   { "native", PROCESSOR_NATIVE,      NULL }
339 };
340
341 extern int reload_completed;
342
343 /* Kept up to date using the SCHED_VARIABLE_ISSUE hook.  */
344 static rtx_insn *last_scheduled_insn;
345 #define MAX_SCHED_UNITS 3
346 static int last_scheduled_unit_distance[MAX_SCHED_UNITS];
347
348 /* The maximum score added for an instruction whose unit hasn't been
349    in use for MAX_SCHED_MIX_DISTANCE steps.  Increase this value to
350    give instruction mix scheduling more priority over instruction
351    grouping.  */
352 #define MAX_SCHED_MIX_SCORE      8
353
354 /* The maximum distance up to which individual scores will be
355    calculated.  Everything beyond this gives MAX_SCHED_MIX_SCORE.
356    Increase this with the OOO windows size of the machine.  */
357 #define MAX_SCHED_MIX_DISTANCE 100
358
359 /* Structure used to hold the components of a S/390 memory
360    address.  A legitimate address on S/390 is of the general
361    form
362           base + index + displacement
363    where any of the components is optional.
364
365    base and index are registers of the class ADDR_REGS,
366    displacement is an unsigned 12-bit immediate constant.  */
367
368 struct s390_address
369 {
370   rtx base;
371   rtx indx;
372   rtx disp;
373   bool pointer;
374   bool literal_pool;
375 };
376
377 /* The following structure is embedded in the machine
378    specific part of struct function.  */
379
380 struct GTY (()) s390_frame_layout
381 {
382   /* Offset within stack frame.  */
383   HOST_WIDE_INT gprs_offset;
384   HOST_WIDE_INT f0_offset;
385   HOST_WIDE_INT f4_offset;
386   HOST_WIDE_INT f8_offset;
387   HOST_WIDE_INT backchain_offset;
388
389   /* Number of first and last gpr where slots in the register
390      save area are reserved for.  */
391   int first_save_gpr_slot;
392   int last_save_gpr_slot;
393
394   /* Location (FP register number) where GPRs (r0-r15) should
395      be saved to.
396       0 - does not need to be saved at all
397      -1 - stack slot  */
398 #define SAVE_SLOT_NONE   0
399 #define SAVE_SLOT_STACK -1
400   signed char gpr_save_slots[16];
401
402   /* Number of first and last gpr to be saved, restored.  */
403   int first_save_gpr;
404   int first_restore_gpr;
405   int last_save_gpr;
406   int last_restore_gpr;
407
408   /* Bits standing for floating point registers. Set, if the
409      respective register has to be saved. Starting with reg 16 (f0)
410      at the rightmost bit.
411      Bit 15 14 13 12 11 10  9  8  7  6  5  4  3  2  1  0
412      fpr 15 13 11  9 14 12 10  8  7  5  3  1  6  4  2  0
413      reg 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16  */
414   unsigned int fpr_bitmap;
415
416   /* Number of floating point registers f8-f15 which must be saved.  */
417   int high_fprs;
418
419   /* Set if return address needs to be saved.
420      This flag is set by s390_return_addr_rtx if it could not use
421      the initial value of r14 and therefore depends on r14 saved
422      to the stack.  */
423   bool save_return_addr_p;
424
425   /* Size of stack frame.  */
426   HOST_WIDE_INT frame_size;
427 };
428
429 /* Define the structure for the machine field in struct function.  */
430
431 struct GTY(()) machine_function
432 {
433   struct s390_frame_layout frame_layout;
434
435   /* Literal pool base register.  */
436   rtx base_reg;
437
438   /* True if we may need to perform branch splitting.  */
439   bool split_branches_pending_p;
440
441   bool has_landing_pad_p;
442
443   /* True if the current function may contain a tbegin clobbering
444      FPRs.  */
445   bool tbegin_p;
446
447   /* For -fsplit-stack support: A stack local which holds a pointer to
448      the stack arguments for a function with a variable number of
449      arguments.  This is set at the start of the function and is used
450      to initialize the overflow_arg_area field of the va_list
451      structure.  */
452   rtx split_stack_varargs_pointer;
453 };
454
455 /* Few accessor macros for struct cfun->machine->s390_frame_layout.  */
456
457 #define cfun_frame_layout (cfun->machine->frame_layout)
458 #define cfun_save_high_fprs_p (!!cfun_frame_layout.high_fprs)
459 #define cfun_save_arg_fprs_p (!!(TARGET_64BIT                           \
460                                  ? cfun_frame_layout.fpr_bitmap & 0x0f  \
461                                  : cfun_frame_layout.fpr_bitmap & 0x03))
462 #define cfun_gprs_save_area_size ((cfun_frame_layout.last_save_gpr_slot - \
463   cfun_frame_layout.first_save_gpr_slot + 1) * UNITS_PER_LONG)
464 #define cfun_set_fpr_save(REGNO) (cfun->machine->frame_layout.fpr_bitmap |=    \
465   (1 << (REGNO - FPR0_REGNUM)))
466 #define cfun_fpr_save_p(REGNO) (!!(cfun->machine->frame_layout.fpr_bitmap &    \
467   (1 << (REGNO - FPR0_REGNUM))))
468 #define cfun_gpr_save_slot(REGNO) \
469   cfun->machine->frame_layout.gpr_save_slots[REGNO]
470
471 /* Number of GPRs and FPRs used for argument passing.  */
472 #define GP_ARG_NUM_REG 5
473 #define FP_ARG_NUM_REG (TARGET_64BIT? 4 : 2)
474 #define VEC_ARG_NUM_REG 8
475
476 /* A couple of shortcuts.  */
477 #define CONST_OK_FOR_J(x) \
478         CONST_OK_FOR_CONSTRAINT_P((x), 'J', "J")
479 #define CONST_OK_FOR_K(x) \
480         CONST_OK_FOR_CONSTRAINT_P((x), 'K', "K")
481 #define CONST_OK_FOR_Os(x) \
482         CONST_OK_FOR_CONSTRAINT_P((x), 'O', "Os")
483 #define CONST_OK_FOR_Op(x) \
484         CONST_OK_FOR_CONSTRAINT_P((x), 'O', "Op")
485 #define CONST_OK_FOR_On(x) \
486         CONST_OK_FOR_CONSTRAINT_P((x), 'O', "On")
487
488 #define REGNO_PAIR_OK(REGNO, MODE)                               \
489   (HARD_REGNO_NREGS ((REGNO), (MODE)) == 1 || !((REGNO) & 1))
490
491 /* That's the read ahead of the dynamic branch prediction unit in
492    bytes on a z10 (or higher) CPU.  */
493 #define PREDICT_DISTANCE (TARGET_Z10 ? 384 : 2048)
494
495
496 /* Indicate which ABI has been used for passing vector args.
497    0 - no vector type arguments have been passed where the ABI is relevant
498    1 - the old ABI has been used
499    2 - a vector type argument has been passed either in a vector register
500        or on the stack by value  */
501 static int s390_vector_abi = 0;
502
503 /* Set the vector ABI marker if TYPE is subject to the vector ABI
504    switch.  The vector ABI affects only vector data types.  There are
505    two aspects of the vector ABI relevant here:
506
507    1. vectors >= 16 bytes have an alignment of 8 bytes with the new
508    ABI and natural alignment with the old.
509
510    2. vector <= 16 bytes are passed in VRs or by value on the stack
511    with the new ABI but by reference on the stack with the old.
512
513    If ARG_P is true TYPE is used for a function argument or return
514    value.  The ABI marker then is set for all vector data types.  If
515    ARG_P is false only type 1 vectors are being checked.  */
516
517 static void
518 s390_check_type_for_vector_abi (const_tree type, bool arg_p, bool in_struct_p)
519 {
520   static hash_set<const_tree> visited_types_hash;
521
522   if (s390_vector_abi)
523     return;
524
525   if (type == NULL_TREE || TREE_CODE (type) == ERROR_MARK)
526     return;
527
528   if (visited_types_hash.contains (type))
529     return;
530
531   visited_types_hash.add (type);
532
533   if (VECTOR_TYPE_P (type))
534     {
535       int type_size = int_size_in_bytes (type);
536
537       /* Outside arguments only the alignment is changing and this
538          only happens for vector types >= 16 bytes.  */
539       if (!arg_p && type_size < 16)
540         return;
541
542       /* In arguments vector types > 16 are passed as before (GCC
543          never enforced the bigger alignment for arguments which was
544          required by the old vector ABI).  However, it might still be
545          ABI relevant due to the changed alignment if it is a struct
546          member.  */
547       if (arg_p && type_size > 16 && !in_struct_p)
548         return;
549
550       s390_vector_abi = TARGET_VX_ABI ? 2 : 1;
551     }
552   else if (POINTER_TYPE_P (type) || TREE_CODE (type) == ARRAY_TYPE)
553     {
554       /* ARRAY_TYPE: Since with neither of the ABIs we have more than
555          natural alignment there will never be ABI dependent padding
556          in an array type.  That's why we do not set in_struct_p to
557          true here.  */
558       s390_check_type_for_vector_abi (TREE_TYPE (type), arg_p, in_struct_p);
559     }
560   else if (TREE_CODE (type) == FUNCTION_TYPE || TREE_CODE (type) == METHOD_TYPE)
561     {
562       tree arg_chain;
563
564       /* Check the return type.  */
565       s390_check_type_for_vector_abi (TREE_TYPE (type), true, false);
566
567       for (arg_chain = TYPE_ARG_TYPES (type);
568            arg_chain;
569            arg_chain = TREE_CHAIN (arg_chain))
570         s390_check_type_for_vector_abi (TREE_VALUE (arg_chain), true, false);
571     }
572   else if (RECORD_OR_UNION_TYPE_P (type))
573     {
574       tree field;
575
576       for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
577         {
578           if (TREE_CODE (field) != FIELD_DECL)
579             continue;
580
581           s390_check_type_for_vector_abi (TREE_TYPE (field), arg_p, true);
582         }
583     }
584 }
585
586
587 /* System z builtins.  */
588
589 #include "s390-builtins.h"
590
591 const unsigned int bflags_builtin[S390_BUILTIN_MAX + 1] =
592   {
593 #undef B_DEF
594 #undef OB_DEF
595 #undef OB_DEF_VAR
596 #define B_DEF(NAME, PATTERN, ATTRS, BFLAGS, ...) BFLAGS,
597 #define OB_DEF(...)
598 #define OB_DEF_VAR(...)
599 #include "s390-builtins.def"
600     0
601   };
602
603 const unsigned int opflags_builtin[S390_BUILTIN_MAX + 1] =
604   {
605 #undef B_DEF
606 #undef OB_DEF
607 #undef OB_DEF_VAR
608 #define B_DEF(NAME, PATTERN, ATTRS, BFLAGS, OPFLAGS, ...) OPFLAGS,
609 #define OB_DEF(...)
610 #define OB_DEF_VAR(...)
611 #include "s390-builtins.def"
612     0
613   };
614
615 const unsigned int bflags_overloaded_builtin[S390_OVERLOADED_BUILTIN_MAX + 1] =
616   {
617 #undef B_DEF
618 #undef OB_DEF
619 #undef OB_DEF_VAR
620 #define B_DEF(...)
621 #define OB_DEF(NAME, FIRST_VAR_NAME, LAST_VAR_NAME, BFLAGS, ...) BFLAGS,
622 #define OB_DEF_VAR(...)
623 #include "s390-builtins.def"
624     0
625   };
626
627 const unsigned int
628 opflags_overloaded_builtin_var[S390_OVERLOADED_BUILTIN_VAR_MAX + 1] =
629   {
630 #undef B_DEF
631 #undef OB_DEF
632 #undef OB_DEF_VAR
633 #define B_DEF(...)
634 #define OB_DEF(...)
635 #define OB_DEF_VAR(NAME, PATTERN, FLAGS, FNTYPE) FLAGS,
636 #include "s390-builtins.def"
637     0
638   };
639
640 tree s390_builtin_types[BT_MAX];
641 tree s390_builtin_fn_types[BT_FN_MAX];
642 tree s390_builtin_decls[S390_BUILTIN_MAX +
643                         S390_OVERLOADED_BUILTIN_MAX +
644                         S390_OVERLOADED_BUILTIN_VAR_MAX];
645
646 static enum insn_code const code_for_builtin[S390_BUILTIN_MAX + 1] = {
647 #undef B_DEF
648 #undef OB_DEF
649 #undef OB_DEF_VAR
650 #define B_DEF(NAME, PATTERN, ...) CODE_FOR_##PATTERN,
651 #define OB_DEF(...)
652 #define OB_DEF_VAR(...)
653
654 #include "s390-builtins.def"
655   CODE_FOR_nothing
656 };
657
658 static void
659 s390_init_builtins (void)
660 {
661   /* These definitions are being used in s390-builtins.def.  */
662   tree returns_twice_attr = tree_cons (get_identifier ("returns_twice"),
663                                        NULL, NULL);
664   tree noreturn_attr = tree_cons (get_identifier ("noreturn"), NULL, NULL);
665   tree c_uint64_type_node;
666
667   /* The uint64_type_node from tree.c is not compatible to the C99
668      uint64_t data type.  What we want is c_uint64_type_node from
669      c-common.c.  But since backend code is not supposed to interface
670      with the frontend we recreate it here.  */
671   if (TARGET_64BIT)
672     c_uint64_type_node = long_unsigned_type_node;
673   else
674     c_uint64_type_node = long_long_unsigned_type_node;
675
676 #undef DEF_TYPE
677 #define DEF_TYPE(INDEX, NODE, CONST_P)                  \
678   if (s390_builtin_types[INDEX] == NULL)                \
679     s390_builtin_types[INDEX] = (!CONST_P) ?            \
680       (NODE) : build_type_variant ((NODE), 1, 0);
681
682 #undef DEF_POINTER_TYPE
683 #define DEF_POINTER_TYPE(INDEX, INDEX_BASE)                             \
684   if (s390_builtin_types[INDEX] == NULL)                                \
685     s390_builtin_types[INDEX] =                                         \
686       build_pointer_type (s390_builtin_types[INDEX_BASE]);
687
688 #undef DEF_DISTINCT_TYPE
689 #define DEF_DISTINCT_TYPE(INDEX, INDEX_BASE)                            \
690   if (s390_builtin_types[INDEX] == NULL)                                \
691     s390_builtin_types[INDEX] =                                         \
692       build_distinct_type_copy (s390_builtin_types[INDEX_BASE]);
693
694 #undef DEF_VECTOR_TYPE
695 #define DEF_VECTOR_TYPE(INDEX, INDEX_BASE, ELEMENTS)                    \
696   if (s390_builtin_types[INDEX] == NULL)                                \
697     s390_builtin_types[INDEX] =                                         \
698       build_vector_type (s390_builtin_types[INDEX_BASE], ELEMENTS);
699
700 #undef DEF_OPAQUE_VECTOR_TYPE
701 #define DEF_OPAQUE_VECTOR_TYPE(INDEX, INDEX_BASE, ELEMENTS)             \
702   if (s390_builtin_types[INDEX] == NULL)                                \
703     s390_builtin_types[INDEX] =                                         \
704       build_opaque_vector_type (s390_builtin_types[INDEX_BASE], ELEMENTS);
705
706 #undef DEF_FN_TYPE
707 #define DEF_FN_TYPE(INDEX, args...)                             \
708   if (s390_builtin_fn_types[INDEX] == NULL)                     \
709     s390_builtin_fn_types[INDEX] =                              \
710       build_function_type_list (args, NULL_TREE);
711 #undef DEF_OV_TYPE
712 #define DEF_OV_TYPE(...)
713 #include "s390-builtin-types.def"
714
715 #undef B_DEF
716 #define B_DEF(NAME, PATTERN, ATTRS, BFLAGS, OPFLAGS, FNTYPE)            \
717   if (s390_builtin_decls[S390_BUILTIN_##NAME] == NULL)                  \
718     s390_builtin_decls[S390_BUILTIN_##NAME] =                           \
719       add_builtin_function ("__builtin_" #NAME,                         \
720                             s390_builtin_fn_types[FNTYPE],              \
721                             S390_BUILTIN_##NAME,                        \
722                             BUILT_IN_MD,                                \
723                             NULL,                                       \
724                             ATTRS);
725 #undef OB_DEF
726 #define OB_DEF(NAME, FIRST_VAR_NAME, LAST_VAR_NAME, BFLAGS, FNTYPE)     \
727   if (s390_builtin_decls[S390_OVERLOADED_BUILTIN_##NAME + S390_BUILTIN_MAX] \
728       == NULL)                                                          \
729     s390_builtin_decls[S390_OVERLOADED_BUILTIN_##NAME + S390_BUILTIN_MAX] = \
730       add_builtin_function ("__builtin_" #NAME,                         \
731                             s390_builtin_fn_types[FNTYPE],              \
732                             S390_OVERLOADED_BUILTIN_##NAME + S390_BUILTIN_MAX, \
733                             BUILT_IN_MD,                                \
734                             NULL,                                       \
735                             0);
736 #undef OB_DEF_VAR
737 #define OB_DEF_VAR(...)
738 #include "s390-builtins.def"
739
740 }
741
742 /* Return true if ARG is appropriate as argument number ARGNUM of
743    builtin DECL.  The operand flags from s390-builtins.def have to
744    passed as OP_FLAGS.  */
745 bool
746 s390_const_operand_ok (tree arg, int argnum, int op_flags, tree decl)
747 {
748   if (O_UIMM_P (op_flags))
749     {
750       int bitwidths[] = { 1, 2, 3, 4, 5, 8, 12, 16, 32 };
751       int bitwidth = bitwidths[op_flags - O_U1];
752
753       if (!tree_fits_uhwi_p (arg)
754           || tree_to_uhwi (arg) > (HOST_WIDE_INT_1U << bitwidth) - 1)
755         {
756           error("constant argument %d for builtin %qF is out of range (0.."
757                 HOST_WIDE_INT_PRINT_UNSIGNED ")",
758                 argnum, decl,
759                 (HOST_WIDE_INT_1U << bitwidth) - 1);
760           return false;
761         }
762     }
763
764   if (O_SIMM_P (op_flags))
765     {
766       int bitwidths[] = { 2, 3, 4, 5, 8, 12, 16, 32 };
767       int bitwidth = bitwidths[op_flags - O_S2];
768
769       if (!tree_fits_shwi_p (arg)
770           || tree_to_shwi (arg) < -(HOST_WIDE_INT_1 << (bitwidth - 1))
771           || tree_to_shwi (arg) > ((HOST_WIDE_INT_1 << (bitwidth - 1)) - 1))
772         {
773           error("constant argument %d for builtin %qF is out of range ("
774                 HOST_WIDE_INT_PRINT_DEC ".."
775                 HOST_WIDE_INT_PRINT_DEC ")",
776                 argnum, decl,
777                 -(HOST_WIDE_INT_1 << (bitwidth - 1)),
778                 (HOST_WIDE_INT_1 << (bitwidth - 1)) - 1);
779           return false;
780         }
781     }
782   return true;
783 }
784
785 /* Expand an expression EXP that calls a built-in function,
786    with result going to TARGET if that's convenient
787    (and in mode MODE if that's convenient).
788    SUBTARGET may be used as the target for computing one of EXP's operands.
789    IGNORE is nonzero if the value is to be ignored.  */
790
791 static rtx
792 s390_expand_builtin (tree exp, rtx target, rtx subtarget ATTRIBUTE_UNUSED,
793                      machine_mode mode ATTRIBUTE_UNUSED,
794                      int ignore ATTRIBUTE_UNUSED)
795 {
796 #define MAX_ARGS 6
797
798   tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
799   unsigned int fcode = DECL_FUNCTION_CODE (fndecl);
800   enum insn_code icode;
801   rtx op[MAX_ARGS], pat;
802   int arity;
803   bool nonvoid;
804   tree arg;
805   call_expr_arg_iterator iter;
806   unsigned int all_op_flags = opflags_for_builtin (fcode);
807   machine_mode last_vec_mode = VOIDmode;
808
809   if (TARGET_DEBUG_ARG)
810     {
811       fprintf (stderr,
812                "s390_expand_builtin, code = %4d, %s, bflags = 0x%x\n",
813                (int)fcode, IDENTIFIER_POINTER (DECL_NAME (fndecl)),
814                bflags_for_builtin (fcode));
815     }
816
817   if (S390_USE_TARGET_ATTRIBUTE)
818     {
819       unsigned int bflags;
820
821       bflags = bflags_for_builtin (fcode);
822       if ((bflags & B_HTM) && !TARGET_HTM)
823         {
824           error ("builtin %qF is not supported without -mhtm "
825                  "(default with -march=zEC12 and higher).", fndecl);
826           return const0_rtx;
827         }
828       if (((bflags & B_VX) || (bflags & B_VXE)) && !TARGET_VX)
829         {
830           error ("builtin %qF is not supported without -mvx "
831                  "(default with -march=z13 and higher).", fndecl);
832           return const0_rtx;
833         }
834
835       if ((bflags & B_VXE) && !TARGET_VXE)
836         {
837           error ("Builtin %qF requires arch12 or higher.", fndecl);
838           return const0_rtx;
839         }
840     }
841   if (fcode >= S390_OVERLOADED_BUILTIN_VAR_OFFSET
842       && fcode < S390_ALL_BUILTIN_MAX)
843     {
844       gcc_unreachable ();
845     }
846   else if (fcode < S390_OVERLOADED_BUILTIN_OFFSET)
847     {
848       icode = code_for_builtin[fcode];
849       /* Set a flag in the machine specific cfun part in order to support
850          saving/restoring of FPRs.  */
851       if (fcode == S390_BUILTIN_tbegin || fcode == S390_BUILTIN_tbegin_retry)
852         cfun->machine->tbegin_p = true;
853     }
854   else if (fcode < S390_OVERLOADED_BUILTIN_VAR_OFFSET)
855     {
856       error ("unresolved overloaded builtin");
857       return const0_rtx;
858     }
859   else
860     internal_error ("bad builtin fcode");
861
862   if (icode == 0)
863     internal_error ("bad builtin icode");
864
865   nonvoid = TREE_TYPE (TREE_TYPE (fndecl)) != void_type_node;
866
867   if (nonvoid)
868     {
869       machine_mode tmode = insn_data[icode].operand[0].mode;
870       if (!target
871           || GET_MODE (target) != tmode
872           || !(*insn_data[icode].operand[0].predicate) (target, tmode))
873         target = gen_reg_rtx (tmode);
874
875       /* There are builtins (e.g. vec_promote) with no vector
876          arguments but an element selector.  So we have to also look
877          at the vector return type when emitting the modulo
878          operation.  */
879       if (VECTOR_MODE_P (insn_data[icode].operand[0].mode))
880         last_vec_mode = insn_data[icode].operand[0].mode;
881     }
882
883   arity = 0;
884   FOR_EACH_CALL_EXPR_ARG (arg, iter, exp)
885     {
886       rtx tmp_rtx;
887       const struct insn_operand_data *insn_op;
888       unsigned int op_flags = all_op_flags & ((1 << O_SHIFT) - 1);
889
890       all_op_flags = all_op_flags >> O_SHIFT;
891
892       if (arg == error_mark_node)
893         return NULL_RTX;
894       if (arity >= MAX_ARGS)
895         return NULL_RTX;
896
897       if (O_IMM_P (op_flags)
898           && TREE_CODE (arg) != INTEGER_CST)
899         {
900           error ("constant value required for builtin %qF argument %d",
901                  fndecl, arity + 1);
902           return const0_rtx;
903         }
904
905       if (!s390_const_operand_ok (arg, arity + 1, op_flags, fndecl))
906         return const0_rtx;
907
908       insn_op = &insn_data[icode].operand[arity + nonvoid];
909       op[arity] = expand_expr (arg, NULL_RTX, insn_op->mode, EXPAND_NORMAL);
910
911       /* expand_expr truncates constants to the target mode only if it
912          is "convenient".  However, our checks below rely on this
913          being done.  */
914       if (CONST_INT_P (op[arity])
915           && SCALAR_INT_MODE_P (insn_op->mode)
916           && GET_MODE (op[arity]) != insn_op->mode)
917         op[arity] = GEN_INT (trunc_int_for_mode (INTVAL (op[arity]),
918                                                  insn_op->mode));
919
920       /* Wrap the expanded RTX for pointer types into a MEM expr with
921          the proper mode.  This allows us to use e.g. (match_operand
922          "memory_operand"..) in the insn patterns instead of (mem
923          (match_operand "address_operand)).  This is helpful for
924          patterns not just accepting MEMs.  */
925       if (POINTER_TYPE_P (TREE_TYPE (arg))
926           && insn_op->predicate != address_operand)
927         op[arity] = gen_rtx_MEM (insn_op->mode, op[arity]);
928
929       /* Expand the module operation required on element selectors.  */
930       if (op_flags == O_ELEM)
931         {
932           gcc_assert (last_vec_mode != VOIDmode);
933           op[arity] = simplify_expand_binop (SImode, code_to_optab (AND),
934                                              op[arity],
935                                              GEN_INT (GET_MODE_NUNITS (last_vec_mode) - 1),
936                                              NULL_RTX, 1, OPTAB_DIRECT);
937         }
938
939       /* Record the vector mode used for an element selector.  This assumes:
940          1. There is no builtin with two different vector modes and an element selector
941          2. The element selector comes after the vector type it is referring to.
942          This currently the true for all the builtins but FIXME we
943          should better check for that.  */
944       if (VECTOR_MODE_P (insn_op->mode))
945         last_vec_mode = insn_op->mode;
946
947       if (insn_op->predicate (op[arity], insn_op->mode))
948         {
949           arity++;
950           continue;
951         }
952
953       if (MEM_P (op[arity])
954           && insn_op->predicate == memory_operand
955           && (GET_MODE (XEXP (op[arity], 0)) == Pmode
956               || GET_MODE (XEXP (op[arity], 0)) == VOIDmode))
957         {
958           op[arity] = replace_equiv_address (op[arity],
959                                              copy_to_mode_reg (Pmode,
960                                                XEXP (op[arity], 0)));
961         }
962       /* Some of the builtins require different modes/types than the
963          pattern in order to implement a specific API.  Instead of
964          adding many expanders which do the mode change we do it here.
965          E.g. s390_vec_add_u128 required to have vector unsigned char
966          arguments is mapped to addti3.  */
967       else if (insn_op->mode != VOIDmode
968                && GET_MODE (op[arity]) != VOIDmode
969                && GET_MODE (op[arity]) != insn_op->mode
970                && ((tmp_rtx = simplify_gen_subreg (insn_op->mode, op[arity],
971                                                    GET_MODE (op[arity]), 0))
972                    != NULL_RTX))
973         {
974           op[arity] = tmp_rtx;
975         }
976       else if (GET_MODE (op[arity]) == insn_op->mode
977                || GET_MODE (op[arity]) == VOIDmode
978                || (insn_op->predicate == address_operand
979                    && GET_MODE (op[arity]) == Pmode))
980         {
981           /* An address_operand usually has VOIDmode in the expander
982              so we cannot use this.  */
983           machine_mode target_mode =
984             (insn_op->predicate == address_operand
985              ? Pmode : insn_op->mode);
986           op[arity] = copy_to_mode_reg (target_mode, op[arity]);
987         }
988
989       if (!insn_op->predicate (op[arity], insn_op->mode))
990         {
991           error ("invalid argument %d for builtin %qF", arity + 1, fndecl);
992           return const0_rtx;
993         }
994       arity++;
995     }
996
997   switch (arity)
998     {
999     case 0:
1000       pat = GEN_FCN (icode) (target);
1001       break;
1002     case 1:
1003       if (nonvoid)
1004         pat = GEN_FCN (icode) (target, op[0]);
1005       else
1006         pat = GEN_FCN (icode) (op[0]);
1007       break;
1008     case 2:
1009       if (nonvoid)
1010         pat = GEN_FCN (icode) (target, op[0], op[1]);
1011       else
1012         pat = GEN_FCN (icode) (op[0], op[1]);
1013       break;
1014     case 3:
1015       if (nonvoid)
1016         pat = GEN_FCN (icode) (target, op[0], op[1], op[2]);
1017       else
1018         pat = GEN_FCN (icode) (op[0], op[1], op[2]);
1019       break;
1020     case 4:
1021       if (nonvoid)
1022         pat = GEN_FCN (icode) (target, op[0], op[1], op[2], op[3]);
1023       else
1024         pat = GEN_FCN (icode) (op[0], op[1], op[2], op[3]);
1025       break;
1026     case 5:
1027       if (nonvoid)
1028         pat = GEN_FCN (icode) (target, op[0], op[1], op[2], op[3], op[4]);
1029       else
1030         pat = GEN_FCN (icode) (op[0], op[1], op[2], op[3], op[4]);
1031       break;
1032     case 6:
1033       if (nonvoid)
1034         pat = GEN_FCN (icode) (target, op[0], op[1], op[2], op[3], op[4], op[5]);
1035       else
1036         pat = GEN_FCN (icode) (op[0], op[1], op[2], op[3], op[4], op[5]);
1037       break;
1038     default:
1039       gcc_unreachable ();
1040     }
1041   if (!pat)
1042     return NULL_RTX;
1043   emit_insn (pat);
1044
1045   if (nonvoid)
1046     return target;
1047   else
1048     return const0_rtx;
1049 }
1050
1051
1052 static const int s390_hotpatch_hw_max = 1000000;
1053 static int s390_hotpatch_hw_before_label = 0;
1054 static int s390_hotpatch_hw_after_label = 0;
1055
1056 /* Check whether the hotpatch attribute is applied to a function and, if it has
1057    an argument, the argument is valid.  */
1058
1059 static tree
1060 s390_handle_hotpatch_attribute (tree *node, tree name, tree args,
1061                                 int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
1062 {
1063   tree expr;
1064   tree expr2;
1065   int err;
1066
1067   if (TREE_CODE (*node) != FUNCTION_DECL)
1068     {
1069       warning (OPT_Wattributes, "%qE attribute only applies to functions",
1070                name);
1071       *no_add_attrs = true;
1072     }
1073   if (args != NULL && TREE_CHAIN (args) != NULL)
1074     {
1075       expr = TREE_VALUE (args);
1076       expr2 = TREE_VALUE (TREE_CHAIN (args));
1077     }
1078   if (args == NULL || TREE_CHAIN (args) == NULL)
1079     err = 1;
1080   else if (TREE_CODE (expr) != INTEGER_CST
1081            || !INTEGRAL_TYPE_P (TREE_TYPE (expr))
1082            || wi::gtu_p (expr, s390_hotpatch_hw_max))
1083     err = 1;
1084   else if (TREE_CODE (expr2) != INTEGER_CST
1085            || !INTEGRAL_TYPE_P (TREE_TYPE (expr2))
1086            || wi::gtu_p (expr2, s390_hotpatch_hw_max))
1087     err = 1;
1088   else
1089     err = 0;
1090   if (err)
1091     {
1092       error ("requested %qE attribute is not a comma separated pair of"
1093              " non-negative integer constants or too large (max. %d)", name,
1094              s390_hotpatch_hw_max);
1095       *no_add_attrs = true;
1096     }
1097
1098   return NULL_TREE;
1099 }
1100
1101 /* Expand the s390_vector_bool type attribute.  */
1102
1103 static tree
1104 s390_handle_vectorbool_attribute (tree *node, tree name ATTRIBUTE_UNUSED,
1105                                   tree args ATTRIBUTE_UNUSED,
1106                                   int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
1107 {
1108   tree type = *node, result = NULL_TREE;
1109   machine_mode mode;
1110
1111   while (POINTER_TYPE_P (type)
1112          || TREE_CODE (type) == FUNCTION_TYPE
1113          || TREE_CODE (type) == METHOD_TYPE
1114          || TREE_CODE (type) == ARRAY_TYPE)
1115     type = TREE_TYPE (type);
1116
1117   mode = TYPE_MODE (type);
1118   switch (mode)
1119     {
1120     case DImode: case V2DImode: result = s390_builtin_types[BT_BV2DI]; break;
1121     case SImode: case V4SImode: result = s390_builtin_types[BT_BV4SI]; break;
1122     case HImode: case V8HImode: result = s390_builtin_types[BT_BV8HI]; break;
1123     case QImode: case V16QImode: result = s390_builtin_types[BT_BV16QI];
1124     default: break;
1125     }
1126
1127   *no_add_attrs = true;  /* No need to hang on to the attribute.  */
1128
1129   if (result)
1130     *node = lang_hooks.types.reconstruct_complex_type (*node, result);
1131
1132   return NULL_TREE;
1133 }
1134
1135 static const struct attribute_spec s390_attribute_table[] = {
1136   { "hotpatch", 2, 2, true, false, false, s390_handle_hotpatch_attribute, false },
1137   { "s390_vector_bool", 0, 0, false, true, false, s390_handle_vectorbool_attribute, true },
1138   /* End element.  */
1139   { NULL,        0, 0, false, false, false, NULL, false }
1140 };
1141
1142 /* Return the alignment for LABEL.  We default to the -falign-labels
1143    value except for the literal pool base label.  */
1144 int
1145 s390_label_align (rtx_insn *label)
1146 {
1147   rtx_insn *prev_insn = prev_active_insn (label);
1148   rtx set, src;
1149
1150   if (prev_insn == NULL_RTX)
1151     goto old;
1152
1153   set = single_set (prev_insn);
1154
1155   if (set == NULL_RTX)
1156     goto old;
1157
1158   src = SET_SRC (set);
1159
1160   /* Don't align literal pool base labels.  */
1161   if (GET_CODE (src) == UNSPEC
1162       && XINT (src, 1) == UNSPEC_MAIN_BASE)
1163     return 0;
1164
1165  old:
1166   return align_labels_log;
1167 }
1168
1169 static machine_mode
1170 s390_libgcc_cmp_return_mode (void)
1171 {
1172   return TARGET_64BIT ? DImode : SImode;
1173 }
1174
1175 static machine_mode
1176 s390_libgcc_shift_count_mode (void)
1177 {
1178   return TARGET_64BIT ? DImode : SImode;
1179 }
1180
1181 static machine_mode
1182 s390_unwind_word_mode (void)
1183 {
1184   return TARGET_64BIT ? DImode : SImode;
1185 }
1186
1187 /* Return true if the back end supports mode MODE.  */
1188 static bool
1189 s390_scalar_mode_supported_p (machine_mode mode)
1190 {
1191   /* In contrast to the default implementation reject TImode constants on 31bit
1192      TARGET_ZARCH for ABI compliance.  */
1193   if (!TARGET_64BIT && TARGET_ZARCH && mode == TImode)
1194     return false;
1195
1196   if (DECIMAL_FLOAT_MODE_P (mode))
1197     return default_decimal_float_supported_p ();
1198
1199   return default_scalar_mode_supported_p (mode);
1200 }
1201
1202 /* Return true if the back end supports vector mode MODE.  */
1203 static bool
1204 s390_vector_mode_supported_p (machine_mode mode)
1205 {
1206   machine_mode inner;
1207
1208   if (!VECTOR_MODE_P (mode)
1209       || !TARGET_VX
1210       || GET_MODE_SIZE (mode) > 16)
1211     return false;
1212
1213   inner = GET_MODE_INNER (mode);
1214
1215   switch (inner)
1216     {
1217     case QImode:
1218     case HImode:
1219     case SImode:
1220     case DImode:
1221     case TImode:
1222     case SFmode:
1223     case DFmode:
1224     case TFmode:
1225       return true;
1226     default:
1227       return false;
1228     }
1229 }
1230
1231 /* Set the has_landing_pad_p flag in struct machine_function to VALUE.  */
1232
1233 void
1234 s390_set_has_landing_pad_p (bool value)
1235 {
1236   cfun->machine->has_landing_pad_p = value;
1237 }
1238
1239 /* If two condition code modes are compatible, return a condition code
1240    mode which is compatible with both.  Otherwise, return
1241    VOIDmode.  */
1242
1243 static machine_mode
1244 s390_cc_modes_compatible (machine_mode m1, machine_mode m2)
1245 {
1246   if (m1 == m2)
1247     return m1;
1248
1249   switch (m1)
1250     {
1251     case CCZmode:
1252       if (m2 == CCUmode || m2 == CCTmode || m2 == CCZ1mode
1253           || m2 == CCSmode || m2 == CCSRmode || m2 == CCURmode)
1254         return m2;
1255       return VOIDmode;
1256
1257     case CCSmode:
1258     case CCUmode:
1259     case CCTmode:
1260     case CCSRmode:
1261     case CCURmode:
1262     case CCZ1mode:
1263       if (m2 == CCZmode)
1264         return m1;
1265
1266       return VOIDmode;
1267
1268     default:
1269       return VOIDmode;
1270     }
1271   return VOIDmode;
1272 }
1273
1274 /* Return true if SET either doesn't set the CC register, or else
1275    the source and destination have matching CC modes and that
1276    CC mode is at least as constrained as REQ_MODE.  */
1277
1278 static bool
1279 s390_match_ccmode_set (rtx set, machine_mode req_mode)
1280 {
1281   machine_mode set_mode;
1282
1283   gcc_assert (GET_CODE (set) == SET);
1284
1285   /* These modes are supposed to be used only in CC consumer
1286      patterns.  */
1287   gcc_assert (req_mode != CCVIALLmode && req_mode != CCVIANYmode
1288               && req_mode != CCVFALLmode && req_mode != CCVFANYmode);
1289
1290   if (GET_CODE (SET_DEST (set)) != REG || !CC_REGNO_P (REGNO (SET_DEST (set))))
1291     return 1;
1292
1293   set_mode = GET_MODE (SET_DEST (set));
1294   switch (set_mode)
1295     {
1296     case CCSmode:
1297     case CCSRmode:
1298     case CCUmode:
1299     case CCURmode:
1300     case CCLmode:
1301     case CCL1mode:
1302     case CCL2mode:
1303     case CCL3mode:
1304     case CCT1mode:
1305     case CCT2mode:
1306     case CCT3mode:
1307     case CCVEQmode:
1308     case CCVIHmode:
1309     case CCVIHUmode:
1310     case CCVFHmode:
1311     case CCVFHEmode:
1312       if (req_mode != set_mode)
1313         return 0;
1314       break;
1315
1316     case CCZmode:
1317       if (req_mode != CCSmode && req_mode != CCUmode && req_mode != CCTmode
1318           && req_mode != CCSRmode && req_mode != CCURmode)
1319         return 0;
1320       break;
1321
1322     case CCAPmode:
1323     case CCANmode:
1324       if (req_mode != CCAmode)
1325         return 0;
1326       break;
1327
1328     default:
1329       gcc_unreachable ();
1330     }
1331
1332   return (GET_MODE (SET_SRC (set)) == set_mode);
1333 }
1334
1335 /* Return true if every SET in INSN that sets the CC register
1336    has source and destination with matching CC modes and that
1337    CC mode is at least as constrained as REQ_MODE.
1338    If REQ_MODE is VOIDmode, always return false.  */
1339
1340 bool
1341 s390_match_ccmode (rtx_insn *insn, machine_mode req_mode)
1342 {
1343   int i;
1344
1345   /* s390_tm_ccmode returns VOIDmode to indicate failure.  */
1346   if (req_mode == VOIDmode)
1347     return false;
1348
1349   if (GET_CODE (PATTERN (insn)) == SET)
1350     return s390_match_ccmode_set (PATTERN (insn), req_mode);
1351
1352   if (GET_CODE (PATTERN (insn)) == PARALLEL)
1353       for (i = 0; i < XVECLEN (PATTERN (insn), 0); i++)
1354         {
1355           rtx set = XVECEXP (PATTERN (insn), 0, i);
1356           if (GET_CODE (set) == SET)
1357             if (!s390_match_ccmode_set (set, req_mode))
1358               return false;
1359         }
1360
1361   return true;
1362 }
1363
1364 /* If a test-under-mask instruction can be used to implement
1365    (compare (and ... OP1) OP2), return the CC mode required
1366    to do that.  Otherwise, return VOIDmode.
1367    MIXED is true if the instruction can distinguish between
1368    CC1 and CC2 for mixed selected bits (TMxx), it is false
1369    if the instruction cannot (TM).  */
1370
1371 machine_mode
1372 s390_tm_ccmode (rtx op1, rtx op2, bool mixed)
1373 {
1374   int bit0, bit1;
1375
1376   /* ??? Fixme: should work on CONST_WIDE_INT as well.  */
1377   if (GET_CODE (op1) != CONST_INT || GET_CODE (op2) != CONST_INT)
1378     return VOIDmode;
1379
1380   /* Selected bits all zero: CC0.
1381      e.g.: int a; if ((a & (16 + 128)) == 0) */
1382   if (INTVAL (op2) == 0)
1383     return CCTmode;
1384
1385   /* Selected bits all one: CC3.
1386      e.g.: int a; if ((a & (16 + 128)) == 16 + 128) */
1387   if (INTVAL (op2) == INTVAL (op1))
1388     return CCT3mode;
1389
1390   /* Exactly two bits selected, mixed zeroes and ones: CC1 or CC2. e.g.:
1391      int a;
1392      if ((a & (16 + 128)) == 16)         -> CCT1
1393      if ((a & (16 + 128)) == 128)        -> CCT2  */
1394   if (mixed)
1395     {
1396       bit1 = exact_log2 (INTVAL (op2));
1397       bit0 = exact_log2 (INTVAL (op1) ^ INTVAL (op2));
1398       if (bit0 != -1 && bit1 != -1)
1399         return bit0 > bit1 ? CCT1mode : CCT2mode;
1400     }
1401
1402   return VOIDmode;
1403 }
1404
1405 /* Given a comparison code OP (EQ, NE, etc.) and the operands
1406    OP0 and OP1 of a COMPARE, return the mode to be used for the
1407    comparison.  */
1408
1409 machine_mode
1410 s390_select_ccmode (enum rtx_code code, rtx op0, rtx op1)
1411 {
1412   switch (code)
1413     {
1414       case EQ:
1415       case NE:
1416         if ((GET_CODE (op0) == NEG || GET_CODE (op0) == ABS)
1417             && GET_MODE_CLASS (GET_MODE (op0)) == MODE_INT)
1418           return CCAPmode;
1419         if (GET_CODE (op0) == PLUS && GET_CODE (XEXP (op0, 1)) == CONST_INT
1420             && CONST_OK_FOR_K (INTVAL (XEXP (op0, 1))))
1421           return CCAPmode;
1422         if ((GET_CODE (op0) == PLUS || GET_CODE (op0) == MINUS
1423              || GET_CODE (op1) == NEG)
1424             && GET_MODE_CLASS (GET_MODE (op0)) == MODE_INT)
1425           return CCLmode;
1426
1427         if (GET_CODE (op0) == AND)
1428           {
1429             /* Check whether we can potentially do it via TM.  */
1430             machine_mode ccmode;
1431             ccmode = s390_tm_ccmode (XEXP (op0, 1), op1, 1);
1432             if (ccmode != VOIDmode)
1433               {
1434                 /* Relax CCTmode to CCZmode to allow fall-back to AND
1435                    if that turns out to be beneficial.  */
1436                 return ccmode == CCTmode ? CCZmode : ccmode;
1437               }
1438           }
1439
1440         if (register_operand (op0, HImode)
1441             && GET_CODE (op1) == CONST_INT
1442             && (INTVAL (op1) == -1 || INTVAL (op1) == 65535))
1443           return CCT3mode;
1444         if (register_operand (op0, QImode)
1445             && GET_CODE (op1) == CONST_INT
1446             && (INTVAL (op1) == -1 || INTVAL (op1) == 255))
1447           return CCT3mode;
1448
1449         return CCZmode;
1450
1451       case LE:
1452       case LT:
1453       case GE:
1454       case GT:
1455         /* The only overflow condition of NEG and ABS happens when
1456            -INT_MAX is used as parameter, which stays negative. So
1457            we have an overflow from a positive value to a negative.
1458            Using CCAP mode the resulting cc can be used for comparisons.  */
1459         if ((GET_CODE (op0) == NEG || GET_CODE (op0) == ABS)
1460             && GET_MODE_CLASS (GET_MODE (op0)) == MODE_INT)
1461           return CCAPmode;
1462
1463         /* If constants are involved in an add instruction it is possible to use
1464            the resulting cc for comparisons with zero. Knowing the sign of the
1465            constant the overflow behavior gets predictable. e.g.:
1466              int a, b; if ((b = a + c) > 0)
1467            with c as a constant value: c < 0 -> CCAN and c >= 0 -> CCAP  */
1468         if (GET_CODE (op0) == PLUS && GET_CODE (XEXP (op0, 1)) == CONST_INT
1469             && (CONST_OK_FOR_K (INTVAL (XEXP (op0, 1)))
1470                 || (CONST_OK_FOR_CONSTRAINT_P (INTVAL (XEXP (op0, 1)), 'O', "Os")
1471                     /* Avoid INT32_MIN on 32 bit.  */
1472                     && (!TARGET_ZARCH || INTVAL (XEXP (op0, 1)) != -0x7fffffff - 1))))
1473           {
1474             if (INTVAL (XEXP((op0), 1)) < 0)
1475               return CCANmode;
1476             else
1477               return CCAPmode;
1478           }
1479         /* Fall through.  */
1480       case UNORDERED:
1481       case ORDERED:
1482       case UNEQ:
1483       case UNLE:
1484       case UNLT:
1485       case UNGE:
1486       case UNGT:
1487       case LTGT:
1488         if ((GET_CODE (op0) == SIGN_EXTEND || GET_CODE (op0) == ZERO_EXTEND)
1489             && GET_CODE (op1) != CONST_INT)
1490           return CCSRmode;
1491         return CCSmode;
1492
1493       case LTU:
1494       case GEU:
1495         if (GET_CODE (op0) == PLUS
1496             && GET_MODE_CLASS (GET_MODE (op0)) == MODE_INT)
1497           return CCL1mode;
1498
1499         if ((GET_CODE (op0) == SIGN_EXTEND || GET_CODE (op0) == ZERO_EXTEND)
1500             && GET_CODE (op1) != CONST_INT)
1501           return CCURmode;
1502         return CCUmode;
1503
1504       case LEU:
1505       case GTU:
1506         if (GET_CODE (op0) == MINUS
1507             && GET_MODE_CLASS (GET_MODE (op0)) == MODE_INT)
1508           return CCL2mode;
1509
1510         if ((GET_CODE (op0) == SIGN_EXTEND || GET_CODE (op0) == ZERO_EXTEND)
1511             && GET_CODE (op1) != CONST_INT)
1512           return CCURmode;
1513         return CCUmode;
1514
1515       default:
1516         gcc_unreachable ();
1517     }
1518 }
1519
1520 /* Replace the comparison OP0 CODE OP1 by a semantically equivalent one
1521    that we can implement more efficiently.  */
1522
1523 static void
1524 s390_canonicalize_comparison (int *code, rtx *op0, rtx *op1,
1525                               bool op0_preserve_value)
1526 {
1527   if (op0_preserve_value)
1528     return;
1529
1530   /* Convert ZERO_EXTRACT back to AND to enable TM patterns.  */
1531   if ((*code == EQ || *code == NE)
1532       && *op1 == const0_rtx
1533       && GET_CODE (*op0) == ZERO_EXTRACT
1534       && GET_CODE (XEXP (*op0, 1)) == CONST_INT
1535       && GET_CODE (XEXP (*op0, 2)) == CONST_INT
1536       && SCALAR_INT_MODE_P (GET_MODE (XEXP (*op0, 0))))
1537     {
1538       rtx inner = XEXP (*op0, 0);
1539       HOST_WIDE_INT modesize = GET_MODE_BITSIZE (GET_MODE (inner));
1540       HOST_WIDE_INT len = INTVAL (XEXP (*op0, 1));
1541       HOST_WIDE_INT pos = INTVAL (XEXP (*op0, 2));
1542
1543       if (len > 0 && len < modesize
1544           && pos >= 0 && pos + len <= modesize
1545           && modesize <= HOST_BITS_PER_WIDE_INT)
1546         {
1547           unsigned HOST_WIDE_INT block;
1548           block = (HOST_WIDE_INT_1U << len) - 1;
1549           block <<= modesize - pos - len;
1550
1551           *op0 = gen_rtx_AND (GET_MODE (inner), inner,
1552                               gen_int_mode (block, GET_MODE (inner)));
1553         }
1554     }
1555
1556   /* Narrow AND of memory against immediate to enable TM.  */
1557   if ((*code == EQ || *code == NE)
1558       && *op1 == const0_rtx
1559       && GET_CODE (*op0) == AND
1560       && GET_CODE (XEXP (*op0, 1)) == CONST_INT
1561       && SCALAR_INT_MODE_P (GET_MODE (XEXP (*op0, 0))))
1562     {
1563       rtx inner = XEXP (*op0, 0);
1564       rtx mask = XEXP (*op0, 1);
1565
1566       /* Ignore paradoxical SUBREGs if all extra bits are masked out.  */
1567       if (GET_CODE (inner) == SUBREG
1568           && SCALAR_INT_MODE_P (GET_MODE (SUBREG_REG (inner)))
1569           && (GET_MODE_SIZE (GET_MODE (inner))
1570               >= GET_MODE_SIZE (GET_MODE (SUBREG_REG (inner))))
1571           && ((INTVAL (mask)
1572                & GET_MODE_MASK (GET_MODE (inner))
1573                & ~GET_MODE_MASK (GET_MODE (SUBREG_REG (inner))))
1574               == 0))
1575         inner = SUBREG_REG (inner);
1576
1577       /* Do not change volatile MEMs.  */
1578       if (MEM_P (inner) && !MEM_VOLATILE_P (inner))
1579         {
1580           int part = s390_single_part (XEXP (*op0, 1),
1581                                        GET_MODE (inner), QImode, 0);
1582           if (part >= 0)
1583             {
1584               mask = gen_int_mode (s390_extract_part (mask, QImode, 0), QImode);
1585               inner = adjust_address_nv (inner, QImode, part);
1586               *op0 = gen_rtx_AND (QImode, inner, mask);
1587             }
1588         }
1589     }
1590
1591   /* Narrow comparisons against 0xffff to HImode if possible.  */
1592   if ((*code == EQ || *code == NE)
1593       && GET_CODE (*op1) == CONST_INT
1594       && INTVAL (*op1) == 0xffff
1595       && SCALAR_INT_MODE_P (GET_MODE (*op0))
1596       && (nonzero_bits (*op0, GET_MODE (*op0))
1597           & ~HOST_WIDE_INT_UC (0xffff)) == 0)
1598     {
1599       *op0 = gen_lowpart (HImode, *op0);
1600       *op1 = constm1_rtx;
1601     }
1602
1603   /* Remove redundant UNSPEC_STRCMPCC_TO_INT conversions if possible.  */
1604   if (GET_CODE (*op0) == UNSPEC
1605       && XINT (*op0, 1) == UNSPEC_STRCMPCC_TO_INT
1606       && XVECLEN (*op0, 0) == 1
1607       && GET_MODE (XVECEXP (*op0, 0, 0)) == CCUmode
1608       && GET_CODE (XVECEXP (*op0, 0, 0)) == REG
1609       && REGNO (XVECEXP (*op0, 0, 0)) == CC_REGNUM
1610       && *op1 == const0_rtx)
1611     {
1612       enum rtx_code new_code = UNKNOWN;
1613       switch (*code)
1614         {
1615           case EQ: new_code = EQ;  break;
1616           case NE: new_code = NE;  break;
1617           case LT: new_code = GTU; break;
1618           case GT: new_code = LTU; break;
1619           case LE: new_code = GEU; break;
1620           case GE: new_code = LEU; break;
1621           default: break;
1622         }
1623
1624       if (new_code != UNKNOWN)
1625         {
1626           *op0 = XVECEXP (*op0, 0, 0);
1627           *code = new_code;
1628         }
1629     }
1630
1631   /* Remove redundant UNSPEC_CC_TO_INT conversions if possible.  */
1632   if (GET_CODE (*op0) == UNSPEC
1633       && XINT (*op0, 1) == UNSPEC_CC_TO_INT
1634       && XVECLEN (*op0, 0) == 1
1635       && GET_CODE (XVECEXP (*op0, 0, 0)) == REG
1636       && REGNO (XVECEXP (*op0, 0, 0)) == CC_REGNUM
1637       && CONST_INT_P (*op1))
1638     {
1639       enum rtx_code new_code = UNKNOWN;
1640       switch (GET_MODE (XVECEXP (*op0, 0, 0)))
1641         {
1642         case CCZmode:
1643         case CCRAWmode:
1644           switch (*code)
1645             {
1646             case EQ: new_code = EQ;  break;
1647             case NE: new_code = NE;  break;
1648             default: break;
1649             }
1650           break;
1651         default: break;
1652         }
1653
1654       if (new_code != UNKNOWN)
1655         {
1656           /* For CCRAWmode put the required cc mask into the second
1657              operand.  */
1658         if (GET_MODE (XVECEXP (*op0, 0, 0)) == CCRAWmode
1659             && INTVAL (*op1) >= 0 && INTVAL (*op1) <= 3)
1660             *op1 = gen_rtx_CONST_INT (VOIDmode, 1 << (3 - INTVAL (*op1)));
1661           *op0 = XVECEXP (*op0, 0, 0);
1662           *code = new_code;
1663         }
1664     }
1665
1666   /* Simplify cascaded EQ, NE with const0_rtx.  */
1667   if ((*code == NE || *code == EQ)
1668       && (GET_CODE (*op0) == EQ || GET_CODE (*op0) == NE)
1669       && GET_MODE (*op0) == SImode
1670       && GET_MODE (XEXP (*op0, 0)) == CCZ1mode
1671       && REG_P (XEXP (*op0, 0))
1672       && XEXP (*op0, 1) == const0_rtx
1673       && *op1 == const0_rtx)
1674     {
1675       if ((*code == EQ && GET_CODE (*op0) == NE)
1676           || (*code == NE && GET_CODE (*op0) == EQ))
1677         *code = EQ;
1678       else
1679         *code = NE;
1680       *op0 = XEXP (*op0, 0);
1681     }
1682
1683   /* Prefer register over memory as first operand.  */
1684   if (MEM_P (*op0) && REG_P (*op1))
1685     {
1686       rtx tem = *op0; *op0 = *op1; *op1 = tem;
1687       *code = (int)swap_condition ((enum rtx_code)*code);
1688     }
1689
1690   /* A comparison result is compared against zero.  Replace it with
1691      the (perhaps inverted) original comparison.
1692      This probably should be done by simplify_relational_operation.  */
1693   if ((*code == EQ || *code == NE)
1694       && *op1 == const0_rtx
1695       && COMPARISON_P (*op0)
1696       && CC_REG_P (XEXP (*op0, 0)))
1697     {
1698       enum rtx_code new_code;
1699
1700       if (*code == EQ)
1701         new_code = reversed_comparison_code_parts (GET_CODE (*op0),
1702                                                    XEXP (*op0, 0),
1703                                                    XEXP (*op1, 0), NULL);
1704       else
1705         new_code = GET_CODE (*op0);
1706
1707       if (new_code != UNKNOWN)
1708         {
1709           *code = new_code;
1710           *op1 = XEXP (*op0, 1);
1711           *op0 = XEXP (*op0, 0);
1712         }
1713     }
1714 }
1715
1716
1717 /* Emit a compare instruction suitable to implement the comparison
1718    OP0 CODE OP1.  Return the correct condition RTL to be placed in
1719    the IF_THEN_ELSE of the conditional branch testing the result.  */
1720
1721 rtx
1722 s390_emit_compare (enum rtx_code code, rtx op0, rtx op1)
1723 {
1724   machine_mode mode = s390_select_ccmode (code, op0, op1);
1725   rtx cc;
1726
1727   if (GET_MODE_CLASS (GET_MODE (op0)) == MODE_CC)
1728     {
1729       /* Do not output a redundant compare instruction if a
1730          compare_and_swap pattern already computed the result and the
1731          machine modes are compatible.  */
1732       gcc_assert (s390_cc_modes_compatible (GET_MODE (op0), mode)
1733                   == GET_MODE (op0));
1734       cc = op0;
1735     }
1736   else
1737     {
1738       cc = gen_rtx_REG (mode, CC_REGNUM);
1739       emit_insn (gen_rtx_SET (cc, gen_rtx_COMPARE (mode, op0, op1)));
1740     }
1741
1742   return gen_rtx_fmt_ee (code, VOIDmode, cc, const0_rtx);
1743 }
1744
1745 /* Emit a SImode compare and swap instruction setting MEM to NEW_RTX if OLD
1746    matches CMP.
1747    Return the correct condition RTL to be placed in the IF_THEN_ELSE of the
1748    conditional branch testing the result.  */
1749
1750 static rtx
1751 s390_emit_compare_and_swap (enum rtx_code code, rtx old, rtx mem,
1752                             rtx cmp, rtx new_rtx)
1753 {
1754   emit_insn (gen_atomic_compare_and_swapsi_internal (old, mem, cmp, new_rtx));
1755   return s390_emit_compare (code, gen_rtx_REG (CCZ1mode, CC_REGNUM),
1756                             const0_rtx);
1757 }
1758
1759 /* Emit a jump instruction to TARGET and return it.  If COND is
1760    NULL_RTX, emit an unconditional jump, else a conditional jump under
1761    condition COND.  */
1762
1763 rtx_insn *
1764 s390_emit_jump (rtx target, rtx cond)
1765 {
1766   rtx insn;
1767
1768   target = gen_rtx_LABEL_REF (VOIDmode, target);
1769   if (cond)
1770     target = gen_rtx_IF_THEN_ELSE (VOIDmode, cond, target, pc_rtx);
1771
1772   insn = gen_rtx_SET (pc_rtx, target);
1773   return emit_jump_insn (insn);
1774 }
1775
1776 /* Return branch condition mask to implement a branch
1777    specified by CODE.  Return -1 for invalid comparisons.  */
1778
1779 int
1780 s390_branch_condition_mask (rtx code)
1781 {
1782   const int CC0 = 1 << 3;
1783   const int CC1 = 1 << 2;
1784   const int CC2 = 1 << 1;
1785   const int CC3 = 1 << 0;
1786
1787   gcc_assert (GET_CODE (XEXP (code, 0)) == REG);
1788   gcc_assert (REGNO (XEXP (code, 0)) == CC_REGNUM);
1789   gcc_assert (XEXP (code, 1) == const0_rtx
1790               || (GET_MODE (XEXP (code, 0)) == CCRAWmode
1791                   && CONST_INT_P (XEXP (code, 1))));
1792
1793
1794   switch (GET_MODE (XEXP (code, 0)))
1795     {
1796     case CCZmode:
1797     case CCZ1mode:
1798       switch (GET_CODE (code))
1799         {
1800         case EQ:        return CC0;
1801         case NE:        return CC1 | CC2 | CC3;
1802         default:        return -1;
1803         }
1804       break;
1805
1806     case CCT1mode:
1807       switch (GET_CODE (code))
1808         {
1809         case EQ:        return CC1;
1810         case NE:        return CC0 | CC2 | CC3;
1811         default:        return -1;
1812         }
1813       break;
1814
1815     case CCT2mode:
1816       switch (GET_CODE (code))
1817         {
1818         case EQ:        return CC2;
1819         case NE:        return CC0 | CC1 | CC3;
1820         default:        return -1;
1821         }
1822       break;
1823
1824     case CCT3mode:
1825       switch (GET_CODE (code))
1826         {
1827         case EQ:        return CC3;
1828         case NE:        return CC0 | CC1 | CC2;
1829         default:        return -1;
1830         }
1831       break;
1832
1833     case CCLmode:
1834       switch (GET_CODE (code))
1835         {
1836         case EQ:        return CC0 | CC2;
1837         case NE:        return CC1 | CC3;
1838         default:        return -1;
1839         }
1840       break;
1841
1842     case CCL1mode:
1843       switch (GET_CODE (code))
1844         {
1845         case LTU:       return CC2 | CC3;  /* carry */
1846         case GEU:       return CC0 | CC1;  /* no carry */
1847         default:        return -1;
1848         }
1849       break;
1850
1851     case CCL2mode:
1852       switch (GET_CODE (code))
1853         {
1854         case GTU:       return CC0 | CC1;  /* borrow */
1855         case LEU:       return CC2 | CC3;  /* no borrow */
1856         default:        return -1;
1857         }
1858       break;
1859
1860     case CCL3mode:
1861       switch (GET_CODE (code))
1862         {
1863         case EQ:        return CC0 | CC2;
1864         case NE:        return CC1 | CC3;
1865         case LTU:       return CC1;
1866         case GTU:       return CC3;
1867         case LEU:       return CC1 | CC2;
1868         case GEU:       return CC2 | CC3;
1869         default:        return -1;
1870         }
1871
1872     case CCUmode:
1873       switch (GET_CODE (code))
1874         {
1875         case EQ:        return CC0;
1876         case NE:        return CC1 | CC2 | CC3;
1877         case LTU:       return CC1;
1878         case GTU:       return CC2;
1879         case LEU:       return CC0 | CC1;
1880         case GEU:       return CC0 | CC2;
1881         default:        return -1;
1882         }
1883       break;
1884
1885     case CCURmode:
1886       switch (GET_CODE (code))
1887         {
1888         case EQ:        return CC0;
1889         case NE:        return CC2 | CC1 | CC3;
1890         case LTU:       return CC2;
1891         case GTU:       return CC1;
1892         case LEU:       return CC0 | CC2;
1893         case GEU:       return CC0 | CC1;
1894         default:        return -1;
1895         }
1896       break;
1897
1898     case CCAPmode:
1899       switch (GET_CODE (code))
1900         {
1901         case EQ:        return CC0;
1902         case NE:        return CC1 | CC2 | CC3;
1903         case LT:        return CC1 | CC3;
1904         case GT:        return CC2;
1905         case LE:        return CC0 | CC1 | CC3;
1906         case GE:        return CC0 | CC2;
1907         default:        return -1;
1908         }
1909       break;
1910
1911     case CCANmode:
1912       switch (GET_CODE (code))
1913         {
1914         case EQ:        return CC0;
1915         case NE:        return CC1 | CC2 | CC3;
1916         case LT:        return CC1;
1917         case GT:        return CC2 | CC3;
1918         case LE:        return CC0 | CC1;
1919         case GE:        return CC0 | CC2 | CC3;
1920         default:        return -1;
1921         }
1922       break;
1923
1924     case CCSmode:
1925       switch (GET_CODE (code))
1926         {
1927         case EQ:        return CC0;
1928         case NE:        return CC1 | CC2 | CC3;
1929         case LT:        return CC1;
1930         case GT:        return CC2;
1931         case LE:        return CC0 | CC1;
1932         case GE:        return CC0 | CC2;
1933         case UNORDERED: return CC3;
1934         case ORDERED:   return CC0 | CC1 | CC2;
1935         case UNEQ:      return CC0 | CC3;
1936         case UNLT:      return CC1 | CC3;
1937         case UNGT:      return CC2 | CC3;
1938         case UNLE:      return CC0 | CC1 | CC3;
1939         case UNGE:      return CC0 | CC2 | CC3;
1940         case LTGT:      return CC1 | CC2;
1941         default:        return -1;
1942         }
1943       break;
1944
1945     case CCSRmode:
1946       switch (GET_CODE (code))
1947         {
1948         case EQ:        return CC0;
1949         case NE:        return CC2 | CC1 | CC3;
1950         case LT:        return CC2;
1951         case GT:        return CC1;
1952         case LE:        return CC0 | CC2;
1953         case GE:        return CC0 | CC1;
1954         case UNORDERED: return CC3;
1955         case ORDERED:   return CC0 | CC2 | CC1;
1956         case UNEQ:      return CC0 | CC3;
1957         case UNLT:      return CC2 | CC3;
1958         case UNGT:      return CC1 | CC3;
1959         case UNLE:      return CC0 | CC2 | CC3;
1960         case UNGE:      return CC0 | CC1 | CC3;
1961         case LTGT:      return CC2 | CC1;
1962         default:        return -1;
1963         }
1964       break;
1965
1966       /* Vector comparison modes.  */
1967       /* CC2 will never be set.  It however is part of the negated
1968          masks.  */
1969     case CCVIALLmode:
1970       switch (GET_CODE (code))
1971         {
1972         case EQ:
1973         case GTU:
1974         case GT:
1975         case GE:        return CC0;
1976           /* The inverted modes are in fact *any* modes.  */
1977         case NE:
1978         case LEU:
1979         case LE:
1980         case LT:        return CC3 | CC1 | CC2;
1981         default:        return -1;
1982         }
1983
1984     case CCVIANYmode:
1985       switch (GET_CODE (code))
1986         {
1987         case EQ:
1988         case GTU:
1989         case GT:
1990         case GE:        return CC0 | CC1;
1991           /* The inverted modes are in fact *all* modes.  */
1992         case NE:
1993         case LEU:
1994         case LE:
1995         case LT:        return CC3 | CC2;
1996         default:        return -1;
1997         }
1998     case CCVFALLmode:
1999       switch (GET_CODE (code))
2000         {
2001         case EQ:
2002         case GT:
2003         case GE:        return CC0;
2004           /* The inverted modes are in fact *any* modes.  */
2005         case NE:
2006         case UNLE:
2007         case UNLT:      return CC3 | CC1 | CC2;
2008         default:        return -1;
2009         }
2010
2011     case CCVFANYmode:
2012       switch (GET_CODE (code))
2013         {
2014         case EQ:
2015         case GT:
2016         case GE:        return CC0 | CC1;
2017           /* The inverted modes are in fact *all* modes.  */
2018         case NE:
2019         case UNLE:
2020         case UNLT:      return CC3 | CC2;
2021         default:        return -1;
2022         }
2023
2024     case CCRAWmode:
2025       switch (GET_CODE (code))
2026         {
2027         case EQ:
2028           return INTVAL (XEXP (code, 1));
2029         case NE:
2030           return (INTVAL (XEXP (code, 1))) ^ 0xf;
2031         default:
2032           gcc_unreachable ();
2033         }
2034
2035     default:
2036       return -1;
2037     }
2038 }
2039
2040
2041 /* Return branch condition mask to implement a compare and branch
2042    specified by CODE.  Return -1 for invalid comparisons.  */
2043
2044 int
2045 s390_compare_and_branch_condition_mask (rtx code)
2046 {
2047   const int CC0 = 1 << 3;
2048   const int CC1 = 1 << 2;
2049   const int CC2 = 1 << 1;
2050
2051   switch (GET_CODE (code))
2052     {
2053     case EQ:
2054       return CC0;
2055     case NE:
2056       return CC1 | CC2;
2057     case LT:
2058     case LTU:
2059       return CC1;
2060     case GT:
2061     case GTU:
2062       return CC2;
2063     case LE:
2064     case LEU:
2065       return CC0 | CC1;
2066     case GE:
2067     case GEU:
2068       return CC0 | CC2;
2069     default:
2070       gcc_unreachable ();
2071     }
2072   return -1;
2073 }
2074
2075 /* If INV is false, return assembler mnemonic string to implement
2076    a branch specified by CODE.  If INV is true, return mnemonic
2077    for the corresponding inverted branch.  */
2078
2079 static const char *
2080 s390_branch_condition_mnemonic (rtx code, int inv)
2081 {
2082   int mask;
2083
2084   static const char *const mnemonic[16] =
2085     {
2086       NULL, "o", "h", "nle",
2087       "l", "nhe", "lh", "ne",
2088       "e", "nlh", "he", "nl",
2089       "le", "nh", "no", NULL
2090     };
2091
2092   if (GET_CODE (XEXP (code, 0)) == REG
2093       && REGNO (XEXP (code, 0)) == CC_REGNUM
2094       && (XEXP (code, 1) == const0_rtx
2095           || (GET_MODE (XEXP (code, 0)) == CCRAWmode
2096               && CONST_INT_P (XEXP (code, 1)))))
2097     mask = s390_branch_condition_mask (code);
2098   else
2099     mask = s390_compare_and_branch_condition_mask (code);
2100
2101   gcc_assert (mask >= 0);
2102
2103   if (inv)
2104     mask ^= 15;
2105
2106   gcc_assert (mask >= 1 && mask <= 14);
2107
2108   return mnemonic[mask];
2109 }
2110
2111 /* Return the part of op which has a value different from def.
2112    The size of the part is determined by mode.
2113    Use this function only if you already know that op really
2114    contains such a part.  */
2115
2116 unsigned HOST_WIDE_INT
2117 s390_extract_part (rtx op, machine_mode mode, int def)
2118 {
2119   unsigned HOST_WIDE_INT value = 0;
2120   int max_parts = HOST_BITS_PER_WIDE_INT / GET_MODE_BITSIZE (mode);
2121   int part_bits = GET_MODE_BITSIZE (mode);
2122   unsigned HOST_WIDE_INT part_mask = (HOST_WIDE_INT_1U << part_bits) - 1;
2123   int i;
2124
2125   for (i = 0; i < max_parts; i++)
2126     {
2127       if (i == 0)
2128         value = UINTVAL (op);
2129       else
2130         value >>= part_bits;
2131
2132       if ((value & part_mask) != (def & part_mask))
2133         return value & part_mask;
2134     }
2135
2136   gcc_unreachable ();
2137 }
2138
2139 /* If OP is an integer constant of mode MODE with exactly one
2140    part of mode PART_MODE unequal to DEF, return the number of that
2141    part. Otherwise, return -1.  */
2142
2143 int
2144 s390_single_part (rtx op,
2145                   machine_mode mode,
2146                   machine_mode part_mode,
2147                   int def)
2148 {
2149   unsigned HOST_WIDE_INT value = 0;
2150   int n_parts = GET_MODE_SIZE (mode) / GET_MODE_SIZE (part_mode);
2151   unsigned HOST_WIDE_INT part_mask
2152     = (HOST_WIDE_INT_1U << GET_MODE_BITSIZE (part_mode)) - 1;
2153   int i, part = -1;
2154
2155   if (GET_CODE (op) != CONST_INT)
2156     return -1;
2157
2158   for (i = 0; i < n_parts; i++)
2159     {
2160       if (i == 0)
2161         value = UINTVAL (op);
2162       else
2163         value >>= GET_MODE_BITSIZE (part_mode);
2164
2165       if ((value & part_mask) != (def & part_mask))
2166         {
2167           if (part != -1)
2168             return -1;
2169           else
2170             part = i;
2171         }
2172     }
2173   return part == -1 ? -1 : n_parts - 1 - part;
2174 }
2175
2176 /* Return true if IN contains a contiguous bitfield in the lower SIZE
2177    bits and no other bits are set in (the lower SIZE bits of) IN.
2178
2179    PSTART and PEND can be used to obtain the start and end
2180    position (inclusive) of the bitfield relative to 64
2181    bits. *PSTART / *PEND gives the position of the first/last bit
2182    of the bitfield counting from the highest order bit starting
2183    with zero.  */
2184
2185 bool
2186 s390_contiguous_bitmask_nowrap_p (unsigned HOST_WIDE_INT in, int size,
2187                                   int *pstart, int *pend)
2188 {
2189   int start;
2190   int end = -1;
2191   int lowbit = HOST_BITS_PER_WIDE_INT - 1;
2192   int highbit = HOST_BITS_PER_WIDE_INT - size;
2193   unsigned HOST_WIDE_INT bitmask = HOST_WIDE_INT_1U;
2194
2195   gcc_assert (!!pstart == !!pend);
2196   for (start = lowbit; start >= highbit; bitmask <<= 1, start--)
2197     if (end == -1)
2198       {
2199         /* Look for the rightmost bit of a contiguous range of ones.  */
2200         if (bitmask & in)
2201           /* Found it.  */
2202           end = start;
2203       }
2204     else
2205       {
2206         /* Look for the firt zero bit after the range of ones.  */
2207         if (! (bitmask & in))
2208           /* Found it.  */
2209           break;
2210       }
2211   /* We're one past the last one-bit.  */
2212   start++;
2213
2214   if (end == -1)
2215     /* No one bits found.  */
2216     return false;
2217
2218   if (start > highbit)
2219     {
2220       unsigned HOST_WIDE_INT mask;
2221
2222       /* Calculate a mask for all bits beyond the contiguous bits.  */
2223       mask = ((~HOST_WIDE_INT_0U >> highbit)
2224               & (~HOST_WIDE_INT_0U << (lowbit - start + 1)));
2225       if (mask & in)
2226         /* There are more bits set beyond the first range of one bits.  */
2227         return false;
2228     }
2229
2230   if (pstart)
2231     {
2232       *pstart = start;
2233       *pend = end;
2234     }
2235
2236   return true;
2237 }
2238
2239 /* Same as s390_contiguous_bitmask_nowrap_p but also returns true
2240    if ~IN contains a contiguous bitfield.  In that case, *END is <
2241    *START.
2242
2243    If WRAP_P is true, a bitmask that wraps around is also tested.
2244    When a wraparoud occurs *START is greater than *END (in
2245    non-null pointers), and the uppermost (64 - SIZE) bits are thus
2246    part of the range.  If WRAP_P is false, no wraparound is
2247    tested.  */
2248
2249 bool
2250 s390_contiguous_bitmask_p (unsigned HOST_WIDE_INT in, bool wrap_p,
2251                            int size, int *start, int *end)
2252 {
2253   int bs = HOST_BITS_PER_WIDE_INT;
2254   bool b;
2255
2256   gcc_assert (!!start == !!end);
2257   if ((in & ((~HOST_WIDE_INT_0U) >> (bs - size))) == 0)
2258     /* This cannot be expressed as a contiguous bitmask.  Exit early because
2259        the second call of s390_contiguous_bitmask_nowrap_p would accept this as
2260        a valid bitmask.  */
2261     return false;
2262   b = s390_contiguous_bitmask_nowrap_p (in, size, start, end);
2263   if (b)
2264     return true;
2265   if (! wrap_p)
2266     return false;
2267   b = s390_contiguous_bitmask_nowrap_p (~in, size, start, end);
2268   if (b && start)
2269     {
2270       int s = *start;
2271       int e = *end;
2272
2273       gcc_assert (s >= 1);
2274       *start = ((e + 1) & (bs - 1));
2275       *end = ((s - 1 + bs) & (bs - 1));
2276     }
2277
2278   return b;
2279 }
2280
2281 /* Return true if OP contains the same contiguous bitfield in *all*
2282    its elements.  START and END can be used to obtain the start and
2283    end position of the bitfield.
2284
2285    START/STOP give the position of the first/last bit of the bitfield
2286    counting from the lowest order bit starting with zero.  In order to
2287    use these values for S/390 instructions this has to be converted to
2288    "bits big endian" style.  */
2289
2290 bool
2291 s390_contiguous_bitmask_vector_p (rtx op, int *start, int *end)
2292 {
2293   unsigned HOST_WIDE_INT mask;
2294   int size;
2295   rtx elt;
2296   bool b;
2297
2298   gcc_assert (!!start == !!end);
2299   if (!const_vec_duplicate_p (op, &elt)
2300       || !CONST_INT_P (elt))
2301     return false;
2302
2303   size = GET_MODE_UNIT_BITSIZE (GET_MODE (op));
2304
2305   /* We cannot deal with V1TI/V1TF. This would require a vgmq.  */
2306   if (size > 64)
2307     return false;
2308
2309   mask = UINTVAL (elt);
2310
2311   b = s390_contiguous_bitmask_p (mask, true, size, start, end);
2312   if (b)
2313     {
2314       if (start)
2315         {
2316           *start -= (HOST_BITS_PER_WIDE_INT - size);
2317           *end -= (HOST_BITS_PER_WIDE_INT - size);
2318         }
2319       return true;
2320     }
2321   else
2322     return false;
2323 }
2324
2325 /* Return true if C consists only of byte chunks being either 0 or
2326    0xff.  If MASK is !=NULL a byte mask is generated which is
2327    appropriate for the vector generate byte mask instruction.  */
2328
2329 bool
2330 s390_bytemask_vector_p (rtx op, unsigned *mask)
2331 {
2332   int i;
2333   unsigned tmp_mask = 0;
2334   int nunit, unit_size;
2335
2336   if (!VECTOR_MODE_P (GET_MODE (op))
2337       || GET_CODE (op) != CONST_VECTOR
2338       || !CONST_INT_P (XVECEXP (op, 0, 0)))
2339     return false;
2340
2341   nunit = GET_MODE_NUNITS (GET_MODE (op));
2342   unit_size = GET_MODE_UNIT_SIZE (GET_MODE (op));
2343
2344   for (i = 0; i < nunit; i++)
2345     {
2346       unsigned HOST_WIDE_INT c;
2347       int j;
2348
2349       if (!CONST_INT_P (XVECEXP (op, 0, i)))
2350         return false;
2351
2352       c = UINTVAL (XVECEXP (op, 0, i));
2353       for (j = 0; j < unit_size; j++)
2354         {
2355           if ((c & 0xff) != 0 && (c & 0xff) != 0xff)
2356             return false;
2357           tmp_mask |= (c & 1) << ((nunit - 1 - i) * unit_size + j);
2358           c = c >> BITS_PER_UNIT;
2359         }
2360     }
2361
2362   if (mask != NULL)
2363     *mask = tmp_mask;
2364
2365   return true;
2366 }
2367
2368 /* Check whether a rotate of ROTL followed by an AND of CONTIG is
2369    equivalent to a shift followed by the AND.  In particular, CONTIG
2370    should not overlap the (rotated) bit 0/bit 63 gap.  Negative values
2371    for ROTL indicate a rotate to the right.  */
2372
2373 bool
2374 s390_extzv_shift_ok (int bitsize, int rotl, unsigned HOST_WIDE_INT contig)
2375 {
2376   int start, end;
2377   bool ok;
2378
2379   ok = s390_contiguous_bitmask_nowrap_p (contig, bitsize, &start, &end);
2380   gcc_assert (ok);
2381
2382   if (rotl >= 0)
2383     return (64 - end >= rotl);
2384   else
2385     {
2386       /* Translate "- rotate right" in BITSIZE mode to "rotate left" in
2387          DIMode.  */
2388       rotl = -rotl + (64 - bitsize);
2389       return (start >= rotl);
2390     }
2391 }
2392
2393 /* Check whether we can (and want to) split a double-word
2394    move in mode MODE from SRC to DST into two single-word
2395    moves, moving the subword FIRST_SUBWORD first.  */
2396
2397 bool
2398 s390_split_ok_p (rtx dst, rtx src, machine_mode mode, int first_subword)
2399 {
2400   /* Floating point and vector registers cannot be split.  */
2401   if (FP_REG_P (src) || FP_REG_P (dst) || VECTOR_REG_P (src) || VECTOR_REG_P (dst))
2402     return false;
2403
2404   /* Non-offsettable memory references cannot be split.  */
2405   if ((GET_CODE (src) == MEM && !offsettable_memref_p (src))
2406       || (GET_CODE (dst) == MEM && !offsettable_memref_p (dst)))
2407     return false;
2408
2409   /* Moving the first subword must not clobber a register
2410      needed to move the second subword.  */
2411   if (register_operand (dst, mode))
2412     {
2413       rtx subreg = operand_subword (dst, first_subword, 0, mode);
2414       if (reg_overlap_mentioned_p (subreg, src))
2415         return false;
2416     }
2417
2418   return true;
2419 }
2420
2421 /* Return true if it can be proven that [MEM1, MEM1 + SIZE]
2422    and [MEM2, MEM2 + SIZE] do overlap and false
2423    otherwise.  */
2424
2425 bool
2426 s390_overlap_p (rtx mem1, rtx mem2, HOST_WIDE_INT size)
2427 {
2428   rtx addr1, addr2, addr_delta;
2429   HOST_WIDE_INT delta;
2430
2431   if (GET_CODE (mem1) != MEM || GET_CODE (mem2) != MEM)
2432     return true;
2433
2434   if (size == 0)
2435     return false;
2436
2437   addr1 = XEXP (mem1, 0);
2438   addr2 = XEXP (mem2, 0);
2439
2440   addr_delta = simplify_binary_operation (MINUS, Pmode, addr2, addr1);
2441
2442   /* This overlapping check is used by peepholes merging memory block operations.
2443      Overlapping operations would otherwise be recognized by the S/390 hardware
2444      and would fall back to a slower implementation. Allowing overlapping
2445      operations would lead to slow code but not to wrong code. Therefore we are
2446      somewhat optimistic if we cannot prove that the memory blocks are
2447      overlapping.
2448      That's why we return false here although this may accept operations on
2449      overlapping memory areas.  */
2450   if (!addr_delta || GET_CODE (addr_delta) != CONST_INT)
2451     return false;
2452
2453   delta = INTVAL (addr_delta);
2454
2455   if (delta == 0
2456       || (delta > 0 && delta < size)
2457       || (delta < 0 && -delta < size))
2458     return true;
2459
2460   return false;
2461 }
2462
2463 /* Check whether the address of memory reference MEM2 equals exactly
2464    the address of memory reference MEM1 plus DELTA.  Return true if
2465    we can prove this to be the case, false otherwise.  */
2466
2467 bool
2468 s390_offset_p (rtx mem1, rtx mem2, rtx delta)
2469 {
2470   rtx addr1, addr2, addr_delta;
2471
2472   if (GET_CODE (mem1) != MEM || GET_CODE (mem2) != MEM)
2473     return false;
2474
2475   addr1 = XEXP (mem1, 0);
2476   addr2 = XEXP (mem2, 0);
2477
2478   addr_delta = simplify_binary_operation (MINUS, Pmode, addr2, addr1);
2479   if (!addr_delta || !rtx_equal_p (addr_delta, delta))
2480     return false;
2481
2482   return true;
2483 }
2484
2485 /* Expand logical operator CODE in mode MODE with operands OPERANDS.  */
2486
2487 void
2488 s390_expand_logical_operator (enum rtx_code code, machine_mode mode,
2489                               rtx *operands)
2490 {
2491   machine_mode wmode = mode;
2492   rtx dst = operands[0];
2493   rtx src1 = operands[1];
2494   rtx src2 = operands[2];
2495   rtx op, clob, tem;
2496
2497   /* If we cannot handle the operation directly, use a temp register.  */
2498   if (!s390_logical_operator_ok_p (operands))
2499     dst = gen_reg_rtx (mode);
2500
2501   /* QImode and HImode patterns make sense only if we have a destination
2502      in memory.  Otherwise perform the operation in SImode.  */
2503   if ((mode == QImode || mode == HImode) && GET_CODE (dst) != MEM)
2504     wmode = SImode;
2505
2506   /* Widen operands if required.  */
2507   if (mode != wmode)
2508     {
2509       if (GET_CODE (dst) == SUBREG
2510           && (tem = simplify_subreg (wmode, dst, mode, 0)) != 0)
2511         dst = tem;
2512       else if (REG_P (dst))
2513         dst = gen_rtx_SUBREG (wmode, dst, 0);
2514       else
2515         dst = gen_reg_rtx (wmode);
2516
2517       if (GET_CODE (src1) == SUBREG
2518           && (tem = simplify_subreg (wmode, src1, mode, 0)) != 0)
2519         src1 = tem;
2520       else if (GET_MODE (src1) != VOIDmode)
2521         src1 = gen_rtx_SUBREG (wmode, force_reg (mode, src1), 0);
2522
2523       if (GET_CODE (src2) == SUBREG
2524           && (tem = simplify_subreg (wmode, src2, mode, 0)) != 0)
2525         src2 = tem;
2526       else if (GET_MODE (src2) != VOIDmode)
2527         src2 = gen_rtx_SUBREG (wmode, force_reg (mode, src2), 0);
2528     }
2529
2530   /* Emit the instruction.  */
2531   op = gen_rtx_SET (dst, gen_rtx_fmt_ee (code, wmode, src1, src2));
2532   clob = gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (CCmode, CC_REGNUM));
2533   emit_insn (gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, op, clob)));
2534
2535   /* Fix up the destination if needed.  */
2536   if (dst != operands[0])
2537     emit_move_insn (operands[0], gen_lowpart (mode, dst));
2538 }
2539
2540 /* Check whether OPERANDS are OK for a logical operation (AND, IOR, XOR).  */
2541
2542 bool
2543 s390_logical_operator_ok_p (rtx *operands)
2544 {
2545   /* If the destination operand is in memory, it needs to coincide
2546      with one of the source operands.  After reload, it has to be
2547      the first source operand.  */
2548   if (GET_CODE (operands[0]) == MEM)
2549     return rtx_equal_p (operands[0], operands[1])
2550            || (!reload_completed && rtx_equal_p (operands[0], operands[2]));
2551
2552   return true;
2553 }
2554
2555 /* Narrow logical operation CODE of memory operand MEMOP with immediate
2556    operand IMMOP to switch from SS to SI type instructions.  */
2557
2558 void
2559 s390_narrow_logical_operator (enum rtx_code code, rtx *memop, rtx *immop)
2560 {
2561   int def = code == AND ? -1 : 0;
2562   HOST_WIDE_INT mask;
2563   int part;
2564
2565   gcc_assert (GET_CODE (*memop) == MEM);
2566   gcc_assert (!MEM_VOLATILE_P (*memop));
2567
2568   mask = s390_extract_part (*immop, QImode, def);
2569   part = s390_single_part (*immop, GET_MODE (*memop), QImode, def);
2570   gcc_assert (part >= 0);
2571
2572   *memop = adjust_address (*memop, QImode, part);
2573   *immop = gen_int_mode (mask, QImode);
2574 }
2575
2576
2577 /* How to allocate a 'struct machine_function'.  */
2578
2579 static struct machine_function *
2580 s390_init_machine_status (void)
2581 {
2582   return ggc_cleared_alloc<machine_function> ();
2583 }
2584
2585 /* Map for smallest class containing reg regno.  */
2586
2587 const enum reg_class regclass_map[FIRST_PSEUDO_REGISTER] =
2588 { GENERAL_REGS, ADDR_REGS, ADDR_REGS, ADDR_REGS,  /*  0 */
2589   ADDR_REGS,    ADDR_REGS, ADDR_REGS, ADDR_REGS,  /*  4 */
2590   ADDR_REGS,    ADDR_REGS, ADDR_REGS, ADDR_REGS,  /*  8 */
2591   ADDR_REGS,    ADDR_REGS, ADDR_REGS, ADDR_REGS,  /* 12 */
2592   FP_REGS,      FP_REGS,   FP_REGS,   FP_REGS,    /* 16 */
2593   FP_REGS,      FP_REGS,   FP_REGS,   FP_REGS,    /* 20 */
2594   FP_REGS,      FP_REGS,   FP_REGS,   FP_REGS,    /* 24 */
2595   FP_REGS,      FP_REGS,   FP_REGS,   FP_REGS,    /* 28 */
2596   ADDR_REGS,    CC_REGS,   ADDR_REGS, ADDR_REGS,  /* 32 */
2597   ACCESS_REGS,  ACCESS_REGS, VEC_REGS, VEC_REGS,  /* 36 */
2598   VEC_REGS, VEC_REGS, VEC_REGS, VEC_REGS,         /* 40 */
2599   VEC_REGS, VEC_REGS, VEC_REGS, VEC_REGS,         /* 44 */
2600   VEC_REGS, VEC_REGS, VEC_REGS, VEC_REGS,         /* 48 */
2601   VEC_REGS, VEC_REGS                              /* 52 */
2602 };
2603
2604 /* Return attribute type of insn.  */
2605
2606 static enum attr_type
2607 s390_safe_attr_type (rtx_insn *insn)
2608 {
2609   if (recog_memoized (insn) >= 0)
2610     return get_attr_type (insn);
2611   else
2612     return TYPE_NONE;
2613 }
2614
2615 /* Return true if DISP is a valid short displacement.  */
2616
2617 static bool
2618 s390_short_displacement (rtx disp)
2619 {
2620   /* No displacement is OK.  */
2621   if (!disp)
2622     return true;
2623
2624   /* Without the long displacement facility we don't need to
2625      distingiush between long and short displacement.  */
2626   if (!TARGET_LONG_DISPLACEMENT)
2627     return true;
2628
2629   /* Integer displacement in range.  */
2630   if (GET_CODE (disp) == CONST_INT)
2631     return INTVAL (disp) >= 0 && INTVAL (disp) < 4096;
2632
2633   /* GOT offset is not OK, the GOT can be large.  */
2634   if (GET_CODE (disp) == CONST
2635       && GET_CODE (XEXP (disp, 0)) == UNSPEC
2636       && (XINT (XEXP (disp, 0), 1) == UNSPEC_GOT
2637           || XINT (XEXP (disp, 0), 1) == UNSPEC_GOTNTPOFF))
2638     return false;
2639
2640   /* All other symbolic constants are literal pool references,
2641      which are OK as the literal pool must be small.  */
2642   if (GET_CODE (disp) == CONST)
2643     return true;
2644
2645   return false;
2646 }
2647
2648 /* Decompose a RTL expression ADDR for a memory address into
2649    its components, returned in OUT.
2650
2651    Returns false if ADDR is not a valid memory address, true
2652    otherwise.  If OUT is NULL, don't return the components,
2653    but check for validity only.
2654
2655    Note: Only addresses in canonical form are recognized.
2656    LEGITIMIZE_ADDRESS should convert non-canonical forms to the
2657    canonical form so that they will be recognized.  */
2658
2659 static int
2660 s390_decompose_address (rtx addr, struct s390_address *out)
2661 {
2662   HOST_WIDE_INT offset = 0;
2663   rtx base = NULL_RTX;
2664   rtx indx = NULL_RTX;
2665   rtx disp = NULL_RTX;
2666   rtx orig_disp;
2667   bool pointer = false;
2668   bool base_ptr = false;
2669   bool indx_ptr = false;
2670   bool literal_pool = false;
2671
2672   /* We may need to substitute the literal pool base register into the address
2673      below.  However, at this point we do not know which register is going to
2674      be used as base, so we substitute the arg pointer register.  This is going
2675      to be treated as holding a pointer below -- it shouldn't be used for any
2676      other purpose.  */
2677   rtx fake_pool_base = gen_rtx_REG (Pmode, ARG_POINTER_REGNUM);
2678
2679   /* Decompose address into base + index + displacement.  */
2680
2681   if (GET_CODE (addr) == REG || GET_CODE (addr) == UNSPEC)
2682     base = addr;
2683
2684   else if (GET_CODE (addr) == PLUS)
2685     {
2686       rtx op0 = XEXP (addr, 0);
2687       rtx op1 = XEXP (addr, 1);
2688       enum rtx_code code0 = GET_CODE (op0);
2689       enum rtx_code code1 = GET_CODE (op1);
2690
2691       if (code0 == REG || code0 == UNSPEC)
2692         {
2693           if (code1 == REG || code1 == UNSPEC)
2694             {
2695               indx = op0;       /* index + base */
2696               base = op1;
2697             }
2698
2699           else
2700             {
2701               base = op0;       /* base + displacement */
2702               disp = op1;
2703             }
2704         }
2705
2706       else if (code0 == PLUS)
2707         {
2708           indx = XEXP (op0, 0); /* index + base + disp */
2709           base = XEXP (op0, 1);
2710           disp = op1;
2711         }
2712
2713       else
2714         {
2715           return false;
2716         }
2717     }
2718
2719   else
2720     disp = addr;                /* displacement */
2721
2722   /* Extract integer part of displacement.  */
2723   orig_disp = disp;
2724   if (disp)
2725     {
2726       if (GET_CODE (disp) == CONST_INT)
2727         {
2728           offset = INTVAL (disp);
2729           disp = NULL_RTX;
2730         }
2731       else if (GET_CODE (disp) == CONST
2732                && GET_CODE (XEXP (disp, 0)) == PLUS
2733                && GET_CODE (XEXP (XEXP (disp, 0), 1)) == CONST_INT)
2734         {
2735           offset = INTVAL (XEXP (XEXP (disp, 0), 1));
2736           disp = XEXP (XEXP (disp, 0), 0);
2737         }
2738     }
2739
2740   /* Strip off CONST here to avoid special case tests later.  */
2741   if (disp && GET_CODE (disp) == CONST)
2742     disp = XEXP (disp, 0);
2743
2744   /* We can convert literal pool addresses to
2745      displacements by basing them off the base register.  */
2746   if (disp && GET_CODE (disp) == SYMBOL_REF && CONSTANT_POOL_ADDRESS_P (disp))
2747     {
2748       if (base || indx)
2749         return false;
2750
2751       base = fake_pool_base, literal_pool = true;
2752
2753       /* Mark up the displacement.  */
2754       disp = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, disp),
2755                              UNSPEC_LTREL_OFFSET);
2756     }
2757
2758   /* Validate base register.  */
2759   if (base)
2760     {
2761       if (GET_CODE (base) == UNSPEC)
2762         switch (XINT (base, 1))
2763           {
2764           case UNSPEC_LTREF:
2765             if (!disp)
2766               disp = gen_rtx_UNSPEC (Pmode,
2767                                      gen_rtvec (1, XVECEXP (base, 0, 0)),
2768                                      UNSPEC_LTREL_OFFSET);
2769             else
2770               return false;
2771
2772             base = XVECEXP (base, 0, 1);
2773             break;
2774
2775           case UNSPEC_LTREL_BASE:
2776             if (XVECLEN (base, 0) == 1)
2777               base = fake_pool_base, literal_pool = true;
2778             else
2779               base = XVECEXP (base, 0, 1);
2780             break;
2781
2782           default:
2783             return false;
2784           }
2785
2786       if (!REG_P (base) || GET_MODE (base) != Pmode)
2787         return false;
2788
2789       if (REGNO (base) == STACK_POINTER_REGNUM
2790           || REGNO (base) == FRAME_POINTER_REGNUM
2791           || ((reload_completed || reload_in_progress)
2792               && frame_pointer_needed
2793               && REGNO (base) == HARD_FRAME_POINTER_REGNUM)
2794           || REGNO (base) == ARG_POINTER_REGNUM
2795           || (flag_pic
2796               && REGNO (base) == PIC_OFFSET_TABLE_REGNUM))
2797         pointer = base_ptr = true;
2798
2799       if ((reload_completed || reload_in_progress)
2800           && base == cfun->machine->base_reg)
2801         pointer = base_ptr = literal_pool = true;
2802     }
2803
2804   /* Validate index register.  */
2805   if (indx)
2806     {
2807       if (GET_CODE (indx) == UNSPEC)
2808         switch (XINT (indx, 1))
2809           {
2810           case UNSPEC_LTREF:
2811             if (!disp)
2812               disp = gen_rtx_UNSPEC (Pmode,
2813                                      gen_rtvec (1, XVECEXP (indx, 0, 0)),
2814                                      UNSPEC_LTREL_OFFSET);
2815             else
2816               return false;
2817
2818             indx = XVECEXP (indx, 0, 1);
2819             break;
2820
2821           case UNSPEC_LTREL_BASE:
2822             if (XVECLEN (indx, 0) == 1)
2823               indx = fake_pool_base, literal_pool = true;
2824             else
2825               indx = XVECEXP (indx, 0, 1);
2826             break;
2827
2828           default:
2829             return false;
2830           }
2831
2832       if (!REG_P (indx) || GET_MODE (indx) != Pmode)
2833         return false;
2834
2835       if (REGNO (indx) == STACK_POINTER_REGNUM
2836           || REGNO (indx) == FRAME_POINTER_REGNUM
2837           || ((reload_completed || reload_in_progress)
2838               && frame_pointer_needed
2839               && REGNO (indx) == HARD_FRAME_POINTER_REGNUM)
2840           || REGNO (indx) == ARG_POINTER_REGNUM
2841           || (flag_pic
2842               && REGNO (indx) == PIC_OFFSET_TABLE_REGNUM))
2843         pointer = indx_ptr = true;
2844
2845       if ((reload_completed || reload_in_progress)
2846           && indx == cfun->machine->base_reg)
2847         pointer = indx_ptr = literal_pool = true;
2848     }
2849
2850   /* Prefer to use pointer as base, not index.  */
2851   if (base && indx && !base_ptr
2852       && (indx_ptr || (!REG_POINTER (base) && REG_POINTER (indx))))
2853     {
2854       rtx tmp = base;
2855       base = indx;
2856       indx = tmp;
2857     }
2858
2859   /* Validate displacement.  */
2860   if (!disp)
2861     {
2862       /* If virtual registers are involved, the displacement will change later
2863          anyway as the virtual registers get eliminated.  This could make a
2864          valid displacement invalid, but it is more likely to make an invalid
2865          displacement valid, because we sometimes access the register save area
2866          via negative offsets to one of those registers.
2867          Thus we don't check the displacement for validity here.  If after
2868          elimination the displacement turns out to be invalid after all,
2869          this is fixed up by reload in any case.  */
2870       /* LRA maintains always displacements up to date and we need to
2871          know the displacement is right during all LRA not only at the
2872          final elimination.  */
2873       if (lra_in_progress
2874           || (base != arg_pointer_rtx
2875               && indx != arg_pointer_rtx
2876               && base != return_address_pointer_rtx
2877               && indx != return_address_pointer_rtx
2878               && base != frame_pointer_rtx
2879               && indx != frame_pointer_rtx
2880               && base != virtual_stack_vars_rtx
2881               && indx != virtual_stack_vars_rtx))
2882         if (!DISP_IN_RANGE (offset))
2883           return false;
2884     }
2885   else
2886     {
2887       /* All the special cases are pointers.  */
2888       pointer = true;
2889
2890       /* In the small-PIC case, the linker converts @GOT
2891          and @GOTNTPOFF offsets to possible displacements.  */
2892       if (GET_CODE (disp) == UNSPEC
2893           && (XINT (disp, 1) == UNSPEC_GOT
2894               || XINT (disp, 1) == UNSPEC_GOTNTPOFF)
2895           && flag_pic == 1)
2896         {
2897           ;
2898         }
2899
2900       /* Accept pool label offsets.  */
2901       else if (GET_CODE (disp) == UNSPEC
2902                && XINT (disp, 1) == UNSPEC_POOL_OFFSET)
2903         ;
2904
2905       /* Accept literal pool references.  */
2906       else if (GET_CODE (disp) == UNSPEC
2907                && XINT (disp, 1) == UNSPEC_LTREL_OFFSET)
2908         {
2909           /* In case CSE pulled a non literal pool reference out of
2910              the pool we have to reject the address.  This is
2911              especially important when loading the GOT pointer on non
2912              zarch CPUs.  In this case the literal pool contains an lt
2913              relative offset to the _GLOBAL_OFFSET_TABLE_ label which
2914              will most likely exceed the displacement.  */
2915           if (GET_CODE (XVECEXP (disp, 0, 0)) != SYMBOL_REF
2916               || !CONSTANT_POOL_ADDRESS_P (XVECEXP (disp, 0, 0)))
2917             return false;
2918
2919           orig_disp = gen_rtx_CONST (Pmode, disp);
2920           if (offset)
2921             {
2922               /* If we have an offset, make sure it does not
2923                  exceed the size of the constant pool entry.  */
2924               rtx sym = XVECEXP (disp, 0, 0);
2925               if (offset >= GET_MODE_SIZE (get_pool_mode (sym)))
2926                 return false;
2927
2928               orig_disp = plus_constant (Pmode, orig_disp, offset);
2929             }
2930         }
2931
2932       else
2933         return false;
2934     }
2935
2936   if (!base && !indx)
2937     pointer = true;
2938
2939   if (out)
2940     {
2941       out->base = base;
2942       out->indx = indx;
2943       out->disp = orig_disp;
2944       out->pointer = pointer;
2945       out->literal_pool = literal_pool;
2946     }
2947
2948   return true;
2949 }
2950
2951 /* Decompose a RTL expression OP for an address style operand into its
2952    components, and return the base register in BASE and the offset in
2953    OFFSET.  While OP looks like an address it is never supposed to be
2954    used as such.
2955
2956    Return true if OP is a valid address operand, false if not.  */
2957
2958 bool
2959 s390_decompose_addrstyle_without_index (rtx op, rtx *base,
2960                                         HOST_WIDE_INT *offset)
2961 {
2962   rtx off = NULL_RTX;
2963
2964   /* We can have an integer constant, an address register,
2965      or a sum of the two.  */
2966   if (CONST_SCALAR_INT_P (op))
2967     {
2968       off = op;
2969       op = NULL_RTX;
2970     }
2971   if (op && GET_CODE (op) == PLUS && CONST_SCALAR_INT_P (XEXP (op, 1)))
2972     {
2973       off = XEXP (op, 1);
2974       op = XEXP (op, 0);
2975     }
2976   while (op && GET_CODE (op) == SUBREG)
2977     op = SUBREG_REG (op);
2978
2979   if (op && GET_CODE (op) != REG)
2980     return false;
2981
2982   if (offset)
2983     {
2984       if (off == NULL_RTX)
2985         *offset = 0;
2986       else if (CONST_INT_P (off))
2987         *offset = INTVAL (off);
2988       else if (CONST_WIDE_INT_P (off))
2989         /* The offset will anyway be cut down to 12 bits so take just
2990            the lowest order chunk of the wide int.  */
2991         *offset = CONST_WIDE_INT_ELT (off, 0);
2992       else
2993         gcc_unreachable ();
2994     }
2995   if (base)
2996     *base = op;
2997
2998    return true;
2999 }
3000
3001
3002 /* Return true if CODE is a valid address without index.  */
3003
3004 bool
3005 s390_legitimate_address_without_index_p (rtx op)
3006 {
3007   struct s390_address addr;
3008
3009   if (!s390_decompose_address (XEXP (op, 0), &addr))
3010     return false;
3011   if (addr.indx)
3012     return false;
3013
3014   return true;
3015 }
3016
3017
3018 /* Return TRUE if ADDR is an operand valid for a load/store relative
3019    instruction.  Be aware that the alignment of the operand needs to
3020    be checked separately.
3021    Valid addresses are single references or a sum of a reference and a
3022    constant integer. Return these parts in SYMREF and ADDEND.  You can
3023    pass NULL in REF and/or ADDEND if you are not interested in these
3024    values.  Literal pool references are *not* considered symbol
3025    references.  */
3026
3027 static bool
3028 s390_loadrelative_operand_p (rtx addr, rtx *symref, HOST_WIDE_INT *addend)
3029 {
3030   HOST_WIDE_INT tmpaddend = 0;
3031
3032   if (GET_CODE (addr) == CONST)
3033     addr = XEXP (addr, 0);
3034
3035   if (GET_CODE (addr) == PLUS)
3036     {
3037       if (!CONST_INT_P (XEXP (addr, 1)))
3038         return false;
3039
3040       tmpaddend = INTVAL (XEXP (addr, 1));
3041       addr = XEXP (addr, 0);
3042     }
3043
3044   if ((GET_CODE (addr) == SYMBOL_REF && !CONSTANT_POOL_ADDRESS_P (addr))
3045       || (GET_CODE (addr) == UNSPEC
3046           && (XINT (addr, 1) == UNSPEC_GOTENT
3047               || (TARGET_CPU_ZARCH && XINT (addr, 1) == UNSPEC_PLT))))
3048     {
3049       if (symref)
3050         *symref = addr;
3051       if (addend)
3052         *addend = tmpaddend;
3053
3054       return true;
3055     }
3056   return false;
3057 }
3058
3059 /* Return true if the address in OP is valid for constraint letter C
3060    if wrapped in a MEM rtx.  Set LIT_POOL_OK to true if it literal
3061    pool MEMs should be accepted.  Only the Q, R, S, T constraint
3062    letters are allowed for C.  */
3063
3064 static int
3065 s390_check_qrst_address (char c, rtx op, bool lit_pool_ok)
3066 {
3067   struct s390_address addr;
3068   bool decomposed = false;
3069
3070   /* This check makes sure that no symbolic address (except literal
3071      pool references) are accepted by the R or T constraints.  */
3072   if (s390_loadrelative_operand_p (op, NULL, NULL))
3073     return 0;
3074
3075   /* Ensure literal pool references are only accepted if LIT_POOL_OK.  */
3076   if (!lit_pool_ok)
3077     {
3078       if (!s390_decompose_address (op, &addr))
3079         return 0;
3080       if (addr.literal_pool)
3081         return 0;
3082       decomposed = true;
3083     }
3084
3085   /* With reload, we sometimes get intermediate address forms that are
3086      actually invalid as-is, but we need to accept them in the most
3087      generic cases below ('R' or 'T'), since reload will in fact fix
3088      them up.  LRA behaves differently here; we never see such forms,
3089      but on the other hand, we need to strictly reject every invalid
3090      address form.  Perform this check right up front.  */
3091   if (lra_in_progress)
3092     {
3093       if (!decomposed && !s390_decompose_address (op, &addr))
3094         return 0;
3095       decomposed = true;
3096     }
3097
3098   switch (c)
3099     {
3100     case 'Q': /* no index short displacement */
3101       if (!decomposed && !s390_decompose_address (op, &addr))
3102         return 0;
3103       if (addr.indx)
3104         return 0;
3105       if (!s390_short_displacement (addr.disp))
3106         return 0;
3107       break;
3108
3109     case 'R': /* with index short displacement */
3110       if (TARGET_LONG_DISPLACEMENT)
3111         {
3112           if (!decomposed && !s390_decompose_address (op, &addr))
3113             return 0;
3114           if (!s390_short_displacement (addr.disp))
3115             return 0;
3116         }
3117       /* Any invalid address here will be fixed up by reload,
3118          so accept it for the most generic constraint.  */
3119       break;
3120
3121     case 'S': /* no index long displacement */
3122       if (!decomposed && !s390_decompose_address (op, &addr))
3123         return 0;
3124       if (addr.indx)
3125         return 0;
3126       break;
3127
3128     case 'T': /* with index long displacement */
3129       /* Any invalid address here will be fixed up by reload,
3130          so accept it for the most generic constraint.  */
3131       break;
3132
3133     default:
3134       return 0;
3135     }
3136   return 1;
3137 }
3138
3139
3140 /* Evaluates constraint strings described by the regular expression
3141    ([A|B|Z](Q|R|S|T))|Y and returns 1 if OP is a valid operand for
3142    the constraint given in STR, or 0 else.  */
3143
3144 int
3145 s390_mem_constraint (const char *str, rtx op)
3146 {
3147   char c = str[0];
3148
3149   switch (c)
3150     {
3151     case 'A':
3152       /* Check for offsettable variants of memory constraints.  */
3153       if (!MEM_P (op) || MEM_VOLATILE_P (op))
3154         return 0;
3155       if ((reload_completed || reload_in_progress)
3156           ? !offsettable_memref_p (op) : !offsettable_nonstrict_memref_p (op))
3157         return 0;
3158       return s390_check_qrst_address (str[1], XEXP (op, 0), true);
3159     case 'B':
3160       /* Check for non-literal-pool variants of memory constraints.  */
3161       if (!MEM_P (op))
3162         return 0;
3163       return s390_check_qrst_address (str[1], XEXP (op, 0), false);
3164     case 'Q':
3165     case 'R':
3166     case 'S':
3167     case 'T':
3168       if (GET_CODE (op) != MEM)
3169         return 0;
3170       return s390_check_qrst_address (c, XEXP (op, 0), true);
3171     case 'Y':
3172       /* Simply check for the basic form of a shift count.  Reload will
3173          take care of making sure we have a proper base register.  */
3174       if (!s390_decompose_addrstyle_without_index (op, NULL, NULL))
3175         return 0;
3176       break;
3177     case 'Z':
3178       return s390_check_qrst_address (str[1], op, true);
3179     default:
3180       return 0;
3181     }
3182   return 1;
3183 }
3184
3185
3186 /* Evaluates constraint strings starting with letter O.  Input
3187    parameter C is the second letter following the "O" in the constraint
3188    string. Returns 1 if VALUE meets the respective constraint and 0
3189    otherwise.  */
3190
3191 int
3192 s390_O_constraint_str (const char c, HOST_WIDE_INT value)
3193 {
3194   if (!TARGET_EXTIMM)
3195     return 0;
3196
3197   switch (c)
3198     {
3199     case 's':
3200       return trunc_int_for_mode (value, SImode) == value;
3201
3202     case 'p':
3203       return value == 0
3204         || s390_single_part (GEN_INT (value), DImode, SImode, 0) == 1;
3205
3206     case 'n':
3207       return s390_single_part (GEN_INT (value - 1), DImode, SImode, -1) == 1;
3208
3209     default:
3210       gcc_unreachable ();
3211     }
3212 }
3213
3214
3215 /* Evaluates constraint strings starting with letter N.  Parameter STR
3216    contains the letters following letter "N" in the constraint string.
3217    Returns true if VALUE matches the constraint.  */
3218
3219 int
3220 s390_N_constraint_str (const char *str, HOST_WIDE_INT value)
3221 {
3222   machine_mode mode, part_mode;
3223   int def;
3224   int part, part_goal;
3225
3226
3227   if (str[0] == 'x')
3228     part_goal = -1;
3229   else
3230     part_goal = str[0] - '0';
3231
3232   switch (str[1])
3233     {
3234     case 'Q':
3235       part_mode = QImode;
3236       break;
3237     case 'H':
3238       part_mode = HImode;
3239       break;
3240     case 'S':
3241       part_mode = SImode;
3242       break;
3243     default:
3244       return 0;
3245     }
3246
3247   switch (str[2])
3248     {
3249     case 'H':
3250       mode = HImode;
3251       break;
3252     case 'S':
3253       mode = SImode;
3254       break;
3255     case 'D':
3256       mode = DImode;
3257       break;
3258     default:
3259       return 0;
3260     }
3261
3262   switch (str[3])
3263     {
3264     case '0':
3265       def = 0;
3266       break;
3267     case 'F':
3268       def = -1;
3269       break;
3270     default:
3271       return 0;
3272     }
3273
3274   if (GET_MODE_SIZE (mode) <= GET_MODE_SIZE (part_mode))
3275     return 0;
3276
3277   part = s390_single_part (GEN_INT (value), mode, part_mode, def);
3278   if (part < 0)
3279     return 0;
3280   if (part_goal != -1 && part_goal != part)
3281     return 0;
3282
3283   return 1;
3284 }
3285
3286
3287 /* Returns true if the input parameter VALUE is a float zero.  */
3288
3289 int
3290 s390_float_const_zero_p (rtx value)
3291 {
3292   return (GET_MODE_CLASS (GET_MODE (value)) == MODE_FLOAT
3293           && value == CONST0_RTX (GET_MODE (value)));
3294 }
3295
3296 /* Implement TARGET_REGISTER_MOVE_COST.  */
3297
3298 static int
3299 s390_register_move_cost (machine_mode mode,
3300                          reg_class_t from, reg_class_t to)
3301 {
3302   /* On s390, copy between fprs and gprs is expensive.  */
3303
3304   /* It becomes somewhat faster having ldgr/lgdr.  */
3305   if (TARGET_Z10 && GET_MODE_SIZE (mode) == 8)
3306     {
3307       /* ldgr is single cycle. */
3308       if (reg_classes_intersect_p (from, GENERAL_REGS)
3309           && reg_classes_intersect_p (to, FP_REGS))
3310         return 1;
3311       /* lgdr needs 3 cycles. */
3312       if (reg_classes_intersect_p (to, GENERAL_REGS)
3313           && reg_classes_intersect_p (from, FP_REGS))
3314         return 3;
3315     }
3316
3317   /* Otherwise copying is done via memory.  */
3318   if ((reg_classes_intersect_p (from, GENERAL_REGS)
3319        && reg_classes_intersect_p (to, FP_REGS))
3320       || (reg_classes_intersect_p (from, FP_REGS)
3321           && reg_classes_intersect_p (to, GENERAL_REGS)))
3322     return 10;
3323
3324   return 1;
3325 }
3326
3327 /* Implement TARGET_MEMORY_MOVE_COST.  */
3328
3329 static int
3330 s390_memory_move_cost (machine_mode mode ATTRIBUTE_UNUSED,
3331                        reg_class_t rclass ATTRIBUTE_UNUSED,
3332                        bool in ATTRIBUTE_UNUSED)
3333 {
3334   return 2;
3335 }
3336
3337 /* Compute a (partial) cost for rtx X.  Return true if the complete
3338    cost has been computed, and false if subexpressions should be
3339    scanned.  In either case, *TOTAL contains the cost result.  The
3340    initial value of *TOTAL is the default value computed by
3341    rtx_cost.  It may be left unmodified.  OUTER_CODE contains the
3342    code of the superexpression of x.  */
3343
3344 static bool
3345 s390_rtx_costs (rtx x, machine_mode mode, int outer_code,
3346                 int opno ATTRIBUTE_UNUSED,
3347                 int *total, bool speed ATTRIBUTE_UNUSED)
3348 {
3349   int code = GET_CODE (x);
3350   switch (code)
3351     {
3352     case CONST:
3353     case CONST_INT:
3354     case LABEL_REF:
3355     case SYMBOL_REF:
3356     case CONST_DOUBLE:
3357     case CONST_WIDE_INT:
3358     case MEM:
3359       *total = 0;
3360       return true;
3361
3362     case IOR:
3363       /* risbg */
3364       if (GET_CODE (XEXP (x, 0)) == AND
3365           && GET_CODE (XEXP (x, 1)) == ASHIFT
3366           && REG_P (XEXP (XEXP (x, 0), 0))
3367           && REG_P (XEXP (XEXP (x, 1), 0))
3368           && CONST_INT_P (XEXP (XEXP (x, 0), 1))
3369           && CONST_INT_P (XEXP (XEXP (x, 1), 1))
3370           && (UINTVAL (XEXP (XEXP (x, 0), 1)) ==
3371               (HOST_WIDE_INT_1U << UINTVAL (XEXP (XEXP (x, 1), 1))) - 1))
3372         {
3373           *total = COSTS_N_INSNS (2);
3374           return true;
3375         }
3376
3377       /* ~AND on a 128 bit mode.  This can be done using a vector
3378          instruction.  */
3379       if (TARGET_VXE
3380           && GET_CODE (XEXP (x, 0)) == NOT
3381           && GET_CODE (XEXP (x, 1)) == NOT
3382           && REG_P (XEXP (XEXP (x, 0), 0))
3383           && REG_P (XEXP (XEXP (x, 1), 0))
3384           && GET_MODE_SIZE (GET_MODE (XEXP (XEXP (x, 0), 0))) == 16
3385           && s390_hard_regno_mode_ok (VR0_REGNUM,
3386                                       GET_MODE (XEXP (XEXP (x, 0), 0))))
3387         {
3388           *total = COSTS_N_INSNS (1);
3389           return true;
3390         }
3391       /* fallthrough */
3392     case ASHIFT:
3393     case ASHIFTRT:
3394     case LSHIFTRT:
3395     case ROTATE:
3396     case ROTATERT:
3397     case AND:
3398     case XOR:
3399     case NEG:
3400     case NOT:
3401       *total = COSTS_N_INSNS (1);
3402       return false;
3403
3404     case PLUS:
3405     case MINUS:
3406       *total = COSTS_N_INSNS (1);
3407       return false;
3408
3409     case MULT:
3410       switch (mode)
3411         {
3412         case SImode:
3413           {
3414             rtx left = XEXP (x, 0);
3415             rtx right = XEXP (x, 1);
3416             if (GET_CODE (right) == CONST_INT
3417                 && CONST_OK_FOR_K (INTVAL (right)))
3418               *total = s390_cost->mhi;
3419             else if (GET_CODE (left) == SIGN_EXTEND)
3420               *total = s390_cost->mh;
3421             else
3422               *total = s390_cost->ms;  /* msr, ms, msy */
3423             break;
3424           }
3425         case DImode:
3426           {
3427             rtx left = XEXP (x, 0);
3428             rtx right = XEXP (x, 1);
3429             if (TARGET_ZARCH)
3430               {
3431                 if (GET_CODE (right) == CONST_INT
3432                     && CONST_OK_FOR_K (INTVAL (right)))
3433                   *total = s390_cost->mghi;
3434                 else if (GET_CODE (left) == SIGN_EXTEND)
3435                   *total = s390_cost->msgf;
3436                 else
3437                   *total = s390_cost->msg;  /* msgr, msg */
3438               }
3439             else /* TARGET_31BIT */
3440               {
3441                 if (GET_CODE (left) == SIGN_EXTEND
3442                     && GET_CODE (right) == SIGN_EXTEND)
3443                   /* mulsidi case: mr, m */
3444                   *total = s390_cost->m;
3445                 else if (GET_CODE (left) == ZERO_EXTEND
3446                          && GET_CODE (right) == ZERO_EXTEND
3447                          && TARGET_CPU_ZARCH)
3448                   /* umulsidi case: ml, mlr */
3449                   *total = s390_cost->ml;
3450                 else
3451                   /* Complex calculation is required.  */
3452                   *total = COSTS_N_INSNS (40);
3453               }
3454             break;
3455           }
3456         case SFmode:
3457         case DFmode:
3458           *total = s390_cost->mult_df;
3459           break;
3460         case TFmode:
3461           *total = s390_cost->mxbr;
3462           break;
3463         default:
3464           return false;
3465         }
3466       return false;
3467
3468     case FMA:
3469       switch (mode)
3470         {
3471         case DFmode:
3472           *total = s390_cost->madbr;
3473           break;
3474         case SFmode:
3475           *total = s390_cost->maebr;
3476           break;
3477         default:
3478           return false;
3479         }
3480       /* Negate in the third argument is free: FMSUB.  */
3481       if (GET_CODE (XEXP (x, 2)) == NEG)
3482         {
3483           *total += (rtx_cost (XEXP (x, 0), mode, FMA, 0, speed)
3484                      + rtx_cost (XEXP (x, 1), mode, FMA, 1, speed)
3485                      + rtx_cost (XEXP (XEXP (x, 2), 0), mode, FMA, 2, speed));
3486           return true;
3487         }
3488       return false;
3489
3490     case UDIV:
3491     case UMOD:
3492       if (mode == TImode)              /* 128 bit division */
3493         *total = s390_cost->dlgr;
3494       else if (mode == DImode)
3495         {
3496           rtx right = XEXP (x, 1);
3497           if (GET_CODE (right) == ZERO_EXTEND) /* 64 by 32 bit division */
3498             *total = s390_cost->dlr;
3499           else                                 /* 64 by 64 bit division */
3500             *total = s390_cost->dlgr;
3501         }
3502       else if (mode == SImode)         /* 32 bit division */
3503         *total = s390_cost->dlr;
3504       return false;
3505
3506     case DIV:
3507     case MOD:
3508       if (mode == DImode)
3509         {
3510           rtx right = XEXP (x, 1);
3511           if (GET_CODE (right) == ZERO_EXTEND) /* 64 by 32 bit division */
3512             if (TARGET_ZARCH)
3513               *total = s390_cost->dsgfr;
3514             else
3515               *total = s390_cost->dr;
3516           else                                 /* 64 by 64 bit division */
3517             *total = s390_cost->dsgr;
3518         }
3519       else if (mode == SImode)         /* 32 bit division */
3520         *total = s390_cost->dlr;
3521       else if (mode == SFmode)
3522         {
3523           *total = s390_cost->debr;
3524         }
3525       else if (mode == DFmode)
3526         {
3527           *total = s390_cost->ddbr;
3528         }
3529       else if (mode == TFmode)
3530         {
3531           *total = s390_cost->dxbr;
3532         }
3533       return false;
3534
3535     case SQRT:
3536       if (mode == SFmode)
3537         *total = s390_cost->sqebr;
3538       else if (mode == DFmode)
3539         *total = s390_cost->sqdbr;
3540       else /* TFmode */
3541         *total = s390_cost->sqxbr;
3542       return false;
3543
3544     case SIGN_EXTEND:
3545     case ZERO_EXTEND:
3546       if (outer_code == MULT || outer_code == DIV || outer_code == MOD
3547           || outer_code == PLUS || outer_code == MINUS
3548           || outer_code == COMPARE)
3549         *total = 0;
3550       return false;
3551
3552     case COMPARE:
3553       *total = COSTS_N_INSNS (1);
3554       if (GET_CODE (XEXP (x, 0)) == AND
3555           && GET_CODE (XEXP (x, 1)) == CONST_INT
3556           && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT)
3557         {
3558           rtx op0 = XEXP (XEXP (x, 0), 0);
3559           rtx op1 = XEXP (XEXP (x, 0), 1);
3560           rtx op2 = XEXP (x, 1);
3561
3562           if (memory_operand (op0, GET_MODE (op0))
3563               && s390_tm_ccmode (op1, op2, 0) != VOIDmode)
3564             return true;
3565           if (register_operand (op0, GET_MODE (op0))
3566               && s390_tm_ccmode (op1, op2, 1) != VOIDmode)
3567             return true;
3568         }
3569       return false;
3570
3571     default:
3572       return false;
3573     }
3574 }
3575
3576 /* Return the cost of an address rtx ADDR.  */
3577
3578 static int
3579 s390_address_cost (rtx addr, machine_mode mode ATTRIBUTE_UNUSED,
3580                    addr_space_t as ATTRIBUTE_UNUSED,
3581                    bool speed ATTRIBUTE_UNUSED)
3582 {
3583   struct s390_address ad;
3584   if (!s390_decompose_address (addr, &ad))
3585     return 1000;
3586
3587   return ad.indx? COSTS_N_INSNS (1) + 1 : COSTS_N_INSNS (1);
3588 }
3589
3590 /* Implement targetm.vectorize.builtin_vectorization_cost.  */
3591 static int
3592 s390_builtin_vectorization_cost (enum vect_cost_for_stmt type_of_cost,
3593                                  tree vectype,
3594                                  int misalign ATTRIBUTE_UNUSED)
3595 {
3596   switch (type_of_cost)
3597     {
3598       case scalar_stmt:
3599       case scalar_load:
3600       case scalar_store:
3601       case vector_stmt:
3602       case vector_load:
3603       case vector_store:
3604       case vec_to_scalar:
3605       case scalar_to_vec:
3606       case cond_branch_not_taken:
3607       case vec_perm:
3608       case vec_promote_demote:
3609       case unaligned_load:
3610       case unaligned_store:
3611         return 1;
3612
3613       case cond_branch_taken:
3614         return 3;
3615
3616       case vec_construct:
3617         return TYPE_VECTOR_SUBPARTS (vectype) - 1;
3618
3619       default:
3620         gcc_unreachable ();
3621     }
3622 }
3623
3624 /* If OP is a SYMBOL_REF of a thread-local symbol, return its TLS mode,
3625    otherwise return 0.  */
3626
3627 int
3628 tls_symbolic_operand (rtx op)
3629 {
3630   if (GET_CODE (op) != SYMBOL_REF)
3631     return 0;
3632   return SYMBOL_REF_TLS_MODEL (op);
3633 }
3634 \f
3635 /* Split DImode access register reference REG (on 64-bit) into its constituent
3636    low and high parts, and store them into LO and HI.  Note that gen_lowpart/
3637    gen_highpart cannot be used as they assume all registers are word-sized,
3638    while our access registers have only half that size.  */
3639
3640 void
3641 s390_split_access_reg (rtx reg, rtx *lo, rtx *hi)
3642 {
3643   gcc_assert (TARGET_64BIT);
3644   gcc_assert (ACCESS_REG_P (reg));
3645   gcc_assert (GET_MODE (reg) == DImode);
3646   gcc_assert (!(REGNO (reg) & 1));
3647
3648   *lo = gen_rtx_REG (SImode, REGNO (reg) + 1);
3649   *hi = gen_rtx_REG (SImode, REGNO (reg));
3650 }
3651
3652 /* Return true if OP contains a symbol reference */
3653
3654 bool
3655 symbolic_reference_mentioned_p (rtx op)
3656 {
3657   const char *fmt;
3658   int i;
3659
3660   if (GET_CODE (op) == SYMBOL_REF || GET_CODE (op) == LABEL_REF)
3661     return 1;
3662
3663   fmt = GET_RTX_FORMAT (GET_CODE (op));
3664   for (i = GET_RTX_LENGTH (GET_CODE (op)) - 1; i >= 0; i--)
3665     {
3666       if (fmt[i] == 'E')
3667         {
3668           int j;
3669
3670           for (j = XVECLEN (op, i) - 1; j >= 0; j--)
3671             if (symbolic_reference_mentioned_p (XVECEXP (op, i, j)))
3672               return 1;
3673         }
3674
3675       else if (fmt[i] == 'e' && symbolic_reference_mentioned_p (XEXP (op, i)))
3676         return 1;
3677     }
3678
3679   return 0;
3680 }
3681
3682 /* Return true if OP contains a reference to a thread-local symbol.  */
3683
3684 bool
3685 tls_symbolic_reference_mentioned_p (rtx op)
3686 {
3687   const char *fmt;
3688   int i;
3689
3690   if (GET_CODE (op) == SYMBOL_REF)
3691     return tls_symbolic_operand (op);
3692
3693   fmt = GET_RTX_FORMAT (GET_CODE (op));
3694   for (i = GET_RTX_LENGTH (GET_CODE (op)) - 1; i >= 0; i--)
3695     {
3696       if (fmt[i] == 'E')
3697         {
3698           int j;
3699
3700           for (j = XVECLEN (op, i) - 1; j >= 0; j--)
3701             if (tls_symbolic_reference_mentioned_p (XVECEXP (op, i, j)))
3702               return true;
3703         }
3704
3705       else if (fmt[i] == 'e' && tls_symbolic_reference_mentioned_p (XEXP (op, i)))
3706         return true;
3707     }
3708
3709   return false;
3710 }
3711
3712
3713 /* Return true if OP is a legitimate general operand when
3714    generating PIC code.  It is given that flag_pic is on
3715    and that OP satisfies CONSTANT_P.  */
3716
3717 int
3718 legitimate_pic_operand_p (rtx op)
3719 {
3720   /* Accept all non-symbolic constants.  */
3721   if (!SYMBOLIC_CONST (op))
3722     return 1;
3723
3724   /* Reject everything else; must be handled
3725      via emit_symbolic_move.  */
3726   return 0;
3727 }
3728
3729 /* Returns true if the constant value OP is a legitimate general operand.
3730    It is given that OP satisfies CONSTANT_P.  */
3731
3732 static bool
3733 s390_legitimate_constant_p (machine_mode mode, rtx op)
3734 {
3735   if (TARGET_VX && VECTOR_MODE_P (mode) && GET_CODE (op) == CONST_VECTOR)
3736     {
3737       if (GET_MODE_SIZE (mode) != 16)
3738         return 0;
3739
3740       if (!satisfies_constraint_j00 (op)
3741           && !satisfies_constraint_jm1 (op)
3742           && !satisfies_constraint_jKK (op)
3743           && !satisfies_constraint_jxx (op)
3744           && !satisfies_constraint_jyy (op))
3745         return 0;
3746     }
3747
3748   /* Accept all non-symbolic constants.  */
3749   if (!SYMBOLIC_CONST (op))
3750     return 1;
3751
3752   /* Accept immediate LARL operands.  */
3753   if (TARGET_CPU_ZARCH && larl_operand (op, mode))
3754     return 1;
3755
3756   /* Thread-local symbols are never legal constants.  This is
3757      so that emit_call knows that computing such addresses
3758      might require a function call.  */
3759   if (TLS_SYMBOLIC_CONST (op))
3760     return 0;
3761
3762   /* In the PIC case, symbolic constants must *not* be
3763      forced into the literal pool.  We accept them here,
3764      so that they will be handled by emit_symbolic_move.  */
3765   if (flag_pic)
3766     return 1;
3767
3768   /* All remaining non-PIC symbolic constants are
3769      forced into the literal pool.  */
3770   return 0;
3771 }
3772
3773 /* Determine if it's legal to put X into the constant pool.  This
3774    is not possible if X contains the address of a symbol that is
3775    not constant (TLS) or not known at final link time (PIC).  */
3776
3777 static bool
3778 s390_cannot_force_const_mem (machine_mode mode, rtx x)
3779 {
3780   switch (GET_CODE (x))
3781     {
3782     case CONST_INT:
3783     case CONST_DOUBLE:
3784     case CONST_WIDE_INT:
3785     case CONST_VECTOR:
3786       /* Accept all non-symbolic constants.  */
3787       return false;
3788
3789     case LABEL_REF:
3790       /* Labels are OK iff we are non-PIC.  */
3791       return flag_pic != 0;
3792
3793     case SYMBOL_REF:
3794       /* 'Naked' TLS symbol references are never OK,
3795          non-TLS symbols are OK iff we are non-PIC.  */
3796       if (tls_symbolic_operand (x))
3797         return true;
3798       else
3799         return flag_pic != 0;
3800
3801     case CONST:
3802       return s390_cannot_force_const_mem (mode, XEXP (x, 0));
3803     case PLUS:
3804     case MINUS:
3805       return s390_cannot_force_const_mem (mode, XEXP (x, 0))
3806              || s390_cannot_force_const_mem (mode, XEXP (x, 1));
3807
3808     case UNSPEC:
3809       switch (XINT (x, 1))
3810         {
3811         /* Only lt-relative or GOT-relative UNSPECs are OK.  */
3812         case UNSPEC_LTREL_OFFSET:
3813         case UNSPEC_GOT:
3814         case UNSPEC_GOTOFF:
3815         case UNSPEC_PLTOFF:
3816         case UNSPEC_TLSGD:
3817         case UNSPEC_TLSLDM:
3818         case UNSPEC_NTPOFF:
3819         case UNSPEC_DTPOFF:
3820         case UNSPEC_GOTNTPOFF:
3821         case UNSPEC_INDNTPOFF:
3822           return false;
3823
3824         /* If the literal pool shares the code section, be put
3825            execute template placeholders into the pool as well.  */
3826         case UNSPEC_INSN:
3827           return TARGET_CPU_ZARCH;
3828
3829         default:
3830           return true;
3831         }
3832       break;
3833
3834     default:
3835       gcc_unreachable ();
3836     }
3837 }
3838
3839 /* Returns true if the constant value OP is a legitimate general
3840    operand during and after reload.  The difference to
3841    legitimate_constant_p is that this function will not accept
3842    a constant that would need to be forced to the literal pool
3843    before it can be used as operand.
3844    This function accepts all constants which can be loaded directly
3845    into a GPR.  */
3846
3847 bool
3848 legitimate_reload_constant_p (rtx op)
3849 {
3850   /* Accept la(y) operands.  */
3851   if (GET_CODE (op) == CONST_INT
3852       && DISP_IN_RANGE (INTVAL (op)))
3853     return true;
3854
3855   /* Accept l(g)hi/l(g)fi operands.  */
3856   if (GET_CODE (op) == CONST_INT
3857       && (CONST_OK_FOR_K (INTVAL (op)) || CONST_OK_FOR_Os (INTVAL (op))))
3858     return true;
3859
3860   /* Accept lliXX operands.  */
3861   if (TARGET_ZARCH
3862       && GET_CODE (op) == CONST_INT
3863       && trunc_int_for_mode (INTVAL (op), word_mode) == INTVAL (op)
3864       && s390_single_part (op, word_mode, HImode, 0) >= 0)
3865   return true;
3866
3867   if (TARGET_EXTIMM
3868       && GET_CODE (op) == CONST_INT
3869       && trunc_int_for_mode (INTVAL (op), word_mode) == INTVAL (op)
3870       && s390_single_part (op, word_mode, SImode, 0) >= 0)
3871     return true;
3872
3873   /* Accept larl operands.  */
3874   if (TARGET_CPU_ZARCH
3875       && larl_operand (op, VOIDmode))
3876     return true;
3877
3878   /* Accept floating-point zero operands that fit into a single GPR.  */
3879   if (GET_CODE (op) == CONST_DOUBLE
3880       && s390_float_const_zero_p (op)
3881       && GET_MODE_SIZE (GET_MODE (op)) <= UNITS_PER_WORD)
3882     return true;
3883
3884   /* Accept double-word operands that can be split.  */
3885   if (GET_CODE (op) == CONST_WIDE_INT
3886       || (GET_CODE (op) == CONST_INT
3887           && trunc_int_for_mode (INTVAL (op), word_mode) != INTVAL (op)))
3888     {
3889       machine_mode dword_mode = word_mode == SImode ? DImode : TImode;
3890       rtx hi = operand_subword (op, 0, 0, dword_mode);
3891       rtx lo = operand_subword (op, 1, 0, dword_mode);
3892       return legitimate_reload_constant_p (hi)
3893              && legitimate_reload_constant_p (lo);
3894     }
3895
3896   /* Everything else cannot be handled without reload.  */
3897   return false;
3898 }
3899
3900 /* Returns true if the constant value OP is a legitimate fp operand
3901    during and after reload.
3902    This function accepts all constants which can be loaded directly
3903    into an FPR.  */
3904
3905 static bool
3906 legitimate_reload_fp_constant_p (rtx op)
3907 {
3908   /* Accept floating-point zero operands if the load zero instruction
3909      can be used.  Prior to z196 the load fp zero instruction caused a
3910      performance penalty if the result is used as BFP number.  */
3911   if (TARGET_Z196
3912       && GET_CODE (op) == CONST_DOUBLE
3913       && s390_float_const_zero_p (op))
3914     return true;
3915
3916   return false;
3917 }
3918
3919 /* Returns true if the constant value OP is a legitimate vector operand
3920    during and after reload.
3921    This function accepts all constants which can be loaded directly
3922    into an VR.  */
3923
3924 static bool
3925 legitimate_reload_vector_constant_p (rtx op)
3926 {
3927   if (TARGET_VX && GET_MODE_SIZE (GET_MODE (op)) == 16
3928       && (satisfies_constraint_j00 (op)
3929           || satisfies_constraint_jm1 (op)
3930           || satisfies_constraint_jKK (op)
3931           || satisfies_constraint_jxx (op)
3932           || satisfies_constraint_jyy (op)))
3933     return true;
3934
3935   return false;
3936 }
3937
3938 /* Given an rtx OP being reloaded into a reg required to be in class RCLASS,
3939    return the class of reg to actually use.  */
3940
3941 static reg_class_t
3942 s390_preferred_reload_class (rtx op, reg_class_t rclass)
3943 {
3944   switch (GET_CODE (op))
3945     {
3946       /* Constants we cannot reload into general registers
3947          must be forced into the literal pool.  */
3948       case CONST_VECTOR:
3949       case CONST_DOUBLE:
3950       case CONST_INT:
3951       case CONST_WIDE_INT:
3952         if (reg_class_subset_p (GENERAL_REGS, rclass)
3953             && legitimate_reload_constant_p (op))
3954           return GENERAL_REGS;
3955         else if (reg_class_subset_p (ADDR_REGS, rclass)
3956                  && legitimate_reload_constant_p (op))
3957           return ADDR_REGS;
3958         else if (reg_class_subset_p (FP_REGS, rclass)
3959                  && legitimate_reload_fp_constant_p (op))
3960           return FP_REGS;
3961         else if (reg_class_subset_p (VEC_REGS, rclass)
3962                  && legitimate_reload_vector_constant_p (op))
3963           return VEC_REGS;
3964
3965         return NO_REGS;
3966
3967       /* If a symbolic constant or a PLUS is reloaded,
3968          it is most likely being used as an address, so
3969          prefer ADDR_REGS.  If 'class' is not a superset
3970          of ADDR_REGS, e.g. FP_REGS, reject this reload.  */
3971       case CONST:
3972         /* Symrefs cannot be pushed into the literal pool with -fPIC
3973            so we *MUST NOT* return NO_REGS for these cases
3974            (s390_cannot_force_const_mem will return true).  
3975
3976            On the other hand we MUST return NO_REGS for symrefs with
3977            invalid addend which might have been pushed to the literal
3978            pool (no -fPIC).  Usually we would expect them to be
3979            handled via secondary reload but this does not happen if
3980            they are used as literal pool slot replacement in reload
3981            inheritance (see emit_input_reload_insns).  */
3982         if (TARGET_CPU_ZARCH
3983             && GET_CODE (XEXP (op, 0)) == PLUS
3984             && GET_CODE (XEXP (XEXP(op, 0), 0)) == SYMBOL_REF
3985             && GET_CODE (XEXP (XEXP(op, 0), 1)) == CONST_INT)
3986           {
3987             if (flag_pic && reg_class_subset_p (ADDR_REGS, rclass))
3988               return ADDR_REGS;
3989             else
3990               return NO_REGS;
3991           }
3992         /* fallthrough */
3993       case LABEL_REF:
3994       case SYMBOL_REF:
3995         if (!legitimate_reload_constant_p (op))
3996           return NO_REGS;
3997         /* fallthrough */
3998       case PLUS:
3999         /* load address will be used.  */
4000         if (reg_class_subset_p (ADDR_REGS, rclass))
4001           return ADDR_REGS;
4002         else
4003           return NO_REGS;
4004
4005       default:
4006         break;
4007     }
4008
4009   return rclass;
4010 }
4011
4012 /* Return true if ADDR is SYMBOL_REF + addend with addend being a
4013    multiple of ALIGNMENT and the SYMBOL_REF being naturally
4014    aligned.  */
4015
4016 bool
4017 s390_check_symref_alignment (rtx addr, HOST_WIDE_INT alignment)
4018 {
4019   HOST_WIDE_INT addend;
4020   rtx symref;
4021
4022   /* The "required alignment" might be 0 (e.g. for certain structs
4023      accessed via BLKmode).  Early abort in this case, as well as when
4024      an alignment > 8 is required.  */
4025   if (alignment < 2 || alignment > 8)
4026     return false;
4027
4028   if (!s390_loadrelative_operand_p (addr, &symref, &addend))
4029     return false;
4030
4031   if (addend & (alignment - 1))
4032     return false;
4033
4034   if (GET_CODE (symref) == SYMBOL_REF)
4035     {
4036       /* We have load-relative instructions for 2-byte, 4-byte, and
4037          8-byte alignment so allow only these.  */
4038       switch (alignment)
4039         {
4040         case 8: return !SYMBOL_FLAG_NOTALIGN8_P (symref);
4041         case 4: return !SYMBOL_FLAG_NOTALIGN4_P (symref);
4042         case 2: return !SYMBOL_FLAG_NOTALIGN2_P (symref);
4043         default: return false;
4044         }
4045     }
4046
4047   if (GET_CODE (symref) == UNSPEC
4048       && alignment <= UNITS_PER_LONG)
4049     return true;
4050
4051   return false;
4052 }
4053
4054 /* ADDR is moved into REG using larl.  If ADDR isn't a valid larl
4055    operand SCRATCH is used to reload the even part of the address and
4056    adding one.  */
4057
4058 void
4059 s390_reload_larl_operand (rtx reg, rtx addr, rtx scratch)
4060 {
4061   HOST_WIDE_INT addend;
4062   rtx symref;
4063
4064   if (!s390_loadrelative_operand_p (addr, &symref, &addend))
4065     gcc_unreachable ();
4066
4067   if (!(addend & 1))
4068     /* Easy case.  The addend is even so larl will do fine.  */
4069     emit_move_insn (reg, addr);
4070   else
4071     {
4072       /* We can leave the scratch register untouched if the target
4073          register is a valid base register.  */
4074       if (REGNO (reg) < FIRST_PSEUDO_REGISTER
4075           && REGNO_REG_CLASS (REGNO (reg)) == ADDR_REGS)
4076         scratch = reg;
4077
4078       gcc_assert (REGNO (scratch) < FIRST_PSEUDO_REGISTER);
4079       gcc_assert (REGNO_REG_CLASS (REGNO (scratch)) == ADDR_REGS);
4080
4081       if (addend != 1)
4082         emit_move_insn (scratch,
4083                         gen_rtx_CONST (Pmode,
4084                                        gen_rtx_PLUS (Pmode, symref,
4085                                                      GEN_INT (addend - 1))));
4086       else
4087         emit_move_insn (scratch, symref);
4088
4089       /* Increment the address using la in order to avoid clobbering cc.  */
4090       s390_load_address (reg, gen_rtx_PLUS (Pmode, scratch, const1_rtx));
4091     }
4092 }
4093
4094 /* Generate what is necessary to move between REG and MEM using
4095    SCRATCH.  The direction is given by TOMEM.  */
4096
4097 void
4098 s390_reload_symref_address (rtx reg, rtx mem, rtx scratch, bool tomem)
4099 {
4100   /* Reload might have pulled a constant out of the literal pool.
4101      Force it back in.  */
4102   if (CONST_INT_P (mem) || GET_CODE (mem) == CONST_DOUBLE
4103       || GET_CODE (mem) == CONST_WIDE_INT
4104       || GET_CODE (mem) == CONST_VECTOR
4105       || GET_CODE (mem) == CONST)
4106     mem = force_const_mem (GET_MODE (reg), mem);
4107
4108   gcc_assert (MEM_P (mem));
4109
4110   /* For a load from memory we can leave the scratch register
4111      untouched if the target register is a valid base register.  */
4112   if (!tomem
4113       && REGNO (reg) < FIRST_PSEUDO_REGISTER
4114       && REGNO_REG_CLASS (REGNO (reg)) == ADDR_REGS
4115       && GET_MODE (reg) == GET_MODE (scratch))
4116     scratch = reg;
4117
4118   /* Load address into scratch register.  Since we can't have a
4119      secondary reload for a secondary reload we have to cover the case
4120      where larl would need a secondary reload here as well.  */
4121   s390_reload_larl_operand (scratch, XEXP (mem, 0), scratch);
4122
4123   /* Now we can use a standard load/store to do the move.  */
4124   if (tomem)
4125     emit_move_insn (replace_equiv_address (mem, scratch), reg);
4126   else
4127     emit_move_insn (reg, replace_equiv_address (mem, scratch));
4128 }
4129
4130 /* Inform reload about cases where moving X with a mode MODE to a register in
4131    RCLASS requires an extra scratch or immediate register.  Return the class
4132    needed for the immediate register.  */
4133
4134 static reg_class_t
4135 s390_secondary_reload (bool in_p, rtx x, reg_class_t rclass_i,
4136                        machine_mode mode, secondary_reload_info *sri)
4137 {
4138   enum reg_class rclass = (enum reg_class) rclass_i;
4139
4140   /* Intermediate register needed.  */
4141   if (reg_classes_intersect_p (CC_REGS, rclass))
4142     return GENERAL_REGS;
4143
4144   if (TARGET_VX)
4145     {
4146       /* The vst/vl vector move instructions allow only for short
4147          displacements.  */
4148       if (MEM_P (x)
4149           && GET_CODE (XEXP (x, 0)) == PLUS
4150           && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT
4151           && !SHORT_DISP_IN_RANGE(INTVAL (XEXP (XEXP (x, 0), 1)))
4152           && reg_class_subset_p (rclass, VEC_REGS)
4153           && (!reg_class_subset_p (rclass, FP_REGS)
4154               || (GET_MODE_SIZE (mode) > 8
4155                   && s390_class_max_nregs (FP_REGS, mode) == 1)))
4156         {
4157           if (in_p)
4158             sri->icode = (TARGET_64BIT ?
4159                           CODE_FOR_reloaddi_la_in :
4160                           CODE_FOR_reloadsi_la_in);
4161           else
4162             sri->icode = (TARGET_64BIT ?
4163                           CODE_FOR_reloaddi_la_out :
4164                           CODE_FOR_reloadsi_la_out);
4165         }
4166     }
4167
4168   if (TARGET_Z10)
4169     {
4170       HOST_WIDE_INT offset;
4171       rtx symref;
4172
4173       /* On z10 several optimizer steps may generate larl operands with
4174          an odd addend.  */
4175       if (in_p
4176           && s390_loadrelative_operand_p (x, &symref, &offset)
4177           && mode == Pmode
4178           && !SYMBOL_FLAG_NOTALIGN2_P (symref)
4179           && (offset & 1) == 1)
4180         sri->icode = ((mode == DImode) ? CODE_FOR_reloaddi_larl_odd_addend_z10
4181                       : CODE_FOR_reloadsi_larl_odd_addend_z10);
4182
4183       /* Handle all the (mem (symref)) accesses we cannot use the z10
4184          instructions for.  */
4185       if (MEM_P (x)
4186           && s390_loadrelative_operand_p (XEXP (x, 0), NULL, NULL)
4187           && (mode == QImode
4188               || !reg_class_subset_p (rclass, GENERAL_REGS)
4189               || GET_MODE_SIZE (mode) > UNITS_PER_WORD
4190               || !s390_check_symref_alignment (XEXP (x, 0),
4191                                                GET_MODE_SIZE (mode))))
4192         {
4193 #define __SECONDARY_RELOAD_CASE(M,m)                                    \
4194           case M##mode:                                                 \
4195             if (TARGET_64BIT)                                           \
4196               sri->icode = in_p ? CODE_FOR_reload##m##di_toreg_z10 :    \
4197                                   CODE_FOR_reload##m##di_tomem_z10;     \
4198             else                                                        \
4199               sri->icode = in_p ? CODE_FOR_reload##m##si_toreg_z10 :    \
4200                                   CODE_FOR_reload##m##si_tomem_z10;     \
4201           break;
4202
4203           switch (GET_MODE (x))
4204             {
4205               __SECONDARY_RELOAD_CASE (QI, qi);
4206               __SECONDARY_RELOAD_CASE (HI, hi);
4207               __SECONDARY_RELOAD_CASE (SI, si);
4208               __SECONDARY_RELOAD_CASE (DI, di);
4209               __SECONDARY_RELOAD_CASE (TI, ti);
4210               __SECONDARY_RELOAD_CASE (SF, sf);
4211               __SECONDARY_RELOAD_CASE (DF, df);
4212               __SECONDARY_RELOAD_CASE (TF, tf);
4213               __SECONDARY_RELOAD_CASE (SD, sd);
4214               __SECONDARY_RELOAD_CASE (DD, dd);
4215               __SECONDARY_RELOAD_CASE (TD, td);
4216               __SECONDARY_RELOAD_CASE (V1QI, v1qi);
4217               __SECONDARY_RELOAD_CASE (V2QI, v2qi);
4218               __SECONDARY_RELOAD_CASE (V4QI, v4qi);
4219               __SECONDARY_RELOAD_CASE (V8QI, v8qi);
4220               __SECONDARY_RELOAD_CASE (V16QI, v16qi);
4221               __SECONDARY_RELOAD_CASE (V1HI, v1hi);
4222               __SECONDARY_RELOAD_CASE (V2HI, v2hi);
4223               __SECONDARY_RELOAD_CASE (V4HI, v4hi);
4224               __SECONDARY_RELOAD_CASE (V8HI, v8hi);
4225               __SECONDARY_RELOAD_CASE (V1SI, v1si);
4226               __SECONDARY_RELOAD_CASE (V2SI, v2si);
4227               __SECONDARY_RELOAD_CASE (V4SI, v4si);
4228               __SECONDARY_RELOAD_CASE (V1DI, v1di);
4229               __SECONDARY_RELOAD_CASE (V2DI, v2di);
4230               __SECONDARY_RELOAD_CASE (V1TI, v1ti);
4231               __SECONDARY_RELOAD_CASE (V1SF, v1sf);
4232               __SECONDARY_RELOAD_CASE (V2SF, v2sf);
4233               __SECONDARY_RELOAD_CASE (V4SF, v4sf);
4234               __SECONDARY_RELOAD_CASE (V1DF, v1df);
4235               __SECONDARY_RELOAD_CASE (V2DF, v2df);
4236               __SECONDARY_RELOAD_CASE (V1TF, v1tf);
4237             default:
4238               gcc_unreachable ();
4239             }
4240 #undef __SECONDARY_RELOAD_CASE
4241         }
4242     }
4243
4244   /* We need a scratch register when loading a PLUS expression which
4245      is not a legitimate operand of the LOAD ADDRESS instruction.  */
4246   /* LRA can deal with transformation of plus op very well -- so we
4247      don't need to prompt LRA in this case.  */
4248   if (! lra_in_progress && in_p && s390_plus_operand (x, mode))
4249     sri->icode = (TARGET_64BIT ?
4250                   CODE_FOR_reloaddi_plus : CODE_FOR_reloadsi_plus);
4251
4252   /* Performing a multiword move from or to memory we have to make sure the
4253      second chunk in memory is addressable without causing a displacement
4254      overflow.  If that would be the case we calculate the address in
4255      a scratch register.  */
4256   if (MEM_P (x)
4257       && GET_CODE (XEXP (x, 0)) == PLUS
4258       && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT
4259       && !DISP_IN_RANGE (INTVAL (XEXP (XEXP (x, 0), 1))
4260                          + GET_MODE_SIZE (mode) - 1))
4261     {
4262       /* For GENERAL_REGS a displacement overflow is no problem if occurring
4263          in a s_operand address since we may fallback to lm/stm.  So we only
4264          have to care about overflows in the b+i+d case.  */
4265       if ((reg_classes_intersect_p (GENERAL_REGS, rclass)
4266            && s390_class_max_nregs (GENERAL_REGS, mode) > 1
4267            && GET_CODE (XEXP (XEXP (x, 0), 0)) == PLUS)
4268           /* For FP_REGS no lm/stm is available so this check is triggered
4269              for displacement overflows in b+i+d and b+d like addresses.  */
4270           || (reg_classes_intersect_p (FP_REGS, rclass)
4271               && s390_class_max_nregs (FP_REGS, mode) > 1))
4272         {
4273           if (in_p)
4274             sri->icode = (TARGET_64BIT ?
4275                           CODE_FOR_reloaddi_la_in :
4276                           CODE_FOR_reloadsi_la_in);
4277           else
4278             sri->icode = (TARGET_64BIT ?
4279                           CODE_FOR_reloaddi_la_out :
4280                           CODE_FOR_reloadsi_la_out);
4281         }
4282     }
4283
4284   /* A scratch address register is needed when a symbolic constant is
4285      copied to r0 compiling with -fPIC.  In other cases the target
4286      register might be used as temporary (see legitimize_pic_address).  */
4287   if (in_p && SYMBOLIC_CONST (x) && flag_pic == 2 && rclass != ADDR_REGS)
4288     sri->icode = (TARGET_64BIT ?
4289                   CODE_FOR_reloaddi_PIC_addr :
4290                   CODE_FOR_reloadsi_PIC_addr);
4291
4292   /* Either scratch or no register needed.  */
4293   return NO_REGS;
4294 }
4295
4296 /* Generate code to load SRC, which is PLUS that is not a
4297    legitimate operand for the LA instruction, into TARGET.
4298    SCRATCH may be used as scratch register.  */
4299
4300 void
4301 s390_expand_plus_operand (rtx target, rtx src,
4302                           rtx scratch)
4303 {
4304   rtx sum1, sum2;
4305   struct s390_address ad;
4306
4307   /* src must be a PLUS; get its two operands.  */
4308   gcc_assert (GET_CODE (src) == PLUS);
4309   gcc_assert (GET_MODE (src) == Pmode);
4310
4311   /* Check if any of the two operands is already scheduled
4312      for replacement by reload.  This can happen e.g. when
4313      float registers occur in an address.  */
4314   sum1 = find_replacement (&XEXP (src, 0));
4315   sum2 = find_replacement (&XEXP (src, 1));
4316   src = gen_rtx_PLUS (Pmode, sum1, sum2);
4317
4318   /* If the address is already strictly valid, there's nothing to do.  */
4319   if (!s390_decompose_address (src, &ad)
4320       || (ad.base && !REGNO_OK_FOR_BASE_P (REGNO (ad.base)))
4321       || (ad.indx && !REGNO_OK_FOR_INDEX_P (REGNO (ad.indx))))
4322     {
4323       /* Otherwise, one of the operands cannot be an address register;
4324          we reload its value into the scratch register.  */
4325       if (true_regnum (sum1) < 1 || true_regnum (sum1) > 15)
4326         {
4327           emit_move_insn (scratch, sum1);
4328           sum1 = scratch;
4329         }
4330       if (true_regnum (sum2) < 1 || true_regnum (sum2) > 15)
4331         {
4332           emit_move_insn (scratch, sum2);
4333           sum2 = scratch;
4334         }
4335
4336       /* According to the way these invalid addresses are generated
4337          in reload.c, it should never happen (at least on s390) that
4338          *neither* of the PLUS components, after find_replacements
4339          was applied, is an address register.  */
4340       if (sum1 == scratch && sum2 == scratch)
4341         {
4342           debug_rtx (src);
4343           gcc_unreachable ();
4344         }
4345
4346       src = gen_rtx_PLUS (Pmode, sum1, sum2);
4347     }
4348
4349   /* Emit the LOAD ADDRESS pattern.  Note that reload of PLUS
4350      is only ever performed on addresses, so we can mark the
4351      sum as legitimate for LA in any case.  */
4352   s390_load_address (target, src);
4353 }
4354
4355
4356 /* Return true if ADDR is a valid memory address.
4357    STRICT specifies whether strict register checking applies.  */
4358
4359 static bool
4360 s390_legitimate_address_p (machine_mode mode, rtx addr, bool strict)
4361 {
4362   struct s390_address ad;
4363
4364   if (TARGET_Z10
4365       && larl_operand (addr, VOIDmode)
4366       && (mode == VOIDmode
4367           || s390_check_symref_alignment (addr, GET_MODE_SIZE (mode))))
4368     return true;
4369
4370   if (!s390_decompose_address (addr, &ad))
4371     return false;
4372
4373   if (strict)
4374     {
4375       if (ad.base && !REGNO_OK_FOR_BASE_P (REGNO (ad.base)))
4376         return false;
4377
4378       if (ad.indx && !REGNO_OK_FOR_INDEX_P (REGNO (ad.indx)))
4379         return false;
4380     }
4381   else
4382     {
4383       if (ad.base
4384           && !(REGNO (ad.base) >= FIRST_PSEUDO_REGISTER
4385                || REGNO_REG_CLASS (REGNO (ad.base)) == ADDR_REGS))
4386         return false;
4387
4388       if (ad.indx
4389           && !(REGNO (ad.indx) >= FIRST_PSEUDO_REGISTER
4390                || REGNO_REG_CLASS (REGNO (ad.indx)) == ADDR_REGS))
4391           return false;
4392     }
4393   return true;
4394 }
4395
4396 /* Return true if OP is a valid operand for the LA instruction.
4397    In 31-bit, we need to prove that the result is used as an
4398    address, as LA performs only a 31-bit addition.  */
4399
4400 bool
4401 legitimate_la_operand_p (rtx op)
4402 {
4403   struct s390_address addr;
4404   if (!s390_decompose_address (op, &addr))
4405     return false;
4406
4407   return (TARGET_64BIT || addr.pointer);
4408 }
4409
4410 /* Return true if it is valid *and* preferable to use LA to
4411    compute the sum of OP1 and OP2.  */
4412
4413 bool
4414 preferred_la_operand_p (rtx op1, rtx op2)
4415 {
4416   struct s390_address addr;
4417
4418   if (op2 != const0_rtx)
4419     op1 = gen_rtx_PLUS (Pmode, op1, op2);
4420
4421   if (!s390_decompose_address (op1, &addr))
4422     return false;
4423   if (addr.base && !REGNO_OK_FOR_BASE_P (REGNO (addr.base)))
4424     return false;
4425   if (addr.indx && !REGNO_OK_FOR_INDEX_P (REGNO (addr.indx)))
4426     return false;
4427
4428   /* Avoid LA instructions with index register on z196; it is
4429      preferable to use regular add instructions when possible.
4430      Starting with zEC12 the la with index register is "uncracked"
4431      again.  */
4432   if (addr.indx && s390_tune == PROCESSOR_2817_Z196)
4433     return false;
4434
4435   if (!TARGET_64BIT && !addr.pointer)
4436     return false;
4437
4438   if (addr.pointer)
4439     return true;
4440
4441   if ((addr.base && REG_P (addr.base) && REG_POINTER (addr.base))
4442       || (addr.indx && REG_P (addr.indx) && REG_POINTER (addr.indx)))
4443     return true;
4444
4445   return false;
4446 }
4447
4448 /* Emit a forced load-address operation to load SRC into DST.
4449    This will use the LOAD ADDRESS instruction even in situations
4450    where legitimate_la_operand_p (SRC) returns false.  */
4451
4452 void
4453 s390_load_address (rtx dst, rtx src)
4454 {
4455   if (TARGET_64BIT)
4456     emit_move_insn (dst, src);
4457   else
4458     emit_insn (gen_force_la_31 (dst, src));
4459 }
4460
4461 /* Return a legitimate reference for ORIG (an address) using the
4462    register REG.  If REG is 0, a new pseudo is generated.
4463
4464    There are two types of references that must be handled:
4465
4466    1. Global data references must load the address from the GOT, via
4467       the PIC reg.  An insn is emitted to do this load, and the reg is
4468       returned.
4469
4470    2. Static data references, constant pool addresses, and code labels
4471       compute the address as an offset from the GOT, whose base is in
4472       the PIC reg.  Static data objects have SYMBOL_FLAG_LOCAL set to
4473       differentiate them from global data objects.  The returned
4474       address is the PIC reg + an unspec constant.
4475
4476    TARGET_LEGITIMIZE_ADDRESS_P rejects symbolic references unless the PIC
4477    reg also appears in the address.  */
4478
4479 rtx
4480 legitimize_pic_address (rtx orig, rtx reg)
4481 {
4482   rtx addr = orig;
4483   rtx addend = const0_rtx;
4484   rtx new_rtx = orig;
4485
4486   gcc_assert (!TLS_SYMBOLIC_CONST (addr));
4487
4488   if (GET_CODE (addr) == CONST)
4489     addr = XEXP (addr, 0);
4490
4491   if (GET_CODE (addr) == PLUS)
4492     {
4493       addend = XEXP (addr, 1);
4494       addr = XEXP (addr, 0);
4495     }
4496
4497   if ((GET_CODE (addr) == LABEL_REF
4498        || (GET_CODE (addr) == SYMBOL_REF && SYMBOL_REF_LOCAL_P (addr))
4499        || (GET_CODE (addr) == UNSPEC &&
4500            (XINT (addr, 1) == UNSPEC_GOTENT
4501             || (TARGET_CPU_ZARCH && XINT (addr, 1) == UNSPEC_PLT))))
4502       && GET_CODE (addend) == CONST_INT)
4503     {
4504       /* This can be locally addressed.  */
4505
4506       /* larl_operand requires UNSPECs to be wrapped in a const rtx.  */
4507       rtx const_addr = (GET_CODE (addr) == UNSPEC ?
4508                         gen_rtx_CONST (Pmode, addr) : addr);
4509
4510       if (TARGET_CPU_ZARCH
4511           && larl_operand (const_addr, VOIDmode)
4512           && INTVAL (addend) < HOST_WIDE_INT_1 << 31
4513           && INTVAL (addend) >= -(HOST_WIDE_INT_1 << 31))
4514         {
4515           if (INTVAL (addend) & 1)
4516             {
4517               /* LARL can't handle odd offsets, so emit a pair of LARL
4518                  and LA.  */
4519               rtx temp = reg? reg : gen_reg_rtx (Pmode);
4520
4521               if (!DISP_IN_RANGE (INTVAL (addend)))
4522                 {
4523                   HOST_WIDE_INT even = INTVAL (addend) - 1;
4524                   addr = gen_rtx_PLUS (Pmode, addr, GEN_INT (even));
4525                   addr = gen_rtx_CONST (Pmode, addr);
4526                   addend = const1_rtx;
4527                 }
4528
4529               emit_move_insn (temp, addr);
4530               new_rtx = gen_rtx_PLUS (Pmode, temp, addend);
4531
4532               if (reg != 0)
4533                 {
4534                   s390_load_address (reg, new_rtx);
4535                   new_rtx = reg;
4536                 }
4537             }
4538           else
4539             {
4540               /* If the offset is even, we can just use LARL.  This
4541                  will happen automatically.  */
4542             }
4543         }
4544       else
4545         {
4546           /* No larl - Access local symbols relative to the GOT.  */
4547
4548           rtx temp = reg? reg : gen_reg_rtx (Pmode);
4549
4550           if (reload_in_progress || reload_completed)
4551             df_set_regs_ever_live (PIC_OFFSET_TABLE_REGNUM, true);
4552
4553           addr = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, addr), UNSPEC_GOTOFF);
4554           if (addend != const0_rtx)
4555             addr = gen_rtx_PLUS (Pmode, addr, addend);
4556           addr = gen_rtx_CONST (Pmode, addr);
4557           addr = force_const_mem (Pmode, addr);
4558           emit_move_insn (temp, addr);
4559
4560           new_rtx = gen_rtx_PLUS (Pmode, pic_offset_table_rtx, temp);
4561           if (reg != 0)
4562             {
4563               s390_load_address (reg, new_rtx);
4564               new_rtx = reg;
4565             }
4566         }
4567     }
4568   else if (GET_CODE (addr) == SYMBOL_REF && addend == const0_rtx)
4569     {
4570       /* A non-local symbol reference without addend.
4571
4572          The symbol ref is wrapped into an UNSPEC to make sure the
4573          proper operand modifier (@GOT or @GOTENT) will be emitted.
4574          This will tell the linker to put the symbol into the GOT.
4575
4576          Additionally the code dereferencing the GOT slot is emitted here.
4577
4578          An addend to the symref needs to be added afterwards.
4579          legitimize_pic_address calls itself recursively to handle
4580          that case.  So no need to do it here.  */
4581
4582       if (reg == 0)
4583         reg = gen_reg_rtx (Pmode);
4584
4585       if (TARGET_Z10)
4586         {
4587           /* Use load relative if possible.
4588              lgrl <target>, sym@GOTENT  */
4589           new_rtx = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, addr), UNSPEC_GOTENT);
4590           new_rtx = gen_rtx_CONST (Pmode, new_rtx);
4591           new_rtx = gen_const_mem (GET_MODE (reg), new_rtx);
4592
4593           emit_move_insn (reg, new_rtx);
4594           new_rtx = reg;
4595         }
4596       else if (flag_pic == 1)
4597         {
4598           /* Assume GOT offset is a valid displacement operand (< 4k
4599              or < 512k with z990).  This is handled the same way in
4600              both 31- and 64-bit code (@GOT).
4601              lg <target>, sym@GOT(r12)  */
4602
4603           if (reload_in_progress || reload_completed)
4604             df_set_regs_ever_live (PIC_OFFSET_TABLE_REGNUM, true);
4605
4606           new_rtx = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, addr), UNSPEC_GOT);
4607           new_rtx = gen_rtx_CONST (Pmode, new_rtx);
4608           new_rtx = gen_rtx_PLUS (Pmode, pic_offset_table_rtx, new_rtx);
4609           new_rtx = gen_const_mem (Pmode, new_rtx);
4610           emit_move_insn (reg, new_rtx);
4611           new_rtx = reg;
4612         }
4613       else if (TARGET_CPU_ZARCH)
4614         {
4615           /* If the GOT offset might be >= 4k, we determine the position
4616              of the GOT entry via a PC-relative LARL (@GOTENT).
4617              larl temp, sym@GOTENT
4618              lg   <target>, 0(temp) */
4619
4620           rtx temp = reg ? reg : gen_reg_rtx (Pmode);
4621
4622           gcc_assert (REGNO (temp) >= FIRST_PSEUDO_REGISTER
4623                       || REGNO_REG_CLASS (REGNO (temp)) == ADDR_REGS);
4624
4625           new_rtx = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, addr), UNSPEC_GOTENT);
4626           new_rtx = gen_rtx_CONST (Pmode, new_rtx);
4627           emit_move_insn (temp, new_rtx);
4628
4629           new_rtx = gen_const_mem (Pmode, temp);
4630           emit_move_insn (reg, new_rtx);
4631
4632           new_rtx = reg;
4633         }
4634       else
4635         {
4636           /* If the GOT offset might be >= 4k, we have to load it
4637              from the literal pool (@GOT).
4638
4639              lg temp, lit-litbase(r13)
4640              lg <target>, 0(temp)
4641              lit:  .long sym@GOT  */
4642
4643           rtx temp = reg ? reg : gen_reg_rtx (Pmode);
4644
4645           gcc_assert (REGNO (temp) >= FIRST_PSEUDO_REGISTER
4646                       || REGNO_REG_CLASS (REGNO (temp)) == ADDR_REGS);
4647
4648           if (reload_in_progress || reload_completed)
4649             df_set_regs_ever_live (PIC_OFFSET_TABLE_REGNUM, true);
4650
4651           addr = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, addr), UNSPEC_GOT);
4652           addr = gen_rtx_CONST (Pmode, addr);
4653           addr = force_const_mem (Pmode, addr);
4654           emit_move_insn (temp, addr);
4655
4656           new_rtx = gen_rtx_PLUS (Pmode, pic_offset_table_rtx, temp);
4657           new_rtx = gen_const_mem (Pmode, new_rtx);
4658           emit_move_insn (reg, new_rtx);
4659           new_rtx = reg;
4660         }
4661     }
4662   else if (GET_CODE (addr) == UNSPEC && GET_CODE (addend) == CONST_INT)
4663     {
4664       gcc_assert (XVECLEN (addr, 0) == 1);
4665       switch (XINT (addr, 1))
4666         {
4667           /* These address symbols (or PLT slots) relative to the GOT
4668              (not GOT slots!).  In general this will exceed the
4669              displacement range so these value belong into the literal
4670              pool.  */
4671         case UNSPEC_GOTOFF:
4672         case UNSPEC_PLTOFF:
4673           new_rtx = force_const_mem (Pmode, orig);
4674           break;
4675
4676           /* For -fPIC the GOT size might exceed the displacement
4677              range so make sure the value is in the literal pool.  */
4678         case UNSPEC_GOT:
4679           if (flag_pic == 2)
4680             new_rtx = force_const_mem (Pmode, orig);
4681           break;
4682
4683           /* For @GOTENT larl is used.  This is handled like local
4684              symbol refs.  */
4685         case UNSPEC_GOTENT:
4686           gcc_unreachable ();
4687           break;
4688
4689           /* @PLT is OK as is on 64-bit, must be converted to
4690              GOT-relative @PLTOFF on 31-bit.  */
4691         case UNSPEC_PLT:
4692           if (!TARGET_CPU_ZARCH)
4693             {
4694               rtx temp = reg? reg : gen_reg_rtx (Pmode);
4695
4696               if (reload_in_progress || reload_completed)
4697                 df_set_regs_ever_live (PIC_OFFSET_TABLE_REGNUM, true);
4698
4699               addr = XVECEXP (addr, 0, 0);
4700               addr = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, addr),
4701                                      UNSPEC_PLTOFF);
4702               if (addend != const0_rtx)
4703                 addr = gen_rtx_PLUS (Pmode, addr, addend);
4704               addr = gen_rtx_CONST (Pmode, addr);
4705               addr = force_const_mem (Pmode, addr);
4706               emit_move_insn (temp, addr);
4707
4708               new_rtx = gen_rtx_PLUS (Pmode, pic_offset_table_rtx, temp);
4709               if (reg != 0)
4710                 {
4711                   s390_load_address (reg, new_rtx);
4712                   new_rtx = reg;
4713                 }
4714             }
4715           else
4716             /* On 64 bit larl can be used.  This case is handled like
4717                local symbol refs.  */
4718             gcc_unreachable ();
4719           break;
4720
4721           /* Everything else cannot happen.  */
4722         default:
4723           gcc_unreachable ();
4724         }
4725     }
4726   else if (addend != const0_rtx)
4727     {
4728       /* Otherwise, compute the sum.  */
4729
4730       rtx base = legitimize_pic_address (addr, reg);
4731       new_rtx  = legitimize_pic_address (addend,
4732                                          base == reg ? NULL_RTX : reg);
4733       if (GET_CODE (new_rtx) == CONST_INT)
4734         new_rtx = plus_constant (Pmode, base, INTVAL (new_rtx));
4735       else
4736         {
4737           if (GET_CODE (new_rtx) == PLUS && CONSTANT_P (XEXP (new_rtx, 1)))
4738             {
4739               base = gen_rtx_PLUS (Pmode, base, XEXP (new_rtx, 0));
4740               new_rtx = XEXP (new_rtx, 1);
4741             }
4742           new_rtx = gen_rtx_PLUS (Pmode, base, new_rtx);
4743         }
4744
4745       if (GET_CODE (new_rtx) == CONST)
4746         new_rtx = XEXP (new_rtx, 0);
4747       new_rtx = force_operand (new_rtx, 0);
4748     }
4749
4750   return new_rtx;
4751 }
4752
4753 /* Load the thread pointer into a register.  */
4754
4755 rtx
4756 s390_get_thread_pointer (void)
4757 {
4758   rtx tp = gen_reg_rtx (Pmode);
4759
4760   emit_move_insn (tp, gen_rtx_REG (Pmode, TP_REGNUM));
4761   mark_reg_pointer (tp, BITS_PER_WORD);
4762
4763   return tp;
4764 }
4765
4766 /* Emit a tls call insn. The call target is the SYMBOL_REF stored
4767    in s390_tls_symbol which always refers to __tls_get_offset.
4768    The returned offset is written to RESULT_REG and an USE rtx is
4769    generated for TLS_CALL.  */
4770
4771 static GTY(()) rtx s390_tls_symbol;
4772
4773 static void
4774 s390_emit_tls_call_insn (rtx result_reg, rtx tls_call)
4775 {
4776   rtx insn;
4777
4778   if (!flag_pic)
4779     emit_insn (s390_load_got ());
4780
4781   if (!s390_tls_symbol)
4782     s390_tls_symbol = gen_rtx_SYMBOL_REF (Pmode, "__tls_get_offset");
4783
4784   insn = s390_emit_call (s390_tls_symbol, tls_call, result_reg,
4785                          gen_rtx_REG (Pmode, RETURN_REGNUM));
4786
4787   use_reg (&CALL_INSN_FUNCTION_USAGE (insn), result_reg);
4788   RTL_CONST_CALL_P (insn) = 1;
4789 }
4790
4791 /* ADDR contains a thread-local SYMBOL_REF.  Generate code to compute
4792    this (thread-local) address.  REG may be used as temporary.  */
4793
4794 static rtx
4795 legitimize_tls_address (rtx addr, rtx reg)
4796 {
4797   rtx new_rtx, tls_call, temp, base, r2;
4798   rtx_insn *insn;
4799
4800   if (GET_CODE (addr) == SYMBOL_REF)
4801     switch (tls_symbolic_operand (addr))
4802       {
4803       case TLS_MODEL_GLOBAL_DYNAMIC:
4804         start_sequence ();
4805         r2 = gen_rtx_REG (Pmode, 2);
4806         tls_call = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, addr), UNSPEC_TLSGD);
4807         new_rtx = gen_rtx_CONST (Pmode, tls_call);
4808         new_rtx = force_const_mem (Pmode, new_rtx);
4809         emit_move_insn (r2, new_rtx);
4810         s390_emit_tls_call_insn (r2, tls_call);
4811         insn = get_insns ();
4812         end_sequence ();
4813
4814         new_rtx = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, addr), UNSPEC_NTPOFF);
4815         temp = gen_reg_rtx (Pmode);
4816         emit_libcall_block (insn, temp, r2, new_rtx);
4817
4818         new_rtx = gen_rtx_PLUS (Pmode, s390_get_thread_pointer (), temp);
4819         if (reg != 0)
4820           {
4821             s390_load_address (reg, new_rtx);
4822             new_rtx = reg;
4823           }
4824         break;
4825
4826       case TLS_MODEL_LOCAL_DYNAMIC:
4827         start_sequence ();
4828         r2 = gen_rtx_REG (Pmode, 2);
4829         tls_call = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, const0_rtx), UNSPEC_TLSLDM);
4830         new_rtx = gen_rtx_CONST (Pmode, tls_call);
4831         new_rtx = force_const_mem (Pmode, new_rtx);
4832         emit_move_insn (r2, new_rtx);
4833         s390_emit_tls_call_insn (r2, tls_call);
4834         insn = get_insns ();
4835         end_sequence ();
4836
4837         new_rtx = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, const0_rtx), UNSPEC_TLSLDM_NTPOFF);
4838         temp = gen_reg_rtx (Pmode);
4839         emit_libcall_block (insn, temp, r2, new_rtx);
4840
4841         new_rtx = gen_rtx_PLUS (Pmode, s390_get_thread_pointer (), temp);
4842         base = gen_reg_rtx (Pmode);
4843         s390_load_address (base, new_rtx);
4844
4845         new_rtx = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, addr), UNSPEC_DTPOFF);
4846         new_rtx = gen_rtx_CONST (Pmode, new_rtx);
4847         new_rtx = force_const_mem (Pmode, new_rtx);
4848         temp = gen_reg_rtx (Pmode);
4849         emit_move_insn (temp, new_rtx);
4850
4851         new_rtx = gen_rtx_PLUS (Pmode, base, temp);
4852         if (reg != 0)
4853           {
4854             s390_load_address (reg, new_rtx);
4855             new_rtx = reg;
4856           }
4857         break;
4858
4859       case TLS_MODEL_INITIAL_EXEC:
4860         if (flag_pic == 1)
4861           {
4862             /* Assume GOT offset < 4k.  This is handled the same way
4863                in both 31- and 64-bit code.  */
4864
4865             if (reload_in_progress || reload_completed)
4866               df_set_regs_ever_live (PIC_OFFSET_TABLE_REGNUM, true);
4867
4868             new_rtx = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, addr), UNSPEC_GOTNTPOFF);
4869             new_rtx = gen_rtx_CONST (Pmode, new_rtx);
4870             new_rtx = gen_rtx_PLUS (Pmode, pic_offset_table_rtx, new_rtx);
4871             new_rtx = gen_const_mem (Pmode, new_rtx);
4872             temp = gen_reg_rtx (Pmode);
4873             emit_move_insn (temp, new_rtx);
4874           }
4875         else if (TARGET_CPU_ZARCH)
4876           {
4877             /* If the GOT offset might be >= 4k, we determine the position
4878                of the GOT entry via a PC-relative LARL.  */
4879
4880             new_rtx = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, addr), UNSPEC_INDNTPOFF);
4881             new_rtx = gen_rtx_CONST (Pmode, new_rtx);
4882             temp = gen_reg_rtx (Pmode);
4883             emit_move_insn (temp, new_rtx);
4884
4885             new_rtx = gen_const_mem (Pmode, temp);
4886             temp = gen_reg_rtx (Pmode);
4887             emit_move_insn (temp, new_rtx);
4888           }
4889         else if (flag_pic)
4890           {
4891             /* If the GOT offset might be >= 4k, we have to load it
4892                from the literal pool.  */
4893
4894             if (reload_in_progress || reload_completed)
4895               df_set_regs_ever_live (PIC_OFFSET_TABLE_REGNUM, true);
4896
4897             new_rtx = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, addr), UNSPEC_GOTNTPOFF);
4898             new_rtx = gen_rtx_CONST (Pmode, new_rtx);
4899             new_rtx = force_const_mem (Pmode, new_rtx);
4900             temp = gen_reg_rtx (Pmode);
4901             emit_move_insn (temp, new_rtx);
4902
4903             new_rtx = gen_rtx_PLUS (Pmode, pic_offset_table_rtx, temp);
4904             new_rtx = gen_const_mem (Pmode, new_rtx);
4905
4906             new_rtx = gen_rtx_UNSPEC (Pmode, gen_rtvec (2, new_rtx, addr), UNSPEC_TLS_LOAD);
4907             temp = gen_reg_rtx (Pmode);
4908             emit_insn (gen_rtx_SET (temp, new_rtx));
4909           }
4910         else
4911           {
4912             /* In position-dependent code, load the absolute address of
4913                the GOT entry from the literal pool.  */
4914
4915             new_rtx = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, addr), UNSPEC_INDNTPOFF);
4916             new_rtx = gen_rtx_CONST (Pmode, new_rtx);
4917             new_rtx = force_const_mem (Pmode, new_rtx);
4918             temp = gen_reg_rtx (Pmode);
4919             emit_move_insn (temp, new_rtx);
4920
4921             new_rtx = temp;
4922             new_rtx = gen_const_mem (Pmode, new_rtx);
4923             new_rtx = gen_rtx_UNSPEC (Pmode, gen_rtvec (2, new_rtx, addr), UNSPEC_TLS_LOAD);
4924             temp = gen_reg_rtx (Pmode);
4925             emit_insn (gen_rtx_SET (temp, new_rtx));
4926           }
4927
4928         new_rtx = gen_rtx_PLUS (Pmode, s390_get_thread_pointer (), temp);
4929         if (reg != 0)
4930           {
4931             s390_load_address (reg, new_rtx);
4932             new_rtx = reg;
4933           }
4934         break;
4935
4936       case TLS_MODEL_LOCAL_EXEC:
4937         new_rtx = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, addr), UNSPEC_NTPOFF);
4938         new_rtx = gen_rtx_CONST (Pmode, new_rtx);
4939         new_rtx = force_const_mem (Pmode, new_rtx);
4940         temp = gen_reg_rtx (Pmode);
4941         emit_move_insn (temp, new_rtx);
4942
4943         new_rtx = gen_rtx_PLUS (Pmode, s390_get_thread_pointer (), temp);
4944         if (reg != 0)
4945           {
4946             s390_load_address (reg, new_rtx);
4947             new_rtx = reg;
4948           }
4949         break;
4950
4951       default:
4952         gcc_unreachable ();
4953       }
4954
4955   else if (GET_CODE (addr) == CONST && GET_CODE (XEXP (addr, 0)) == UNSPEC)
4956     {
4957       switch (XINT (XEXP (addr, 0), 1))
4958         {
4959         case UNSPEC_INDNTPOFF:
4960           gcc_assert (TARGET_CPU_ZARCH);
4961           new_rtx = addr;
4962           break;
4963
4964         default:
4965           gcc_unreachable ();
4966         }
4967     }
4968
4969   else if (GET_CODE (addr) == CONST && GET_CODE (XEXP (addr, 0)) == PLUS
4970            && GET_CODE (XEXP (XEXP (addr, 0), 1)) == CONST_INT)
4971     {
4972       new_rtx = XEXP (XEXP (addr, 0), 0);
4973       if (GET_CODE (new_rtx) != SYMBOL_REF)
4974         new_rtx = gen_rtx_CONST (Pmode, new_rtx);
4975
4976       new_rtx = legitimize_tls_address (new_rtx, reg);
4977       new_rtx = plus_constant (Pmode, new_rtx,
4978                                INTVAL (XEXP (XEXP (addr, 0), 1)));
4979       new_rtx = force_operand (new_rtx, 0);
4980     }
4981
4982   else
4983     gcc_unreachable ();  /* for now ... */
4984
4985   return new_rtx;
4986 }
4987
4988 /* Emit insns making the address in operands[1] valid for a standard
4989    move to operands[0].  operands[1] is replaced by an address which
4990    should be used instead of the former RTX to emit the move
4991    pattern.  */
4992
4993 void
4994 emit_symbolic_move (rtx *operands)
4995 {
4996   rtx temp = !can_create_pseudo_p () ? operands[0] : gen_reg_rtx (Pmode);
4997
4998   if (GET_CODE (operands[0]) == MEM)
4999     operands[1] = force_reg (Pmode, operands[1]);
5000   else if (TLS_SYMBOLIC_CONST (operands[1]))
5001     operands[1] = legitimize_tls_address (operands[1], temp);
5002   else if (flag_pic)
5003     operands[1] = legitimize_pic_address (operands[1], temp);
5004 }
5005
5006 /* Try machine-dependent ways of modifying an illegitimate address X
5007    to be legitimate.  If we find one, return the new, valid address.
5008
5009    OLDX is the address as it was before break_out_memory_refs was called.
5010    In some cases it is useful to look at this to decide what needs to be done.
5011
5012    MODE is the mode of the operand pointed to by X.
5013
5014    When -fpic is used, special handling is needed for symbolic references.
5015    See comments by legitimize_pic_address for details.  */
5016
5017 static rtx
5018 s390_legitimize_address (rtx x, rtx oldx ATTRIBUTE_UNUSED,
5019                          machine_mode mode ATTRIBUTE_UNUSED)
5020 {
5021   rtx constant_term = const0_rtx;
5022
5023   if (TLS_SYMBOLIC_CONST (x))
5024     {
5025       x = legitimize_tls_address (x, 0);
5026
5027       if (s390_legitimate_address_p (mode, x, FALSE))
5028         return x;
5029     }
5030   else if (GET_CODE (x) == PLUS
5031            && (TLS_SYMBOLIC_CONST (XEXP (x, 0))
5032                || TLS_SYMBOLIC_CONST (XEXP (x, 1))))
5033     {
5034       return x;
5035     }
5036   else if (flag_pic)
5037     {
5038       if (SYMBOLIC_CONST (x)
5039           || (GET_CODE (x) == PLUS
5040               && (SYMBOLIC_CONST (XEXP (x, 0))
5041                   || SYMBOLIC_CONST (XEXP (x, 1)))))
5042           x = legitimize_pic_address (x, 0);
5043
5044       if (s390_legitimate_address_p (mode, x, FALSE))
5045         return x;
5046     }
5047
5048   x = eliminate_constant_term (x, &constant_term);
5049
5050   /* Optimize loading of large displacements by splitting them
5051      into the multiple of 4K and the rest; this allows the
5052      former to be CSE'd if possible.
5053
5054      Don't do this if the displacement is added to a register
5055      pointing into the stack frame, as the offsets will
5056      change later anyway.  */
5057
5058   if (GET_CODE (constant_term) == CONST_INT
5059       && !TARGET_LONG_DISPLACEMENT
5060       && !DISP_IN_RANGE (INTVAL (constant_term))
5061       && !(REG_P (x) && REGNO_PTR_FRAME_P (REGNO (x))))
5062     {
5063       HOST_WIDE_INT lower = INTVAL (constant_term) & 0xfff;
5064       HOST_WIDE_INT upper = INTVAL (constant_term) ^ lower;
5065
5066       rtx temp = gen_reg_rtx (Pmode);
5067       rtx val  = force_operand (GEN_INT (upper), temp);
5068       if (val != temp)
5069         emit_move_insn (temp, val);
5070
5071       x = gen_rtx_PLUS (Pmode, x, temp);
5072       constant_term = GEN_INT (lower);
5073     }
5074
5075   if (GET_CODE (x) == PLUS)
5076     {
5077       if (GET_CODE (XEXP (x, 0)) == REG)
5078         {
5079           rtx temp = gen_reg_rtx (Pmode);
5080           rtx val  = force_operand (XEXP (x, 1), temp);
5081           if (val != temp)
5082             emit_move_insn (temp, val);
5083
5084           x = gen_rtx_PLUS (Pmode, XEXP (x, 0), temp);
5085         }
5086
5087       else if (GET_CODE (XEXP (x, 1)) == REG)
5088         {
5089           rtx temp = gen_reg_rtx (Pmode);
5090           rtx val  = force_operand (XEXP (x, 0), temp);
5091           if (val != temp)
5092             emit_move_insn (temp, val);
5093
5094           x = gen_rtx_PLUS (Pmode, temp, XEXP (x, 1));
5095         }
5096     }
5097
5098   if (constant_term != const0_rtx)
5099     x = gen_rtx_PLUS (Pmode, x, constant_term);
5100
5101   return x;
5102 }
5103
5104 /* Try a machine-dependent way of reloading an illegitimate address AD
5105    operand.  If we find one, push the reload and return the new address.
5106
5107    MODE is the mode of the enclosing MEM.  OPNUM is the operand number
5108    and TYPE is the reload type of the current reload.  */
5109
5110 rtx
5111 legitimize_reload_address (rtx ad, machine_mode mode ATTRIBUTE_UNUSED,
5112                            int opnum, int type)
5113 {
5114   if (!optimize || TARGET_LONG_DISPLACEMENT)
5115     return NULL_RTX;
5116
5117   if (GET_CODE (ad) == PLUS)
5118     {
5119       rtx tem = simplify_binary_operation (PLUS, Pmode,
5120                                            XEXP (ad, 0), XEXP (ad, 1));
5121       if (tem)
5122         ad = tem;
5123     }
5124
5125   if (GET_CODE (ad) == PLUS
5126       && GET_CODE (XEXP (ad, 0)) == REG
5127       && GET_CODE (XEXP (ad, 1)) == CONST_INT
5128       && !DISP_IN_RANGE (INTVAL (XEXP (ad, 1))))
5129     {
5130       HOST_WIDE_INT lower = INTVAL (XEXP (ad, 1)) & 0xfff;
5131       HOST_WIDE_INT upper = INTVAL (XEXP (ad, 1)) ^ lower;
5132       rtx cst, tem, new_rtx;
5133
5134       cst = GEN_INT (upper);
5135       if (!legitimate_reload_constant_p (cst))
5136         cst = force_const_mem (Pmode, cst);
5137
5138       tem = gen_rtx_PLUS (Pmode, XEXP (ad, 0), cst);
5139       new_rtx = gen_rtx_PLUS (Pmode, tem, GEN_INT (lower));
5140
5141       push_reload (XEXP (tem, 1), 0, &XEXP (tem, 1), 0,
5142                    BASE_REG_CLASS, Pmode, VOIDmode, 0, 0,
5143                    opnum, (enum reload_type) type);
5144       return new_rtx;
5145     }
5146
5147   return NULL_RTX;
5148 }
5149
5150 /* Emit code to move LEN bytes from DST to SRC.  */
5151
5152 bool
5153 s390_expand_movmem (rtx dst, rtx src, rtx len)
5154 {
5155   /* When tuning for z10 or higher we rely on the Glibc functions to
5156      do the right thing. Only for constant lengths below 64k we will
5157      generate inline code.  */
5158   if (s390_tune >= PROCESSOR_2097_Z10
5159       && (GET_CODE (len) != CONST_INT || INTVAL (len) > (1<<16)))
5160     return false;
5161
5162   /* Expand memcpy for constant length operands without a loop if it
5163      is shorter that way.
5164
5165      With a constant length argument a
5166      memcpy loop (without pfd) is 36 bytes -> 6 * mvc  */
5167   if (GET_CODE (len) == CONST_INT
5168       && INTVAL (len) >= 0
5169       && INTVAL (len) <= 256 * 6
5170       && (!TARGET_MVCLE || INTVAL (len) <= 256))
5171     {
5172       HOST_WIDE_INT o, l;
5173
5174       for (l = INTVAL (len), o = 0; l > 0; l -= 256, o += 256)
5175         {
5176           rtx newdst = adjust_address (dst, BLKmode, o);
5177           rtx newsrc = adjust_address (src, BLKmode, o);
5178           emit_insn (gen_movmem_short (newdst, newsrc,
5179                                        GEN_INT (l > 256 ? 255 : l - 1)));
5180         }
5181     }
5182
5183   else if (TARGET_MVCLE)
5184     {
5185       emit_insn (gen_movmem_long (dst, src, convert_to_mode (Pmode, len, 1)));
5186     }
5187
5188   else
5189     {
5190       rtx dst_addr, src_addr, count, blocks, temp;
5191       rtx_code_label *loop_start_label = gen_label_rtx ();
5192       rtx_code_label *loop_end_label = gen_label_rtx ();
5193       rtx_code_label *end_label = gen_label_rtx ();
5194       machine_mode mode;
5195
5196       mode = GET_MODE (len);
5197       if (mode == VOIDmode)
5198         mode = Pmode;
5199
5200       dst_addr = gen_reg_rtx (Pmode);
5201       src_addr = gen_reg_rtx (Pmode);
5202       count = gen_reg_rtx (mode);
5203       blocks = gen_reg_rtx (mode);
5204
5205       convert_move (count, len, 1);
5206       emit_cmp_and_jump_insns (count, const0_rtx,
5207                                EQ, NULL_RTX, mode, 1, end_label);
5208
5209       emit_move_insn (dst_addr, force_operand (XEXP (dst, 0), NULL_RTX));
5210       emit_move_insn (src_addr, force_operand (XEXP (src, 0), NULL_RTX));
5211       dst = change_address (dst, VOIDmode, dst_addr);
5212       src = change_address (src, VOIDmode, src_addr);
5213
5214       temp = expand_binop (mode, add_optab, count, constm1_rtx, count, 1,
5215                            OPTAB_DIRECT);
5216       if (temp != count)
5217         emit_move_insn (count, temp);
5218
5219       temp = expand_binop (mode, lshr_optab, count, GEN_INT (8), blocks, 1,
5220                            OPTAB_DIRECT);
5221       if (temp != blocks)
5222         emit_move_insn (blocks, temp);
5223
5224       emit_cmp_and_jump_insns (blocks, const0_rtx,
5225                                EQ, NULL_RTX, mode, 1, loop_end_label);
5226
5227       emit_label (loop_start_label);
5228
5229       if (TARGET_Z10
5230           && (GET_CODE (len) != CONST_INT || INTVAL (len) > 768))
5231         {
5232           rtx prefetch;
5233
5234           /* Issue a read prefetch for the +3 cache line.  */
5235           prefetch = gen_prefetch (gen_rtx_PLUS (Pmode, src_addr, GEN_INT (768)),
5236                                    const0_rtx, const0_rtx);
5237           PREFETCH_SCHEDULE_BARRIER_P (prefetch) = true;
5238           emit_insn (prefetch);
5239
5240           /* Issue a write prefetch for the +3 cache line.  */
5241           prefetch = gen_prefetch (gen_rtx_PLUS (Pmode, dst_addr, GEN_INT (768)),
5242                                    const1_rtx, const0_rtx);
5243           PREFETCH_SCHEDULE_BARRIER_P (prefetch) = true;
5244           emit_insn (prefetch);
5245         }
5246
5247       emit_insn (gen_movmem_short (dst, src, GEN_INT (255)));
5248       s390_load_address (dst_addr,
5249                          gen_rtx_PLUS (Pmode, dst_addr, GEN_INT (256)));
5250       s390_load_address (src_addr,
5251                          gen_rtx_PLUS (Pmode, src_addr, GEN_INT (256)));
5252
5253       temp = expand_binop (mode, add_optab, blocks, constm1_rtx, blocks, 1,
5254                            OPTAB_DIRECT);
5255       if (temp != blocks)
5256         emit_move_insn (blocks, temp);
5257
5258       emit_cmp_and_jump_insns (blocks, const0_rtx,
5259                                EQ, NULL_RTX, mode, 1, loop_end_label);
5260
5261       emit_jump (loop_start_label);
5262       emit_label (loop_end_label);
5263
5264       emit_insn (gen_movmem_short (dst, src,
5265                                    convert_to_mode (Pmode, count, 1)));
5266       emit_label (end_label);
5267     }
5268   return true;
5269 }
5270
5271 /* Emit code to set LEN bytes at DST to VAL.
5272    Make use of clrmem if VAL is zero.  */
5273
5274 void
5275 s390_expand_setmem (rtx dst, rtx len, rtx val)
5276 {
5277   const int very_unlikely = REG_BR_PROB_BASE / 100 - 1;
5278
5279   if (GET_CODE (len) == CONST_INT && INTVAL (len) <= 0)
5280     return;
5281
5282   gcc_assert (GET_CODE (val) == CONST_INT || GET_MODE (val) == QImode);
5283
5284   /* Expand setmem/clrmem for a constant length operand without a
5285      loop if it will be shorter that way.
5286      With a constant length and without pfd argument a
5287      clrmem loop is 32 bytes -> 5.3 * xc
5288      setmem loop is 36 bytes -> 3.6 * (mvi/stc + mvc) */
5289   if (GET_CODE (len) == CONST_INT
5290       && ((INTVAL (len) <= 256 * 5 && val == const0_rtx)
5291           || INTVAL (len) <= 257 * 3)
5292       && (!TARGET_MVCLE || INTVAL (len) <= 256))
5293     {
5294       HOST_WIDE_INT o, l;
5295
5296       if (val == const0_rtx)
5297         /* clrmem: emit 256 byte blockwise XCs.  */
5298         for (l = INTVAL (len), o = 0; l > 0; l -= 256, o += 256)
5299           {
5300             rtx newdst = adjust_address (dst, BLKmode, o);
5301             emit_insn (gen_clrmem_short (newdst,
5302                                          GEN_INT (l > 256 ? 255 : l - 1)));
5303           }
5304       else
5305         /* setmem: emit 1(mvi) + 256(mvc) byte blockwise memsets by
5306            setting first byte to val and using a 256 byte mvc with one
5307            byte overlap to propagate the byte.  */
5308         for (l = INTVAL (len), o = 0; l > 0; l -= 257, o += 257)
5309           {
5310             rtx newdst = adjust_address (dst, BLKmode, o);
5311             emit_move_insn (adjust_address (dst, QImode, o), val);
5312             if (l > 1)
5313               {
5314                 rtx newdstp1 = adjust_address (dst, BLKmode, o + 1);
5315                 emit_insn (gen_movmem_short (newdstp1, newdst,
5316                                              GEN_INT (l > 257 ? 255 : l - 2)));
5317               }
5318           }
5319     }
5320
5321   else if (TARGET_MVCLE)
5322     {
5323       val = force_not_mem (convert_modes (Pmode, QImode, val, 1));
5324       if (TARGET_64BIT)
5325         emit_insn (gen_setmem_long_di (dst, convert_to_mode (Pmode, len, 1),
5326                                        val));
5327       else
5328         emit_insn (gen_setmem_long_si (dst, convert_to_mode (Pmode, len, 1),
5329                                        val));
5330     }
5331
5332   else
5333     {
5334       rtx dst_addr, count, blocks, temp, dstp1 = NULL_RTX;
5335       rtx_code_label *loop_start_label = gen_label_rtx ();
5336       rtx_code_label *onebyte_end_label = gen_label_rtx ();
5337       rtx_code_label *zerobyte_end_label = gen_label_rtx ();
5338       rtx_code_label *restbyte_end_label = gen_label_rtx ();
5339       machine_mode mode;
5340
5341       mode = GET_MODE (len);
5342       if (mode == VOIDmode)
5343         mode = Pmode;
5344
5345       dst_addr = gen_reg_rtx (Pmode);
5346       count = gen_reg_rtx (mode);
5347       blocks = gen_reg_rtx (mode);
5348
5349       convert_move (count, len, 1);
5350       emit_cmp_and_jump_insns (count, const0_rtx,
5351                                EQ, NULL_RTX, mode, 1, zerobyte_end_label,
5352                                very_unlikely);
5353
5354       /* We need to make a copy of the target address since memset is
5355          supposed to return it unmodified.  We have to make it here
5356          already since the new reg is used at onebyte_end_label.  */
5357       emit_move_insn (dst_addr, force_operand (XEXP (dst, 0), NULL_RTX));
5358       dst = change_address (dst, VOIDmode, dst_addr);
5359
5360       if (val != const0_rtx)
5361         {
5362           /* When using the overlapping mvc the original target
5363              address is only accessed as single byte entity (even by
5364              the mvc reading this value).  */
5365           set_mem_size (dst, 1);
5366           dstp1 = adjust_address (dst, VOIDmode, 1);
5367           emit_cmp_and_jump_insns (count,
5368                                    const1_rtx, EQ, NULL_RTX, mode, 1,
5369                                    onebyte_end_label, very_unlikely);
5370         }
5371
5372       /* There is one unconditional (mvi+mvc)/xc after the loop
5373          dealing with the rest of the bytes, subtracting two (mvi+mvc)
5374          or one (xc) here leaves this number of bytes to be handled by
5375          it.  */
5376       temp = expand_binop (mode, add_optab, count,
5377                            val == const0_rtx ? constm1_rtx : GEN_INT (-2),
5378                            count, 1, OPTAB_DIRECT);
5379       if (temp != count)
5380         emit_move_insn (count, temp);
5381
5382       temp = expand_binop (mode, lshr_optab, count, GEN_INT (8), blocks, 1,
5383                            OPTAB_DIRECT);
5384       if (temp != blocks)
5385         emit_move_insn (blocks, temp);
5386
5387       emit_cmp_and_jump_insns (blocks, const0_rtx,
5388                                EQ, NULL_RTX, mode, 1, restbyte_end_label);
5389
5390       emit_jump (loop_start_label);
5391
5392       if (val != const0_rtx)
5393         {
5394           /* The 1 byte != 0 special case.  Not handled efficiently
5395              since we require two jumps for that.  However, this
5396              should be very rare.  */
5397           emit_label (onebyte_end_label);
5398           emit_move_insn (adjust_address (dst, QImode, 0), val);
5399           emit_jump (zerobyte_end_label);
5400         }
5401
5402       emit_label (loop_start_label);
5403
5404       if (TARGET_Z10
5405           && (GET_CODE (len) != CONST_INT || INTVAL (len) > 1024))
5406         {
5407           /* Issue a write prefetch for the +4 cache line.  */
5408           rtx prefetch = gen_prefetch (gen_rtx_PLUS (Pmode, dst_addr,
5409                                                      GEN_INT (1024)),
5410                                        const1_rtx, const0_rtx);
5411           emit_insn (prefetch);
5412           PREFETCH_SCHEDULE_BARRIER_P (prefetch) = true;
5413         }
5414
5415       if (val == const0_rtx)
5416         emit_insn (gen_clrmem_short (dst, GEN_INT (255)));
5417       else
5418         {
5419           /* Set the first byte in the block to the value and use an
5420              overlapping mvc for the block.  */
5421           emit_move_insn (adjust_address (dst, QImode, 0), val);
5422           emit_insn (gen_movmem_short (dstp1, dst, GEN_INT (254)));
5423         }
5424       s390_load_address (dst_addr,
5425                          gen_rtx_PLUS (Pmode, dst_addr, GEN_INT (256)));
5426
5427       temp = expand_binop (mode, add_optab, blocks, constm1_rtx, blocks, 1,
5428                            OPTAB_DIRECT);
5429       if (temp != blocks)
5430         emit_move_insn (blocks, temp);
5431
5432       emit_cmp_and_jump_insns (blocks, const0_rtx,
5433                                NE, NULL_RTX, mode, 1, loop_start_label);
5434
5435       emit_label (restbyte_end_label);
5436
5437       if (val == const0_rtx)
5438         emit_insn (gen_clrmem_short (dst, convert_to_mode (Pmode, count, 1)));
5439       else
5440         {
5441           /* Set the first byte in the block to the value and use an
5442              overlapping mvc for the block.  */
5443           emit_move_insn (adjust_address (dst, QImode, 0), val);
5444           /* execute only uses the lowest 8 bits of count that's
5445              exactly what we need here.  */
5446           emit_insn (gen_movmem_short (dstp1, dst,
5447                                        convert_to_mode (Pmode, count, 1)));
5448         }
5449
5450       emit_label (zerobyte_end_label);
5451     }
5452 }
5453
5454 /* Emit code to compare LEN bytes at OP0 with those at OP1,
5455    and return the result in TARGET.  */
5456
5457 bool
5458 s390_expand_cmpmem (rtx target, rtx op0, rtx op1, rtx len)
5459 {
5460   rtx ccreg = gen_rtx_REG (CCUmode, CC_REGNUM);
5461   rtx tmp;
5462
5463   /* When tuning for z10 or higher we rely on the Glibc functions to
5464      do the right thing. Only for constant lengths below 64k we will
5465      generate inline code.  */
5466   if (s390_tune >= PROCESSOR_2097_Z10
5467       && (GET_CODE (len) != CONST_INT || INTVAL (len) > (1<<16)))
5468     return false;
5469
5470   /* As the result of CMPINT is inverted compared to what we need,
5471      we have to swap the operands.  */
5472   tmp = op0; op0 = op1; op1 = tmp;
5473
5474   if (GET_CODE (len) == CONST_INT && INTVAL (len) >= 0 && INTVAL (len) <= 256)
5475     {
5476       if (INTVAL (len) > 0)
5477         {
5478           emit_insn (gen_cmpmem_short (op0, op1, GEN_INT (INTVAL (len) - 1)));
5479           emit_insn (gen_cmpint (target, ccreg));
5480         }
5481       else
5482         emit_move_insn (target, const0_rtx);
5483     }
5484   else if (TARGET_MVCLE)
5485     {
5486       emit_insn (gen_cmpmem_long (op0, op1, convert_to_mode (Pmode, len, 1)));
5487       emit_insn (gen_cmpint (target, ccreg));
5488     }
5489   else
5490     {
5491       rtx addr0, addr1, count, blocks, temp;
5492       rtx_code_label *loop_start_label = gen_label_rtx ();
5493       rtx_code_label *loop_end_label = gen_label_rtx ();
5494       rtx_code_label *end_label = gen_label_rtx ();
5495       machine_mode mode;
5496
5497       mode = GET_MODE (len);
5498       if (mode == VOIDmode)
5499         mode = Pmode;
5500
5501       addr0 = gen_reg_rtx (Pmode);
5502       addr1 = gen_reg_rtx (Pmode);
5503       count = gen_reg_rtx (mode);
5504       blocks = gen_reg_rtx (mode);
5505
5506       convert_move (count, len, 1);
5507       emit_cmp_and_jump_insns (count, const0_rtx,
5508                                EQ, NULL_RTX, mode, 1, end_label);
5509
5510       emit_move_insn (addr0, force_operand (XEXP (op0, 0), NULL_RTX));
5511       emit_move_insn (addr1, force_operand (XEXP (op1, 0), NULL_RTX));
5512       op0 = change_address (op0, VOIDmode, addr0);
5513       op1 = change_address (op1, VOIDmode, addr1);
5514
5515       temp = expand_binop (mode, add_optab, count, constm1_rtx, count, 1,
5516                            OPTAB_DIRECT);
5517       if (temp != count)
5518         emit_move_insn (count, temp);
5519
5520       temp = expand_binop (mode, lshr_optab, count, GEN_INT (8), blocks, 1,
5521                            OPTAB_DIRECT);
5522       if (temp != blocks)
5523         emit_move_insn (blocks, temp);
5524
5525       emit_cmp_and_jump_insns (blocks, const0_rtx,
5526                                EQ, NULL_RTX, mode, 1, loop_end_label);
5527
5528       emit_label (loop_start_label);
5529
5530       if (TARGET_Z10
5531           && (GET_CODE (len) != CONST_INT || INTVAL (len) > 512))
5532         {
5533           rtx prefetch;
5534
5535           /* Issue a read prefetch for the +2 cache line of operand 1.  */
5536           prefetch = gen_prefetch (gen_rtx_PLUS (Pmode, addr0, GEN_INT (512)),
5537                                    const0_rtx, const0_rtx);
5538           emit_insn (prefetch);
5539           PREFETCH_SCHEDULE_BARRIER_P (prefetch) = true;
5540
5541           /* Issue a read prefetch for the +2 cache line of operand 2.  */
5542           prefetch = gen_prefetch (gen_rtx_PLUS (Pmode, addr1, GEN_INT (512)),
5543                                    const0_rtx, const0_rtx);
5544           emit_insn (prefetch);
5545           PREFETCH_SCHEDULE_BARRIER_P (prefetch) = true;
5546         }
5547
5548       emit_insn (gen_cmpmem_short (op0, op1, GEN_INT (255)));
5549       temp = gen_rtx_NE (VOIDmode, ccreg, const0_rtx);
5550       temp = gen_rtx_IF_THEN_ELSE (VOIDmode, temp,
5551                         gen_rtx_LABEL_REF (VOIDmode, end_label), pc_rtx);
5552       temp = gen_rtx_SET (pc_rtx, temp);
5553       emit_jump_insn (temp);
5554
5555       s390_load_address (addr0,
5556                          gen_rtx_PLUS (Pmode, addr0, GEN_INT (256)));
5557       s390_load_address (addr1,
5558                          gen_rtx_PLUS (Pmode, addr1, GEN_INT (256)));
5559
5560       temp = expand_binop (mode, add_optab, blocks, constm1_rtx, blocks, 1,
5561                            OPTAB_DIRECT);
5562       if (temp != blocks)
5563         emit_move_insn (blocks, temp);
5564
5565       emit_cmp_and_jump_insns (blocks, const0_rtx,
5566                                EQ, NULL_RTX, mode, 1, loop_end_label);
5567
5568       emit_jump (loop_start_label);
5569       emit_label (loop_end_label);
5570
5571       emit_insn (gen_cmpmem_short (op0, op1,
5572                                    convert_to_mode (Pmode, count, 1)));
5573       emit_label (end_label);
5574
5575       emit_insn (gen_cmpint (target, ccreg));
5576     }
5577   return true;
5578 }
5579
5580 /* Emit a conditional jump to LABEL for condition code mask MASK using
5581    comparsion operator COMPARISON.  Return the emitted jump insn.  */
5582
5583 static rtx_insn *
5584 s390_emit_ccraw_jump (HOST_WIDE_INT mask, enum rtx_code comparison, rtx label)
5585 {
5586   rtx temp;
5587
5588   gcc_assert (comparison == EQ || comparison == NE);
5589   gcc_assert (mask > 0 && mask < 15);
5590
5591   temp = gen_rtx_fmt_ee (comparison, VOIDmode,
5592                          gen_rtx_REG (CCRAWmode, CC_REGNUM), GEN_INT (mask));
5593   temp = gen_rtx_IF_THEN_ELSE (VOIDmode, temp,
5594                                gen_rtx_LABEL_REF (VOIDmode, label), pc_rtx);
5595   temp = gen_rtx_SET (pc_rtx, temp);
5596   return emit_jump_insn (temp);
5597 }
5598
5599 /* Emit the instructions to implement strlen of STRING and store the
5600    result in TARGET.  The string has the known ALIGNMENT.  This
5601    version uses vector instructions and is therefore not appropriate
5602    for targets prior to z13.  */
5603
5604 void
5605 s390_expand_vec_strlen (rtx target, rtx string, rtx alignment)
5606 {
5607   int very_unlikely = REG_BR_PROB_BASE / 100 - 1;
5608   int very_likely = REG_BR_PROB_BASE - 1;
5609   rtx highest_index_to_load_reg = gen_reg_rtx (Pmode);
5610   rtx str_reg = gen_reg_rtx (V16QImode);
5611   rtx str_addr_base_reg = gen_reg_rtx (Pmode);
5612   rtx str_idx_reg = gen_reg_rtx (Pmode);
5613   rtx result_reg = gen_reg_rtx (V16QImode);
5614   rtx is_aligned_label = gen_label_rtx ();
5615   rtx into_loop_label = NULL_RTX;
5616   rtx loop_start_label = gen_label_rtx ();
5617   rtx temp;
5618   rtx len = gen_reg_rtx (QImode);
5619   rtx cond;
5620
5621   s390_load_address (str_addr_base_reg, XEXP (string, 0));
5622   emit_move_insn (str_idx_reg, const0_rtx);
5623
5624   if (INTVAL (alignment) < 16)
5625     {
5626       /* Check whether the address happens to be aligned properly so
5627          jump directly to the aligned loop.  */
5628       emit_cmp_and_jump_insns (gen_rtx_AND (Pmode,
5629                                             str_addr_base_reg, GEN_INT (15)),
5630                                const0_rtx, EQ, NULL_RTX,
5631                                Pmode, 1, is_aligned_label);
5632
5633       temp = gen_reg_rtx (Pmode);
5634       temp = expand_binop (Pmode, and_optab, str_addr_base_reg,
5635                            GEN_INT (15), temp, 1, OPTAB_DIRECT);
5636       gcc_assert (REG_P (temp));
5637       highest_index_to_load_reg =
5638         expand_binop (Pmode, sub_optab, GEN_INT (15), temp,
5639                       highest_index_to_load_reg, 1, OPTAB_DIRECT);
5640       gcc_assert (REG_P (highest_index_to_load_reg));
5641       emit_insn (gen_vllv16qi (str_reg,
5642                    convert_to_mode (SImode, highest_index_to_load_reg, 1),
5643                    gen_rtx_MEM (BLKmode, str_addr_base_reg)));
5644
5645       into_loop_label = gen_label_rtx ();
5646       s390_emit_jump (into_loop_label, NULL_RTX);
5647       emit_barrier ();
5648     }
5649
5650   emit_label (is_aligned_label);
5651   LABEL_NUSES (is_aligned_label) = INTVAL (alignment) < 16 ? 2 : 1;
5652
5653   /* Reaching this point we are only performing 16 bytes aligned
5654      loads.  */
5655   emit_move_insn (highest_index_to_load_reg, GEN_INT (15));
5656
5657   emit_label (loop_start_label);
5658   LABEL_NUSES (loop_start_label) = 1;
5659
5660   /* Load 16 bytes of the string into VR.  */
5661   emit_move_insn (str_reg,
5662                   gen_rtx_MEM (V16QImode,
5663                                gen_rtx_PLUS (Pmode, str_idx_reg,
5664                                              str_addr_base_reg)));
5665   if (into_loop_label != NULL_RTX)
5666     {
5667       emit_label (into_loop_label);
5668       LABEL_NUSES (into_loop_label) = 1;
5669     }
5670
5671   /* Increment string index by 16 bytes.  */
5672   expand_binop (Pmode, add_optab, str_idx_reg, GEN_INT (16),
5673                 str_idx_reg, 1, OPTAB_DIRECT);
5674
5675   emit_insn (gen_vec_vfenesv16qi (result_reg, str_reg, str_reg,
5676                                   GEN_INT (VSTRING_FLAG_ZS | VSTRING_FLAG_CS)));
5677
5678   add_int_reg_note (s390_emit_ccraw_jump (8, NE, loop_start_label),
5679                     REG_BR_PROB, very_likely);
5680   emit_insn (gen_vec_extractv16qi (len, result_reg, GEN_INT (7)));
5681
5682   /* If the string pointer wasn't aligned we have loaded less then 16
5683      bytes and the remaining bytes got filled with zeros (by vll).
5684      Now we have to check whether the resulting index lies within the
5685      bytes actually part of the string.  */
5686
5687   cond = s390_emit_compare (GT, convert_to_mode (Pmode, len, 1),
5688                             highest_index_to_load_reg);
5689   s390_load_address (highest_index_to_load_reg,
5690                      gen_rtx_PLUS (Pmode, highest_index_to_load_reg,
5691                                    const1_rtx));
5692   if (TARGET_64BIT)
5693     emit_insn (gen_movdicc (str_idx_reg, cond,
5694                             highest_index_to_load_reg, str_idx_reg));
5695   else
5696     emit_insn (gen_movsicc (str_idx_reg, cond,
5697                             highest_index_to_load_reg, str_idx_reg));
5698
5699   add_int_reg_note (s390_emit_jump (is_aligned_label, cond), REG_BR_PROB,
5700                     very_unlikely);
5701
5702   expand_binop (Pmode, add_optab, str_idx_reg,
5703                 GEN_INT (-16), str_idx_reg, 1, OPTAB_DIRECT);
5704   /* FIXME: len is already zero extended - so avoid the llgcr emitted
5705      here.  */
5706   temp = expand_binop (Pmode, add_optab, str_idx_reg,
5707                        convert_to_mode (Pmode, len, 1),
5708                        target, 1, OPTAB_DIRECT);
5709   if (temp != target)
5710     emit_move_insn (target, temp);
5711 }
5712
5713 void
5714 s390_expand_vec_movstr (rtx result, rtx dst, rtx src)
5715 {
5716   int very_unlikely = REG_BR_PROB_BASE / 100 - 1;
5717   rtx temp = gen_reg_rtx (Pmode);
5718   rtx src_addr = XEXP (src, 0);
5719   rtx dst_addr = XEXP (dst, 0);
5720   rtx src_addr_reg = gen_reg_rtx (Pmode);
5721   rtx dst_addr_reg = gen_reg_rtx (Pmode);
5722   rtx offset = gen_reg_rtx (Pmode);
5723   rtx vsrc = gen_reg_rtx (V16QImode);
5724   rtx vpos = gen_reg_rtx (V16QImode);
5725   rtx loadlen = gen_reg_rtx (SImode);
5726   rtx gpos_qi = gen_reg_rtx(QImode);
5727   rtx gpos = gen_reg_rtx (SImode);
5728   rtx done_label = gen_label_rtx ();
5729   rtx loop_label = gen_label_rtx ();
5730   rtx exit_label = gen_label_rtx ();
5731   rtx full_label = gen_label_rtx ();
5732
5733   /* Perform a quick check for string ending on the first up to 16
5734      bytes and exit early if successful.  */
5735
5736   emit_insn (gen_vlbb (vsrc, src, GEN_INT (6)));
5737   emit_insn (gen_lcbb (loadlen, src_addr, GEN_INT (6)));
5738   emit_insn (gen_vfenezv16qi (vpos, vsrc, vsrc));
5739   emit_insn (gen_vec_extractv16qi (gpos_qi, vpos, GEN_INT (7)));
5740   emit_move_insn (gpos, gen_rtx_SUBREG (SImode, gpos_qi, 0));
5741   /* gpos is the byte index if a zero was found and 16 otherwise.
5742      So if it is lower than the loaded bytes we have a hit.  */
5743   emit_cmp_and_jump_insns (gpos, loadlen, GE, NULL_RTX, SImode, 1,
5744                            full_label);
5745   emit_insn (gen_vstlv16qi (vsrc, gpos, dst));
5746
5747   force_expand_binop (Pmode, add_optab, dst_addr, gpos, result,
5748                       1, OPTAB_DIRECT);
5749   emit_jump (exit_label);
5750   emit_barrier ();
5751
5752   emit_label (full_label);
5753   LABEL_NUSES (full_label) = 1;
5754
5755   /* Calculate `offset' so that src + offset points to the last byte
5756      before 16 byte alignment.  */
5757
5758   /* temp = src_addr & 0xf */
5759   force_expand_binop (Pmode, and_optab, src_addr, GEN_INT (15), temp,
5760                       1, OPTAB_DIRECT);
5761
5762   /* offset = 0xf - temp */
5763   emit_move_insn (offset, GEN_INT (15));
5764   force_expand_binop (Pmode, sub_optab, offset, temp, offset,
5765                       1, OPTAB_DIRECT);
5766
5767   /* Store `offset' bytes in the dstination string.  The quick check
5768      has loaded at least `offset' bytes into vsrc.  */
5769
5770   emit_insn (gen_vstlv16qi (vsrc, gen_lowpart (SImode, offset), dst));
5771
5772   /* Advance to the next byte to be loaded.  */
5773   force_expand_binop (Pmode, add_optab, offset, const1_rtx, offset,
5774                       1, OPTAB_DIRECT);
5775
5776   /* Make sure the addresses are single regs which can be used as a
5777      base.  */
5778   emit_move_insn (src_addr_reg, src_addr);
5779   emit_move_insn (dst_addr_reg, dst_addr);
5780
5781   /* MAIN LOOP */
5782
5783   emit_label (loop_label);
5784   LABEL_NUSES (loop_label) = 1;
5785
5786   emit_move_insn (vsrc,
5787                   gen_rtx_MEM (V16QImode,
5788                                gen_rtx_PLUS (Pmode, src_addr_reg, offset)));
5789
5790   emit_insn (gen_vec_vfenesv16qi (vpos, vsrc, vsrc,
5791                                   GEN_INT (VSTRING_FLAG_ZS | VSTRING_FLAG_CS)));
5792   add_int_reg_note (s390_emit_ccraw_jump (8, EQ, done_label),
5793                     REG_BR_PROB, very_unlikely);
5794
5795   emit_move_insn (gen_rtx_MEM (V16QImode,
5796                                gen_rtx_PLUS (Pmode, dst_addr_reg, offset)),
5797                   vsrc);
5798   /* offset += 16 */
5799   force_expand_binop (Pmode, add_optab, offset, GEN_INT (16),
5800                       offset,  1, OPTAB_DIRECT);
5801
5802   emit_jump (loop_label);
5803   emit_barrier ();
5804
5805   /* REGULAR EXIT */
5806
5807   /* We are done.  Add the offset of the zero character to the dst_addr
5808      pointer to get the result.  */
5809
5810   emit_label (done_label);
5811   LABEL_NUSES (done_label) = 1;
5812
5813   force_expand_binop (Pmode, add_optab, dst_addr_reg, offset, dst_addr_reg,
5814                       1, OPTAB_DIRECT);
5815
5816   emit_insn (gen_vec_extractv16qi (gpos_qi, vpos, GEN_INT (7)));
5817   emit_move_insn (gpos, gen_rtx_SUBREG (SImode, gpos_qi, 0));
5818
5819   emit_insn (gen_vstlv16qi (vsrc, gpos, gen_rtx_MEM (BLKmode, dst_addr_reg)));
5820
5821   force_expand_binop (Pmode, add_optab, dst_addr_reg, gpos, result,
5822                       1, OPTAB_DIRECT);
5823
5824   /* EARLY EXIT */
5825
5826   emit_label (exit_label);
5827   LABEL_NUSES (exit_label) = 1;
5828 }
5829
5830
5831 /* Expand conditional increment or decrement using alc/slb instructions.
5832    Should generate code setting DST to either SRC or SRC + INCREMENT,
5833    depending on the result of the comparison CMP_OP0 CMP_CODE CMP_OP1.
5834    Returns true if successful, false otherwise.
5835
5836    That makes it possible to implement some if-constructs without jumps e.g.:
5837    (borrow = CC0 | CC1 and carry = CC2 | CC3)
5838    unsigned int a, b, c;
5839    if (a < b)  c++; -> CCU  b > a  -> CC2;    c += carry;
5840    if (a < b)  c--; -> CCL3 a - b  -> borrow; c -= borrow;
5841    if (a <= b) c++; -> CCL3 b - a  -> borrow; c += carry;
5842    if (a <= b) c--; -> CCU  a <= b -> borrow; c -= borrow;
5843
5844    Checks for EQ and NE with a nonzero value need an additional xor e.g.:
5845    if (a == b) c++; -> CCL3 a ^= b; 0 - a  -> borrow;    c += carry;
5846    if (a == b) c--; -> CCU  a ^= b; a <= 0 -> CC0 | CC1; c -= borrow;
5847    if (a != b) c++; -> CCU  a ^= b; a > 0  -> CC2;       c += carry;
5848    if (a != b) c--; -> CCL3 a ^= b; 0 - a  -> borrow;    c -= borrow; */
5849
5850 bool
5851 s390_expand_addcc (enum rtx_code cmp_code, rtx cmp_op0, rtx cmp_op1,
5852                    rtx dst, rtx src, rtx increment)
5853 {
5854   machine_mode cmp_mode;
5855   machine_mode cc_mode;
5856   rtx op_res;
5857   rtx insn;
5858   rtvec p;
5859   int ret;
5860
5861   if ((GET_MODE (cmp_op0) == SImode || GET_MODE (cmp_op0) == VOIDmode)
5862       && (GET_MODE (cmp_op1) == SImode || GET_MODE (cmp_op1) == VOIDmode))
5863     cmp_mode = SImode;
5864   else if ((GET_MODE (cmp_op0) == DImode || GET_MODE (cmp_op0) == VOIDmode)
5865            && (GET_MODE (cmp_op1) == DImode || GET_MODE (cmp_op1) == VOIDmode))
5866     cmp_mode = DImode;
5867   else
5868     return false;
5869
5870   /* Try ADD LOGICAL WITH CARRY.  */
5871   if (increment == const1_rtx)
5872     {
5873       /* Determine CC mode to use.  */
5874       if (cmp_code == EQ || cmp_code == NE)
5875         {
5876           if (cmp_op1 != const0_rtx)
5877             {
5878               cmp_op0 = expand_simple_binop (cmp_mode, XOR, cmp_op0, cmp_op1,
5879                                              NULL_RTX, 0, OPTAB_WIDEN);
5880               cmp_op1 = const0_rtx;
5881             }
5882
5883           cmp_code = cmp_code == EQ ? LEU : GTU;
5884         }
5885
5886       if (cmp_code == LTU || cmp_code == LEU)
5887         {
5888           rtx tem = cmp_op0;
5889           cmp_op0 = cmp_op1;
5890           cmp_op1 = tem;
5891           cmp_code = swap_condition (cmp_code);
5892         }
5893
5894       switch (cmp_code)
5895         {
5896           case GTU:
5897             cc_mode = CCUmode;
5898             break;
5899
5900           case GEU:
5901             cc_mode = CCL3mode;
5902             break;
5903
5904           default:
5905             return false;
5906         }
5907
5908       /* Emit comparison instruction pattern. */
5909       if (!register_operand (cmp_op0, cmp_mode))
5910         cmp_op0 = force_reg (cmp_mode, cmp_op0);
5911
5912       insn = gen_rtx_SET (gen_rtx_REG (cc_mode, CC_REGNUM),
5913                           gen_rtx_COMPARE (cc_mode, cmp_op0, cmp_op1));
5914       /* We use insn_invalid_p here to add clobbers if required.  */
5915       ret = insn_invalid_p (emit_insn (insn), false);
5916       gcc_assert (!ret);
5917
5918       /* Emit ALC instruction pattern.  */
5919       op_res = gen_rtx_fmt_ee (cmp_code, GET_MODE (dst),
5920                                gen_rtx_REG (cc_mode, CC_REGNUM),
5921                                const0_rtx);
5922
5923       if (src != const0_rtx)
5924         {
5925           if (!register_operand (src, GET_MODE (dst)))
5926             src = force_reg (GET_MODE (dst), src);
5927
5928           op_res = gen_rtx_PLUS (GET_MODE (dst), op_res, src);
5929           op_res = gen_rtx_PLUS (GET_MODE (dst), op_res, const0_rtx);
5930         }
5931
5932       p = rtvec_alloc (2);
5933       RTVEC_ELT (p, 0) =
5934         gen_rtx_SET (dst, op_res);
5935       RTVEC_ELT (p, 1) =
5936         gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (CCmode, CC_REGNUM));
5937       emit_insn (gen_rtx_PARALLEL (VOIDmode, p));
5938
5939       return true;
5940     }
5941
5942   /* Try SUBTRACT LOGICAL WITH BORROW.  */
5943   if (increment == constm1_rtx)
5944     {
5945       /* Determine CC mode to use.  */
5946       if (cmp_code == EQ || cmp_code == NE)
5947         {
5948           if (cmp_op1 != const0_rtx)
5949             {
5950               cmp_op0 = expand_simple_binop (cmp_mode, XOR, cmp_op0, cmp_op1,
5951                                              NULL_RTX, 0, OPTAB_WIDEN);
5952               cmp_op1 = const0_rtx;
5953             }
5954
5955           cmp_code = cmp_code == EQ ? LEU : GTU;
5956         }
5957
5958       if (cmp_code == GTU || cmp_code == GEU)
5959         {
5960           rtx tem = cmp_op0;
5961           cmp_op0 = cmp_op1;
5962           cmp_op1 = tem;
5963           cmp_code = swap_condition (cmp_code);
5964         }
5965
5966       switch (cmp_code)
5967         {
5968           case LEU:
5969             cc_mode = CCUmode;
5970             break;
5971
5972           case LTU:
5973             cc_mode = CCL3mode;
5974             break;
5975
5976           default:
5977             return false;
5978         }
5979
5980       /* Emit comparison instruction pattern. */
5981       if (!register_operand (cmp_op0, cmp_mode))
5982         cmp_op0 = force_reg (cmp_mode, cmp_op0);
5983
5984       insn = gen_rtx_SET (gen_rtx_REG (cc_mode, CC_REGNUM),
5985                           gen_rtx_COMPARE (cc_mode, cmp_op0, cmp_op1));
5986       /* We use insn_invalid_p here to add clobbers if required.  */
5987       ret = insn_invalid_p (emit_insn (insn), false);
5988       gcc_assert (!ret);
5989
5990       /* Emit SLB instruction pattern.  */
5991       if (!register_operand (src, GET_MODE (dst)))
5992         src = force_reg (GET_MODE (dst), src);
5993
5994       op_res = gen_rtx_MINUS (GET_MODE (dst),
5995                               gen_rtx_MINUS (GET_MODE (dst), src, const0_rtx),
5996                               gen_rtx_fmt_ee (cmp_code, GET_MODE (dst),
5997                                               gen_rtx_REG (cc_mode, CC_REGNUM),
5998                                               const0_rtx));
5999       p = rtvec_alloc (2);
6000       RTVEC_ELT (p, 0) =
6001         gen_rtx_SET (dst, op_res);
6002       RTVEC_ELT (p, 1) =
6003         gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (CCmode, CC_REGNUM));
6004       emit_insn (gen_rtx_PARALLEL (VOIDmode, p));
6005
6006       return true;
6007     }
6008
6009   return false;
6010 }
6011
6012 /* Expand code for the insv template. Return true if successful.  */
6013
6014 bool
6015 s390_expand_insv (rtx dest, rtx op1, rtx op2, rtx src)
6016 {
6017   int bitsize = INTVAL (op1);
6018   int bitpos = INTVAL (op2);
6019   machine_mode mode = GET_MODE (dest);
6020   machine_mode smode;
6021   int smode_bsize, mode_bsize;
6022   rtx op, clobber;
6023
6024   if (bitsize + bitpos > GET_MODE_BITSIZE (mode))
6025     return false;
6026
6027   /* Generate INSERT IMMEDIATE (IILL et al).  */
6028   /* (set (ze (reg)) (const_int)).  */
6029   if (TARGET_ZARCH
6030       && register_operand (dest, word_mode)
6031       && (bitpos % 16) == 0
6032       && (bitsize % 16) == 0
6033       && const_int_operand (src, VOIDmode))
6034     {
6035       HOST_WIDE_INT val = INTVAL (src);
6036       int regpos = bitpos + bitsize;
6037
6038       while (regpos > bitpos)
6039         {
6040           machine_mode putmode;
6041           int putsize;
6042
6043           if (TARGET_EXTIMM && (regpos % 32 == 0) && (regpos >= bitpos + 32))
6044             putmode = SImode;
6045           else
6046             putmode = HImode;
6047
6048           putsize = GET_MODE_BITSIZE (putmode);
6049           regpos -= putsize;
6050           emit_move_insn (gen_rtx_ZERO_EXTRACT (word_mode, dest,
6051                                                 GEN_INT (putsize),
6052                                                 GEN_INT (regpos)),
6053                           gen_int_mode (val, putmode));
6054           val >>= putsize;
6055         }
6056       gcc_assert (regpos == bitpos);
6057       return true;
6058     }
6059
6060   smode = smallest_mode_for_size (bitsize, MODE_INT);
6061   smode_bsize = GET_MODE_BITSIZE (smode);
6062   mode_bsize = GET_MODE_BITSIZE (mode);
6063
6064   /* Generate STORE CHARACTERS UNDER MASK (STCM et al).  */
6065   if (bitpos == 0
6066       && (bitsize % BITS_PER_UNIT) == 0
6067       && MEM_P (dest)
6068       && (register_operand (src, word_mode)
6069           || const_int_operand (src, VOIDmode)))
6070     {
6071       /* Emit standard pattern if possible.  */
6072       if (smode_bsize == bitsize)
6073         {
6074           emit_move_insn (adjust_address (dest, smode, 0),
6075                           gen_lowpart (smode, src));
6076           return true;
6077         }
6078
6079       /* (set (ze (mem)) (const_int)).  */
6080       else if (const_int_operand (src, VOIDmode))
6081         {
6082           int size = bitsize / BITS_PER_UNIT;
6083           rtx src_mem = adjust_address (force_const_mem (word_mode, src),
6084                                         BLKmode,
6085                                         UNITS_PER_WORD - size);
6086
6087           dest = adjust_address (dest, BLKmode, 0);
6088           set_mem_size (dest, size);
6089           s390_expand_movmem (dest, src_mem, GEN_INT (size));
6090           return true;
6091         }
6092
6093       /* (set (ze (mem)) (reg)).  */
6094       else if (register_operand (src, word_mode))
6095         {
6096           if (bitsize <= 32)
6097             emit_move_insn (gen_rtx_ZERO_EXTRACT (word_mode, dest, op1,
6098                                                   const0_rtx), src);
6099           else
6100             {
6101               /* Emit st,stcmh sequence.  */
6102               int stcmh_width = bitsize - 32;
6103               int size = stcmh_width / BITS_PER_UNIT;
6104
6105               emit_move_insn (adjust_address (dest, SImode, size),
6106                               gen_lowpart (SImode, src));
6107               set_mem_size (dest, size);
6108               emit_move_insn (gen_rtx_ZERO_EXTRACT (word_mode, dest,
6109                                                     GEN_INT (stcmh_width),
6110                                                     const0_rtx),
6111                               gen_rtx_LSHIFTRT (word_mode, src, GEN_INT (32)));
6112             }
6113           return true;
6114         }
6115     }
6116
6117   /* Generate INSERT CHARACTERS UNDER MASK (IC, ICM et al).  */
6118   if ((bitpos % BITS_PER_UNIT) == 0
6119       && (bitsize % BITS_PER_UNIT) == 0
6120       && (bitpos & 32) == ((bitpos + bitsize - 1) & 32)
6121       && MEM_P (src)
6122       && (mode == DImode || mode == SImode)
6123       && register_operand (dest, mode))
6124     {
6125       /* Emit a strict_low_part pattern if possible.  */
6126       if (smode_bsize == bitsize && bitpos == mode_bsize - smode_bsize)
6127         {
6128           op = gen_rtx_STRICT_LOW_PART (VOIDmode, gen_lowpart (smode, dest));
6129           op = gen_rtx_SET (op, gen_lowpart (smode, src));
6130           clobber = gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (CCmode, CC_REGNUM));
6131           emit_insn (gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, op, clobber)));
6132           return true;
6133         }
6134
6135       /* ??? There are more powerful versions of ICM that are not
6136          completely represented in the md file.  */
6137     }
6138
6139   /* For z10, generate ROTATE THEN INSERT SELECTED BITS (RISBG et al).  */
6140   if (TARGET_Z10 && (mode == DImode || mode == SImode))
6141     {
6142       machine_mode mode_s = GET_MODE (src);
6143
6144       if (CONSTANT_P (src))
6145         {
6146           /* For constant zero values the representation with AND
6147              appears to be folded in more situations than the (set
6148              (zero_extract) ...).
6149              We only do this when the start and end of the bitfield
6150              remain in the same SImode chunk.  That way nihf or nilf
6151              can be used.
6152              The AND patterns might still generate a risbg for this.  */
6153           if (src == const0_rtx && bitpos / 32  == (bitpos + bitsize - 1) / 32)
6154             return false;
6155           else
6156             src = force_reg (mode, src);
6157         }
6158       else if (mode_s != mode)
6159         {
6160           gcc_assert (GET_MODE_BITSIZE (mode_s) >= bitsize);
6161           src = force_reg (mode_s, src);
6162           src = gen_lowpart (mode, src);
6163         }
6164
6165       op = gen_rtx_ZERO_EXTRACT (mode, dest, op1, op2),
6166       op = gen_rtx_SET (op, src);
6167
6168       if (!TARGET_ZEC12)
6169         {
6170           clobber = gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (CCmode, CC_REGNUM));
6171           op = gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, op, clobber));
6172         }
6173       emit_insn (op);
6174
6175       return true;
6176     }
6177
6178   return false;
6179 }
6180
6181 /* A subroutine of s390_expand_cs_hqi and s390_expand_atomic which returns a
6182    register that holds VAL of mode MODE shifted by COUNT bits.  */
6183
6184 static inline rtx
6185 s390_expand_mask_and_shift (rtx val, machine_mode mode, rtx count)
6186 {
6187   val = expand_simple_binop (SImode, AND, val, GEN_INT (GET_MODE_MASK (mode)),
6188                              NULL_RTX, 1, OPTAB_DIRECT);
6189   return expand_simple_binop (SImode, ASHIFT, val, count,
6190                               NULL_RTX, 1, OPTAB_DIRECT);
6191 }
6192
6193 /* Generate a vector comparison COND of CMP_OP1 and CMP_OP2 and store
6194    the result in TARGET.  */
6195
6196 void
6197 s390_expand_vec_compare (rtx target, enum rtx_code cond,
6198                          rtx cmp_op1, rtx cmp_op2)
6199 {
6200   machine_mode mode = GET_MODE (target);
6201   bool neg_p = false, swap_p = false;
6202   rtx tmp;
6203
6204   if (GET_MODE_CLASS (GET_MODE (cmp_op1)) == MODE_VECTOR_FLOAT)
6205     {
6206       switch (cond)
6207         {
6208           /* NE a != b -> !(a == b) */
6209         case NE:   cond = EQ; neg_p = true;                break;
6210           /* UNGT a u> b -> !(b >= a) */
6211         case UNGT: cond = GE; neg_p = true; swap_p = true; break;
6212           /* UNGE a u>= b -> !(b > a) */
6213         case UNGE: cond = GT; neg_p = true; swap_p = true; break;
6214           /* LE: a <= b -> b >= a */
6215         case LE:   cond = GE;               swap_p = true; break;
6216           /* UNLE: a u<= b -> !(a > b) */
6217         case UNLE: cond = GT; neg_p = true;                break;
6218           /* LT: a < b -> b > a */
6219         case LT:   cond = GT;               swap_p = true; break;
6220           /* UNLT: a u< b -> !(a >= b) */
6221         case UNLT: cond = GE; neg_p = true;                break;
6222         case UNEQ:
6223           emit_insn (gen_vec_cmpuneqv2df (target, cmp_op1, cmp_op2));
6224           return;
6225         case LTGT:
6226           emit_insn (gen_vec_cmpltgtv2df (target, cmp_op1, cmp_op2));
6227           return;
6228         case ORDERED:
6229           emit_insn (gen_vec_orderedv2df (target, cmp_op1, cmp_op2));
6230           return;
6231         case UNORDERED:
6232           emit_insn (gen_vec_unorderedv2df (target, cmp_op1, cmp_op2));
6233           return;
6234         default: break;
6235         }
6236     }
6237   else
6238     {
6239       switch (cond)
6240         {
6241           /* NE: a != b -> !(a == b) */
6242         case NE:  cond = EQ;  neg_p = true;                break;
6243           /* GE: a >= b -> !(b > a) */
6244         case GE:  cond = GT;  neg_p = true; swap_p = true; break;
6245           /* GEU: a >= b -> !(b > a) */
6246         case GEU: cond = GTU; neg_p = true; swap_p = true; break;
6247           /* LE: a <= b -> !(a > b) */
6248         case LE:  cond = GT;  neg_p = true;                break;
6249           /* LEU: a <= b -> !(a > b) */
6250         case LEU: cond = GTU; neg_p = true;                break;
6251           /* LT: a < b -> b > a */
6252         case LT:  cond = GT;                swap_p = true; break;
6253           /* LTU: a < b -> b > a */
6254         case LTU: cond = GTU;               swap_p = true; break;
6255         default: break;
6256         }
6257     }
6258
6259   if (swap_p)
6260     {
6261       tmp = cmp_op1; cmp_op1 = cmp_op2; cmp_op2 = tmp;
6262     }
6263
6264   emit_insn (gen_rtx_SET (target, gen_rtx_fmt_ee (cond,
6265                                                   mode,
6266                                                   cmp_op1, cmp_op2)));
6267   if (neg_p)
6268     emit_insn (gen_rtx_SET (target, gen_rtx_NOT (mode, target)));
6269 }
6270
6271 /* Expand the comparison CODE of CMP1 and CMP2 and copy 1 or 0 into
6272    TARGET if either all (ALL_P is true) or any (ALL_P is false) of the
6273    elements in CMP1 and CMP2 fulfill the comparison.
6274    This function is only used to emit patterns for the vx builtins and
6275    therefore only handles comparison codes required by the
6276    builtins.  */
6277 void
6278 s390_expand_vec_compare_cc (rtx target, enum rtx_code code,
6279                             rtx cmp1, rtx cmp2, bool all_p)
6280 {
6281   machine_mode cc_producer_mode, cc_consumer_mode, scratch_mode;
6282   rtx tmp_reg = gen_reg_rtx (SImode);
6283   bool swap_p = false;
6284
6285   if (GET_MODE_CLASS (GET_MODE (cmp1)) == MODE_VECTOR_INT)
6286     {
6287       switch (code)
6288         {
6289         case EQ:
6290         case NE:
6291           cc_producer_mode = CCVEQmode;
6292           break;
6293         case GE:
6294         case LT:
6295           code = swap_condition (code);
6296           swap_p = true;
6297           /* fallthrough */
6298         case GT:
6299         case LE:
6300           cc_producer_mode = CCVIHmode;
6301           break;
6302         case GEU:
6303         case LTU:
6304           code = swap_condition (code);
6305           swap_p = true;
6306           /* fallthrough */
6307         case GTU:
6308         case LEU:
6309           cc_producer_mode = CCVIHUmode;
6310           break;
6311         default:
6312           gcc_unreachable ();
6313         }
6314
6315       scratch_mode = GET_MODE (cmp1);
6316       /* These codes represent inverted CC interpretations.  Inverting
6317          an ALL CC mode results in an ANY CC mode and the other way
6318          around.  Invert the all_p flag here to compensate for
6319          that.  */
6320       if (code == NE || code == LE || code == LEU)
6321         all_p = !all_p;
6322
6323       cc_consumer_mode = all_p ? CCVIALLmode : CCVIANYmode;
6324     }
6325   else if (GET_MODE_CLASS (GET_MODE (cmp1)) == MODE_VECTOR_FLOAT)
6326     {
6327       bool inv_p = false;
6328
6329       switch (code)
6330         {
6331         case EQ:   cc_producer_mode = CCVEQmode;  break;
6332         case NE:   cc_producer_mode = CCVEQmode;  inv_p = true; break;
6333         case GT:   cc_producer_mode = CCVFHmode;  break;
6334         case GE:   cc_producer_mode = CCVFHEmode; break;
6335         case UNLE: cc_producer_mode = CCVFHmode;  inv_p = true; break;
6336         case UNLT: cc_producer_mode = CCVFHEmode; inv_p = true; break;
6337         case LT:   cc_producer_mode = CCVFHmode;  code = GT; swap_p = true; break;
6338         case LE:   cc_producer_mode = CCVFHEmode; code = GE; swap_p = true; break;
6339         default: gcc_unreachable ();
6340         }
6341       scratch_mode = mode_for_vector (
6342                        int_mode_for_mode (GET_MODE_INNER (GET_MODE (cmp1))),
6343                        GET_MODE_NUNITS (GET_MODE (cmp1)));
6344       gcc_assert (scratch_mode != BLKmode);
6345
6346       if (inv_p)
6347         all_p = !all_p;
6348
6349       cc_consumer_mode = all_p ? CCVFALLmode : CCVFANYmode;
6350     }
6351   else
6352     gcc_unreachable ();
6353
6354   if (swap_p)
6355     {
6356       rtx tmp = cmp2;
6357       cmp2 = cmp1;
6358       cmp1 = tmp;
6359     }
6360
6361   emit_insn (gen_rtx_PARALLEL (VOIDmode,
6362                gen_rtvec (2, gen_rtx_SET (
6363                                gen_rtx_REG (cc_producer_mode, CC_REGNUM),
6364                                gen_rtx_COMPARE (cc_producer_mode, cmp1, cmp2)),
6365                           gen_rtx_CLOBBER (VOIDmode,
6366                                            gen_rtx_SCRATCH (scratch_mode)))));
6367   emit_move_insn (target, const0_rtx);
6368   emit_move_insn (tmp_reg, const1_rtx);
6369
6370   emit_move_insn (target,
6371                   gen_rtx_IF_THEN_ELSE (SImode,
6372                     gen_rtx_fmt_ee (code, VOIDmode,
6373                                     gen_rtx_REG (cc_consumer_mode, CC_REGNUM),
6374                                     const0_rtx),
6375                                         tmp_reg, target));
6376 }
6377
6378 /* Invert the comparison CODE applied to a CC mode.  This is only safe
6379    if we know whether there result was created by a floating point
6380    compare or not.  For the CCV modes this is encoded as part of the
6381    mode.  */
6382 enum rtx_code
6383 s390_reverse_condition (machine_mode mode, enum rtx_code code)
6384 {
6385   /* Reversal of FP compares takes care -- an ordered compare
6386      becomes an unordered compare and vice versa.  */
6387   if (mode == CCVFALLmode || mode == CCVFANYmode)
6388     return reverse_condition_maybe_unordered (code);
6389   else if (mode == CCVIALLmode || mode == CCVIANYmode)
6390     return reverse_condition (code);
6391   else
6392     gcc_unreachable ();
6393 }
6394
6395 /* Generate a vector comparison expression loading either elements of
6396    THEN or ELS into TARGET depending on the comparison COND of CMP_OP1
6397    and CMP_OP2.  */
6398
6399 void
6400 s390_expand_vcond (rtx target, rtx then, rtx els,
6401                    enum rtx_code cond, rtx cmp_op1, rtx cmp_op2)
6402 {
6403   rtx tmp;
6404   machine_mode result_mode;
6405   rtx result_target;
6406
6407   machine_mode target_mode = GET_MODE (target);
6408   machine_mode cmp_mode = GET_MODE (cmp_op1);
6409   rtx op = (cond == LT) ? els : then;
6410
6411   /* Try to optimize x < 0 ? -1 : 0 into (signed) x >> 31
6412      and x < 0 ? 1 : 0 into (unsigned) x >> 31.  Likewise
6413      for short and byte (x >> 15 and x >> 7 respectively).  */
6414   if ((cond == LT || cond == GE)
6415       && target_mode == cmp_mode
6416       && cmp_op2 == CONST0_RTX (cmp_mode)
6417       && op == CONST0_RTX (target_mode)
6418       && s390_vector_mode_supported_p (target_mode)
6419       && GET_MODE_CLASS (target_mode) == MODE_VECTOR_INT)
6420     {
6421       rtx negop = (cond == LT) ? then : els;
6422
6423       int shift = GET_MODE_BITSIZE (GET_MODE_INNER (target_mode)) - 1;
6424
6425       /* if x < 0 ? 1 : 0 or if x >= 0 ? 0 : 1 */
6426       if (negop == CONST1_RTX (target_mode))
6427         {
6428           rtx res = expand_simple_binop (cmp_mode, LSHIFTRT, cmp_op1,
6429                                          GEN_INT (shift), target,
6430                                          1, OPTAB_DIRECT);
6431           if (res != target)
6432             emit_move_insn (target, res);
6433           return;
6434         }
6435
6436       /* if x < 0 ? -1 : 0 or if x >= 0 ? 0 : -1 */
6437       else if (all_ones_operand (negop, target_mode))
6438         {
6439           rtx res = expand_simple_binop (cmp_mode, ASHIFTRT, cmp_op1,
6440                                          GEN_INT (shift), target,
6441                                          0, OPTAB_DIRECT);
6442           if (res != target)
6443             emit_move_insn (target, res);
6444           return;
6445         }
6446     }
6447
6448   /* We always use an integral type vector to hold the comparison
6449      result.  */
6450   result_mode = mode_for_vector (int_mode_for_mode (GET_MODE_INNER (cmp_mode)),
6451                                  GET_MODE_NUNITS (cmp_mode));
6452   result_target = gen_reg_rtx (result_mode);
6453
6454   /* We allow vector immediates as comparison operands that
6455      can be handled by the optimization above but not by the
6456      following code.  Hence, force them into registers here.  */
6457   if (!REG_P (cmp_op1))
6458     cmp_op1 = force_reg (GET_MODE (cmp_op1), cmp_op1);
6459
6460   if (!REG_P (cmp_op2))
6461     cmp_op2 = force_reg (GET_MODE (cmp_op2), cmp_op2);
6462
6463   s390_expand_vec_compare (result_target, cond,
6464                            cmp_op1, cmp_op2);
6465
6466   /* If the results are supposed to be either -1 or 0 we are done
6467      since this is what our compare instructions generate anyway.  */
6468   if (all_ones_operand (then, GET_MODE (then))
6469       && const0_operand (els, GET_MODE (els)))
6470     {
6471       emit_move_insn (target, gen_rtx_SUBREG (target_mode,
6472                                               result_target, 0));
6473       return;
6474     }
6475
6476   /* Otherwise we will do a vsel afterwards.  */
6477   /* This gets triggered e.g.
6478      with gcc.c-torture/compile/pr53410-1.c */
6479   if (!REG_P (then))
6480     then = force_reg (target_mode, then);
6481
6482   if (!REG_P (els))
6483     els = force_reg (target_mode, els);
6484
6485   tmp = gen_rtx_fmt_ee (EQ, VOIDmode,
6486                         result_target,
6487                         CONST0_RTX (result_mode));
6488
6489   /* We compared the result against zero above so we have to swap then
6490      and els here.  */
6491   tmp = gen_rtx_IF_THEN_ELSE (target_mode, tmp, els, then);
6492
6493   gcc_assert (target_mode == GET_MODE (then));
6494   emit_insn (gen_rtx_SET (target, tmp));
6495 }
6496
6497 /* Emit the RTX necessary to initialize the vector TARGET with values
6498    in VALS.  */
6499 void
6500 s390_expand_vec_init (rtx target, rtx vals)
6501 {
6502   machine_mode mode = GET_MODE (target);
6503   machine_mode inner_mode = GET_MODE_INNER (mode);
6504   int n_elts = GET_MODE_NUNITS (mode);
6505   bool all_same = true, all_regs = true, all_const_int = true;
6506   rtx x;
6507   int i;
6508
6509   for (i = 0; i < n_elts; ++i)
6510     {
6511       x = XVECEXP (vals, 0, i);
6512
6513       if (!CONST_INT_P (x))
6514         all_const_int = false;
6515
6516       if (i > 0 && !rtx_equal_p (x, XVECEXP (vals, 0, 0)))
6517         all_same = false;
6518
6519       if (!REG_P (x))
6520         all_regs = false;
6521     }
6522
6523   /* Use vector gen mask or vector gen byte mask if possible.  */
6524   if (all_same && all_const_int
6525       && (XVECEXP (vals, 0, 0) == const0_rtx
6526           || s390_contiguous_bitmask_vector_p (XVECEXP (vals, 0, 0),
6527                                                NULL, NULL)
6528           || s390_bytemask_vector_p (XVECEXP (vals, 0, 0), NULL)))
6529     {
6530       emit_insn (gen_rtx_SET (target,
6531                               gen_rtx_CONST_VECTOR (mode, XVEC (vals, 0))));
6532       return;
6533     }
6534
6535   if (all_same)
6536     {
6537       emit_insn (gen_rtx_SET (target,
6538                               gen_rtx_VEC_DUPLICATE (mode,
6539                                                      XVECEXP (vals, 0, 0))));
6540       return;
6541     }
6542
6543   if (all_regs
6544       && REG_P (target)
6545       && n_elts == 2
6546       && GET_MODE_SIZE (inner_mode) == 8)
6547     {
6548       /* Use vector load pair.  */
6549       emit_insn (gen_rtx_SET (target,
6550                               gen_rtx_VEC_CONCAT (mode,
6551                                                   XVECEXP (vals, 0, 0),
6552                                                   XVECEXP (vals, 0, 1))));
6553       return;
6554     }
6555
6556   /* Use vector load logical element and zero.  */
6557   if (TARGET_VXE && (mode == V4SImode || mode == V4SFmode))
6558     {
6559       bool found = true;
6560
6561       x = XVECEXP (vals, 0, 0);
6562       if (memory_operand (x, inner_mode))
6563         {
6564           for (i = 1; i < n_elts; ++i)
6565             found = found && XVECEXP (vals, 0, i) == const0_rtx;
6566
6567           if (found)
6568             {
6569               machine_mode half_mode = (inner_mode == SFmode
6570                                         ? V2SFmode : V2SImode);
6571               emit_insn (gen_rtx_SET (target,
6572                               gen_rtx_VEC_CONCAT (mode,
6573                                                   gen_rtx_VEC_CONCAT (half_mode,
6574                                                                       x,
6575                                                                       const0_rtx),
6576                                                   gen_rtx_VEC_CONCAT (half_mode,
6577                                                                       const0_rtx,
6578                                                                       const0_rtx))));
6579               return;
6580             }
6581         }
6582     }
6583
6584   /* We are about to set the vector elements one by one.  Zero out the
6585      full register first in order to help the data flow framework to
6586      detect it as full VR set.  */
6587   emit_insn (gen_rtx_SET (target, CONST0_RTX (mode)));
6588
6589   /* Unfortunately the vec_init expander is not allowed to fail.  So
6590      we have to implement the fallback ourselves.  */
6591   for (i = 0; i < n_elts; i++)
6592     {
6593       rtx elem = XVECEXP (vals, 0, i);
6594       if (!general_operand (elem, GET_MODE (elem)))
6595         elem = force_reg (inner_mode, elem);
6596
6597       emit_insn (gen_rtx_SET (target,
6598                               gen_rtx_UNSPEC (mode,
6599                                               gen_rtvec (3, elem,
6600                                                          GEN_INT (i), target),
6601                                               UNSPEC_VEC_SET)));
6602     }
6603 }
6604
6605 /* Structure to hold the initial parameters for a compare_and_swap operation
6606    in HImode and QImode.  */
6607
6608 struct alignment_context
6609 {
6610   rtx memsi;      /* SI aligned memory location.  */
6611   rtx shift;      /* Bit offset with regard to lsb.  */
6612   rtx modemask;   /* Mask of the HQImode shifted by SHIFT bits.  */
6613   rtx modemaski;  /* ~modemask */
6614   bool aligned;   /* True if memory is aligned, false else.  */
6615 };
6616
6617 /* A subroutine of s390_expand_cs_hqi and s390_expand_atomic to initialize
6618    structure AC for transparent simplifying, if the memory alignment is known
6619    to be at least 32bit.  MEM is the memory location for the actual operation
6620    and MODE its mode.  */
6621
6622 static void
6623 init_alignment_context (struct alignment_context *ac, rtx mem,
6624                         machine_mode mode)
6625 {
6626   ac->shift = GEN_INT (GET_MODE_SIZE (SImode) - GET_MODE_SIZE (mode));
6627   ac->aligned = (MEM_ALIGN (mem) >= GET_MODE_BITSIZE (SImode));
6628
6629   if (ac->aligned)
6630     ac->memsi = adjust_address (mem, SImode, 0); /* Memory is aligned.  */
6631   else
6632     {
6633       /* Alignment is unknown.  */
6634       rtx byteoffset, addr, align;
6635
6636       /* Force the address into a register.  */
6637       addr = force_reg (Pmode, XEXP (mem, 0));
6638
6639       /* Align it to SImode.  */
6640       align = expand_simple_binop (Pmode, AND, addr,
6641                                    GEN_INT (-GET_MODE_SIZE (SImode)),
6642                                    NULL_RTX, 1, OPTAB_DIRECT);
6643       /* Generate MEM.  */
6644       ac->memsi = gen_rtx_MEM (SImode, align);
6645       MEM_VOLATILE_P (ac->memsi) = MEM_VOLATILE_P (mem);
6646       set_mem_alias_set (ac->memsi, ALIAS_SET_MEMORY_BARRIER);
6647       set_mem_align (ac->memsi, GET_MODE_BITSIZE (SImode));
6648
6649       /* Calculate shiftcount.  */
6650       byteoffset = expand_simple_binop (Pmode, AND, addr,
6651                                         GEN_INT (GET_MODE_SIZE (SImode) - 1),
6652                                         NULL_RTX, 1, OPTAB_DIRECT);
6653       /* As we already have some offset, evaluate the remaining distance.  */
6654       ac->shift = expand_simple_binop (SImode, MINUS, ac->shift, byteoffset,
6655                                       NULL_RTX, 1, OPTAB_DIRECT);
6656     }
6657
6658   /* Shift is the byte count, but we need the bitcount.  */
6659   ac->shift = expand_simple_binop (SImode, ASHIFT, ac->shift, GEN_INT (3),
6660                                    NULL_RTX, 1, OPTAB_DIRECT);
6661
6662   /* Calculate masks.  */
6663   ac->modemask = expand_simple_binop (SImode, ASHIFT,
6664                                       GEN_INT (GET_MODE_MASK (mode)),
6665                                       ac->shift, NULL_RTX, 1, OPTAB_DIRECT);
6666   ac->modemaski = expand_simple_unop (SImode, NOT, ac->modemask,
6667                                       NULL_RTX, 1);
6668 }
6669
6670 /* A subroutine of s390_expand_cs_hqi.  Insert INS into VAL.  If possible,
6671    use a single insv insn into SEQ2.  Otherwise, put prep insns in SEQ1 and
6672    perform the merge in SEQ2.  */
6673
6674 static rtx
6675 s390_two_part_insv (struct alignment_context *ac, rtx *seq1, rtx *seq2,
6676                     machine_mode mode, rtx val, rtx ins)
6677 {
6678   rtx tmp;
6679
6680   if (ac->aligned)
6681     {
6682       start_sequence ();
6683       tmp = copy_to_mode_reg (SImode, val);
6684       if (s390_expand_insv (tmp, GEN_INT (GET_MODE_BITSIZE (mode)),
6685                             const0_rtx, ins))
6686         {
6687           *seq1 = NULL;
6688           *seq2 = get_insns ();
6689           end_sequence ();
6690           return tmp;
6691         }
6692       end_sequence ();
6693     }
6694
6695   /* Failed to use insv.  Generate a two part shift and mask.  */
6696   start_sequence ();
6697   tmp = s390_expand_mask_and_shift (ins, mode, ac->shift);
6698   *seq1 = get_insns ();
6699   end_sequence ();
6700
6701   start_sequence ();
6702   tmp = expand_simple_binop (SImode, IOR, tmp, val, NULL_RTX, 1, OPTAB_DIRECT);
6703   *seq2 = get_insns ();
6704   end_sequence ();
6705
6706   return tmp;
6707 }
6708
6709 /* Expand an atomic compare and swap operation for HImode and QImode.  MEM is
6710    the memory location, CMP the old value to compare MEM with and NEW_RTX the
6711    value to set if CMP == MEM.  */
6712
6713 void
6714 s390_expand_cs_hqi (machine_mode mode, rtx btarget, rtx vtarget, rtx mem,
6715                     rtx cmp, rtx new_rtx, bool is_weak)
6716 {
6717   struct alignment_context ac;
6718   rtx cmpv, newv, val, cc, seq0, seq1, seq2, seq3;
6719   rtx res = gen_reg_rtx (SImode);
6720   rtx_code_label *csloop = NULL, *csend = NULL;
6721
6722   gcc_assert (MEM_P (mem));
6723
6724   init_alignment_context (&ac, mem, mode);
6725
6726   /* Load full word.  Subsequent loads are performed by CS.  */
6727   val = expand_simple_binop (SImode, AND, ac.memsi, ac.modemaski,
6728                              NULL_RTX, 1, OPTAB_DIRECT);
6729
6730   /* Prepare insertions of cmp and new_rtx into the loaded value.  When
6731      possible, we try to use insv to make this happen efficiently.  If
6732      that fails we'll generate code both inside and outside the loop.  */
6733   cmpv = s390_two_part_insv (&ac, &seq0, &seq2, mode, val, cmp);
6734   newv = s390_two_part_insv (&ac, &seq1, &seq3, mode, val, new_rtx);
6735
6736   if (seq0)
6737     emit_insn (seq0);
6738   if (seq1)
6739     emit_insn (seq1);
6740
6741   /* Start CS loop.  */
6742   if (!is_weak)
6743     {
6744       /* Begin assuming success.  */
6745       emit_move_insn (btarget, const1_rtx);
6746
6747       csloop = gen_label_rtx ();
6748       csend = gen_label_rtx ();
6749       emit_label (csloop);
6750     }
6751
6752   /* val = "<mem>00..0<mem>"
6753    * cmp = "00..0<cmp>00..0"
6754    * new = "00..0<new>00..0"
6755    */
6756
6757   emit_insn (seq2);
6758   emit_insn (seq3);
6759
6760   cc = s390_emit_compare_and_swap (EQ, res, ac.memsi, cmpv, newv);
6761   if (is_weak)
6762     emit_insn (gen_cstorecc4 (btarget, cc, XEXP (cc, 0), XEXP (cc, 1)));
6763   else
6764     {
6765       rtx tmp;
6766
6767       /* Jump to end if we're done (likely?).  */
6768       s390_emit_jump (csend, cc);
6769
6770       /* Check for changes outside mode, and loop internal if so.
6771          Arrange the moves so that the compare is adjacent to the
6772          branch so that we can generate CRJ.  */
6773       tmp = copy_to_reg (val);
6774       force_expand_binop (SImode, and_optab, res, ac.modemaski, val,
6775                           1, OPTAB_DIRECT);
6776       cc = s390_emit_compare (NE, val, tmp);
6777       s390_emit_jump (csloop, cc);
6778
6779       /* Failed.  */
6780       emit_move_insn (btarget, const0_rtx);
6781       emit_label (csend);
6782     }
6783
6784   /* Return the correct part of the bitfield.  */
6785   convert_move (vtarget, expand_simple_binop (SImode, LSHIFTRT, res, ac.shift,
6786                                               NULL_RTX, 1, OPTAB_DIRECT), 1);
6787 }
6788
6789 /* Expand an atomic operation CODE of mode MODE.  MEM is the memory location
6790    and VAL the value to play with.  If AFTER is true then store the value
6791    MEM holds after the operation, if AFTER is false then store the value MEM
6792    holds before the operation.  If TARGET is zero then discard that value, else
6793    store it to TARGET.  */
6794
6795 void
6796 s390_expand_atomic (machine_mode mode, enum rtx_code code,
6797                     rtx target, rtx mem, rtx val, bool after)
6798 {
6799   struct alignment_context ac;
6800   rtx cmp;
6801   rtx new_rtx = gen_reg_rtx (SImode);
6802   rtx orig = gen_reg_rtx (SImode);
6803   rtx_code_label *csloop = gen_label_rtx ();
6804
6805   gcc_assert (!target || register_operand (target, VOIDmode));
6806   gcc_assert (MEM_P (mem));
6807
6808   init_alignment_context (&ac, mem, mode);
6809
6810   /* Shift val to the correct bit positions.
6811      Preserve "icm", but prevent "ex icm".  */
6812   if (!(ac.aligned && code == SET && MEM_P (val)))
6813     val = s390_expand_mask_and_shift (val, mode, ac.shift);
6814
6815   /* Further preparation insns.  */
6816   if (code == PLUS || code == MINUS)
6817     emit_move_insn (orig, val);
6818   else if (code == MULT || code == AND) /* val = "11..1<val>11..1" */
6819     val = expand_simple_binop (SImode, XOR, val, ac.modemaski,
6820                                NULL_RTX, 1, OPTAB_DIRECT);
6821
6822   /* Load full word.  Subsequent loads are performed by CS.  */
6823   cmp = force_reg (SImode, ac.memsi);
6824
6825   /* Start CS loop.  */
6826   emit_label (csloop);
6827   emit_move_insn (new_rtx, cmp);
6828
6829   /* Patch new with val at correct position.  */
6830   switch (code)
6831     {
6832     case PLUS:
6833     case MINUS:
6834       val = expand_simple_binop (SImode, code, new_rtx, orig,
6835                                  NULL_RTX, 1, OPTAB_DIRECT);
6836       val = expand_simple_binop (SImode, AND, val, ac.modemask,
6837                                  NULL_RTX, 1, OPTAB_DIRECT);
6838       /* FALLTHRU */
6839     case SET:
6840       if (ac.aligned && MEM_P (val))
6841         store_bit_field (new_rtx, GET_MODE_BITSIZE (mode), 0,
6842                          0, 0, SImode, val, false);
6843       else
6844         {
6845           new_rtx = expand_simple_binop (SImode, AND, new_rtx, ac.modemaski,
6846                                      NULL_RTX, 1, OPTAB_DIRECT);
6847           new_rtx = expand_simple_binop (SImode, IOR, new_rtx, val,
6848                                      NULL_RTX, 1, OPTAB_DIRECT);
6849         }
6850       break;
6851     case AND:
6852     case IOR:
6853     case XOR:
6854       new_rtx = expand_simple_binop (SImode, code, new_rtx, val,
6855                                  NULL_RTX, 1, OPTAB_DIRECT);
6856       break;
6857     case MULT: /* NAND */
6858       new_rtx = expand_simple_binop (SImode, AND, new_rtx, val,
6859                                  NULL_RTX, 1, OPTAB_DIRECT);
6860       new_rtx = expand_simple_binop (SImode, XOR, new_rtx, ac.modemask,
6861                                  NULL_RTX, 1, OPTAB_DIRECT);
6862       break;
6863     default:
6864       gcc_unreachable ();
6865     }
6866
6867   s390_emit_jump (csloop, s390_emit_compare_and_swap (NE, cmp,
6868                                                       ac.memsi, cmp, new_rtx));
6869
6870   /* Return the correct part of the bitfield.  */
6871   if (target)
6872     convert_move (target, expand_simple_binop (SImode, LSHIFTRT,
6873                                                after ? new_rtx : cmp, ac.shift,
6874                                                NULL_RTX, 1, OPTAB_DIRECT), 1);
6875 }
6876
6877 /* This is called from dwarf2out.c via TARGET_ASM_OUTPUT_DWARF_DTPREL.
6878    We need to emit DTP-relative relocations.  */
6879
6880 static void s390_output_dwarf_dtprel (FILE *, int, rtx) ATTRIBUTE_UNUSED;
6881
6882 static void
6883 s390_output_dwarf_dtprel (FILE *file, int size, rtx x)
6884 {
6885   switch (size)
6886     {
6887     case 4:
6888       fputs ("\t.long\t", file);
6889       break;
6890     case 8:
6891       fputs ("\t.quad\t", file);
6892       break;
6893     default:
6894       gcc_unreachable ();
6895     }
6896   output_addr_const (file, x);
6897   fputs ("@DTPOFF", file);
6898 }
6899
6900 /* Return the proper mode for REGNO being represented in the dwarf
6901    unwind table.  */
6902 machine_mode
6903 s390_dwarf_frame_reg_mode (int regno)
6904 {
6905   machine_mode save_mode = default_dwarf_frame_reg_mode (regno);
6906
6907   /* Make sure not to return DImode for any GPR with -m31 -mzarch.  */
6908   if (GENERAL_REGNO_P (regno))
6909     save_mode = Pmode;
6910
6911   /* The rightmost 64 bits of vector registers are call-clobbered.  */
6912   if (GET_MODE_SIZE (save_mode) > 8)
6913     save_mode = DImode;
6914
6915   return save_mode;
6916 }
6917
6918 #ifdef TARGET_ALTERNATE_LONG_DOUBLE_MANGLING
6919 /* Implement TARGET_MANGLE_TYPE.  */
6920
6921 static const char *
6922 s390_mangle_type (const_tree type)
6923 {
6924   type = TYPE_MAIN_VARIANT (type);
6925
6926   if (TREE_CODE (type) != VOID_TYPE && TREE_CODE (type) != BOOLEAN_TYPE
6927       && TREE_CODE (type) != INTEGER_TYPE && TREE_CODE (type) != REAL_TYPE)
6928     return NULL;
6929
6930   if (type == s390_builtin_types[BT_BV16QI]) return "U6__boolc";
6931   if (type == s390_builtin_types[BT_BV8HI]) return "U6__bools";
6932   if (type == s390_builtin_types[BT_BV4SI]) return "U6__booli";
6933   if (type == s390_builtin_types[BT_BV2DI]) return "U6__booll";
6934
6935   if (TYPE_MAIN_VARIANT (type) == long_double_type_node
6936       && TARGET_LONG_DOUBLE_128)
6937     return "g";
6938
6939   /* For all other types, use normal C++ mangling.  */
6940   return NULL;
6941 }
6942 #endif
6943
6944 /* In the name of slightly smaller debug output, and to cater to
6945    general assembler lossage, recognize various UNSPEC sequences
6946    and turn them back into a direct symbol reference.  */
6947
6948 static rtx
6949 s390_delegitimize_address (rtx orig_x)
6950 {
6951   rtx x, y;
6952
6953   orig_x = delegitimize_mem_from_attrs (orig_x);
6954   x = orig_x;
6955
6956   /* Extract the symbol ref from:
6957      (plus:SI (reg:SI 12 %r12)
6958               (const:SI (unspec:SI [(symbol_ref/f:SI ("*.LC0"))]
6959                                     UNSPEC_GOTOFF/PLTOFF)))
6960      and
6961      (plus:SI (reg:SI 12 %r12)
6962               (const:SI (plus:SI (unspec:SI [(symbol_ref:SI ("L"))]
6963                                              UNSPEC_GOTOFF/PLTOFF)
6964                                  (const_int 4 [0x4]))))  */
6965   if (GET_CODE (x) == PLUS
6966       && REG_P (XEXP (x, 0))
6967       && REGNO (XEXP (x, 0)) == PIC_OFFSET_TABLE_REGNUM
6968       && GET_CODE (XEXP (x, 1)) == CONST)
6969     {
6970       HOST_WIDE_INT offset = 0;
6971
6972       /* The const operand.  */
6973       y = XEXP (XEXP (x, 1), 0);
6974
6975       if (GET_CODE (y) == PLUS
6976           && GET_CODE (XEXP (y, 1)) == CONST_INT)
6977         {
6978           offset = INTVAL (XEXP (y, 1));
6979           y = XEXP (y, 0);
6980         }
6981
6982       if (GET_CODE (y) == UNSPEC
6983           && (XINT (y, 1) == UNSPEC_GOTOFF
6984               || XINT (y, 1) == UNSPEC_PLTOFF))
6985         return plus_constant (Pmode, XVECEXP (y, 0, 0), offset);
6986     }
6987
6988   if (GET_CODE (x) != MEM)
6989     return orig_x;
6990
6991   x = XEXP (x, 0);
6992   if (GET_CODE (x) == PLUS
6993       && GET_CODE (XEXP (x, 1)) == CONST
6994       && GET_CODE (XEXP (x, 0)) == REG
6995       && REGNO (XEXP (x, 0)) == PIC_OFFSET_TABLE_REGNUM)
6996     {
6997       y = XEXP (XEXP (x, 1), 0);
6998       if (GET_CODE (y) == UNSPEC
6999           && XINT (y, 1) == UNSPEC_GOT)
7000         y = XVECEXP (y, 0, 0);
7001       else
7002         return orig_x;
7003     }
7004   else if (GET_CODE (x) == CONST)
7005     {
7006       /* Extract the symbol ref from:
7007          (mem:QI (const:DI (unspec:DI [(symbol_ref:DI ("foo"))]
7008                                        UNSPEC_PLT/GOTENT)))  */
7009
7010       y = XEXP (x, 0);
7011       if (GET_CODE (y) == UNSPEC
7012           && (XINT (y, 1) == UNSPEC_GOTENT
7013               || XINT (y, 1) == UNSPEC_PLT))
7014         y = XVECEXP (y, 0, 0);
7015       else
7016         return orig_x;
7017     }
7018   else
7019     return orig_x;
7020
7021   if (GET_MODE (orig_x) != Pmode)
7022     {
7023       if (GET_MODE (orig_x) == BLKmode)
7024         return orig_x;
7025       y = lowpart_subreg (GET_MODE (orig_x), y, Pmode);
7026       if (y == NULL_RTX)
7027         return orig_x;
7028     }
7029   return y;
7030 }
7031
7032 /* Output operand OP to stdio stream FILE.
7033    OP is an address (register + offset) which is not used to address data;
7034    instead the rightmost bits are interpreted as the value.  */
7035
7036 static void
7037 print_addrstyle_operand (FILE *file, rtx op)
7038 {
7039   HOST_WIDE_INT offset;
7040   rtx base;
7041
7042   /* Extract base register and offset.  */
7043   if (!s390_decompose_addrstyle_without_index (op, &base, &offset))
7044     gcc_unreachable ();
7045
7046   /* Sanity check.  */
7047   if (base)
7048     {
7049       gcc_assert (GET_CODE (base) == REG);
7050       gcc_assert (REGNO (base) < FIRST_PSEUDO_REGISTER);
7051       gcc_assert (REGNO_REG_CLASS (REGNO (base)) == ADDR_REGS);
7052     }
7053
7054   /* Offsets are constricted to twelve bits.  */
7055   fprintf (file, HOST_WIDE_INT_PRINT_DEC, offset & ((1 << 12) - 1));
7056   if (base)
7057     fprintf (file, "(%s)", reg_names[REGNO (base)]);
7058 }
7059
7060 /* Assigns the number of NOP halfwords to be emitted before and after the
7061    function label to *HW_BEFORE and *HW_AFTER.  Both pointers must not be NULL.
7062    If hotpatching is disabled for the function, the values are set to zero.
7063 */
7064
7065 static void
7066 s390_function_num_hotpatch_hw (tree decl,
7067                                int *hw_before,
7068                                int *hw_after)
7069 {
7070   tree attr;
7071
7072   attr = lookup_attribute ("hotpatch", DECL_ATTRIBUTES (decl));
7073
7074   /* Handle the arguments of the hotpatch attribute.  The values
7075      specified via attribute might override the cmdline argument
7076      values.  */
7077   if (attr)
7078     {
7079       tree args = TREE_VALUE (attr);
7080
7081       *hw_before = TREE_INT_CST_LOW (TREE_VALUE (args));
7082       *hw_after = TREE_INT_CST_LOW (TREE_VALUE (TREE_CHAIN (args)));
7083     }
7084   else
7085     {
7086       /* Use the values specified by the cmdline arguments.  */
7087       *hw_before = s390_hotpatch_hw_before_label;
7088       *hw_after = s390_hotpatch_hw_after_label;
7089     }
7090 }
7091
7092 /* Write the current .machine and .machinemode specification to the assembler
7093    file.  */
7094
7095 #ifdef HAVE_AS_MACHINE_MACHINEMODE
7096 static void
7097 s390_asm_output_machine_for_arch (FILE *asm_out_file)
7098 {
7099   fprintf (asm_out_file, "\t.machinemode %s\n",
7100            (TARGET_ZARCH) ? "zarch" : "esa");
7101   fprintf (asm_out_file, "\t.machine \"%s", processor_table[s390_arch].name);
7102   if (S390_USE_ARCHITECTURE_MODIFIERS)
7103     {
7104       int cpu_flags;
7105
7106       cpu_flags = processor_flags_table[(int) s390_arch];
7107       if (TARGET_HTM && !(cpu_flags & PF_TX))
7108         fprintf (asm_out_file, "+htm");
7109       else if (!TARGET_HTM && (cpu_flags & PF_TX))
7110         fprintf (asm_out_file, "+nohtm");
7111       if (TARGET_VX && !(cpu_flags & PF_VX))
7112         fprintf (asm_out_file, "+vx");
7113       else if (!TARGET_VX && (cpu_flags & PF_VX))
7114         fprintf (asm_out_file, "+novx");
7115     }
7116   fprintf (asm_out_file, "\"\n");
7117 }
7118
7119 /* Write an extra function header before the very start of the function.  */
7120
7121 void
7122 s390_asm_output_function_prefix (FILE *asm_out_file,
7123                                  const char *fnname ATTRIBUTE_UNUSED)
7124 {
7125   if (DECL_FUNCTION_SPECIFIC_TARGET (current_function_decl) == NULL)
7126     return;
7127   /* Since only the function specific options are saved but not the indications
7128      which options are set, it's too much work here to figure out which options
7129      have actually changed.  Thus, generate .machine and .machinemode whenever a
7130      function has the target attribute or pragma.  */
7131   fprintf (asm_out_file, "\t.machinemode push\n");
7132   fprintf (asm_out_file, "\t.machine push\n");
7133   s390_asm_output_machine_for_arch (asm_out_file);
7134 }
7135
7136 /* Write an extra function footer after the very end of the function.  */
7137
7138 void
7139 s390_asm_declare_function_size (FILE *asm_out_file,
7140                                 const char *fnname, tree decl)
7141 {
7142   if (!flag_inhibit_size_directive)
7143     ASM_OUTPUT_MEASURED_SIZE (asm_out_file, fnname);
7144   if (DECL_FUNCTION_SPECIFIC_TARGET (decl) == NULL)
7145     return;
7146   fprintf (asm_out_file, "\t.machine pop\n");
7147   fprintf (asm_out_file, "\t.machinemode pop\n");
7148 }
7149 #endif
7150
7151 /* Write the extra assembler code needed to declare a function properly.  */
7152
7153 void
7154 s390_asm_output_function_label (FILE *asm_out_file, const char *fname,
7155                                 tree decl)
7156 {
7157   int hw_before, hw_after;
7158
7159   s390_function_num_hotpatch_hw (decl, &hw_before, &hw_after);
7160   if (hw_before > 0)
7161     {
7162       unsigned int function_alignment;
7163       int i;
7164
7165       /* Add a trampoline code area before the function label and initialize it
7166          with two-byte nop instructions.  This area can be overwritten with code
7167          that jumps to a patched version of the function.  */
7168       asm_fprintf (asm_out_file, "\tnopr\t%%r0"
7169                    "\t# pre-label NOPs for hotpatch (%d halfwords)\n",
7170                    hw_before);
7171       for (i = 1; i < hw_before; i++)
7172         fputs ("\tnopr\t%r0\n", asm_out_file);
7173
7174       /* Note:  The function label must be aligned so that (a) the bytes of the
7175          following nop do not cross a cacheline boundary, and (b) a jump address
7176          (eight bytes for 64 bit targets, 4 bytes for 32 bit targets) can be
7177          stored directly before the label without crossing a cacheline
7178          boundary.  All this is necessary to make sure the trampoline code can
7179          be changed atomically.
7180          This alignment is done automatically using the FOUNCTION_BOUNDARY, but
7181          if there are NOPs before the function label, the alignment is placed
7182          before them.  So it is necessary to duplicate the alignment after the
7183          NOPs.  */
7184       function_alignment = MAX (8, DECL_ALIGN (decl) / BITS_PER_UNIT);
7185       if (! DECL_USER_ALIGN (decl))
7186         function_alignment = MAX (function_alignment,
7187                                   (unsigned int) align_functions);
7188       fputs ("\t# alignment for hotpatch\n", asm_out_file);
7189       ASM_OUTPUT_ALIGN (asm_out_file, floor_log2 (function_alignment));
7190     }
7191
7192   if (S390_USE_TARGET_ATTRIBUTE && TARGET_DEBUG_ARG)
7193     {
7194       asm_fprintf (asm_out_file, "\t# fn:%s ar%d\n", fname, s390_arch);
7195       asm_fprintf (asm_out_file, "\t# fn:%s tu%d\n", fname, s390_tune);
7196       asm_fprintf (asm_out_file, "\t# fn:%s sg%d\n", fname, s390_stack_guard);
7197       asm_fprintf (asm_out_file, "\t# fn:%s ss%d\n", fname, s390_stack_size);
7198       asm_fprintf (asm_out_file, "\t# fn:%s bc%d\n", fname, s390_branch_cost);
7199       asm_fprintf (asm_out_file, "\t# fn:%s wf%d\n", fname,
7200                    s390_warn_framesize);
7201       asm_fprintf (asm_out_file, "\t# fn:%s ba%d\n", fname, TARGET_BACKCHAIN);
7202       asm_fprintf (asm_out_file, "\t# fn:%s hd%d\n", fname, TARGET_HARD_DFP);
7203       asm_fprintf (asm_out_file, "\t# fn:%s hf%d\n", fname, !TARGET_SOFT_FLOAT);
7204       asm_fprintf (asm_out_file, "\t# fn:%s ht%d\n", fname, TARGET_OPT_HTM);
7205       asm_fprintf (asm_out_file, "\t# fn:%s vx%d\n", fname, TARGET_OPT_VX);
7206       asm_fprintf (asm_out_file, "\t# fn:%s ps%d\n", fname,
7207                    TARGET_PACKED_STACK);
7208       asm_fprintf (asm_out_file, "\t# fn:%s se%d\n", fname, TARGET_SMALL_EXEC);
7209       asm_fprintf (asm_out_file, "\t# fn:%s mv%d\n", fname, TARGET_MVCLE);
7210       asm_fprintf (asm_out_file, "\t# fn:%s zv%d\n", fname, TARGET_ZVECTOR);
7211       asm_fprintf (asm_out_file, "\t# fn:%s wd%d\n", fname,
7212                    s390_warn_dynamicstack_p);
7213     }
7214   ASM_OUTPUT_LABEL (asm_out_file, fname);
7215   if (hw_after > 0)
7216     asm_fprintf (asm_out_file,
7217                  "\t# post-label NOPs for hotpatch (%d halfwords)\n",
7218                  hw_after);
7219 }
7220
7221 /* Output machine-dependent UNSPECs occurring in address constant X
7222    in assembler syntax to stdio stream FILE.  Returns true if the
7223    constant X could be recognized, false otherwise.  */
7224
7225 static bool
7226 s390_output_addr_const_extra (FILE *file, rtx x)
7227 {
7228   if (GET_CODE (x) == UNSPEC && XVECLEN (x, 0) == 1)
7229     switch (XINT (x, 1))
7230       {
7231       case UNSPEC_GOTENT:
7232         output_addr_const (file, XVECEXP (x, 0, 0));
7233         fprintf (file, "@GOTENT");
7234         return true;
7235       case UNSPEC_GOT:
7236         output_addr_const (file, XVECEXP (x, 0, 0));
7237         fprintf (file, "@GOT");
7238         return true;
7239       case UNSPEC_GOTOFF:
7240         output_addr_const (file, XVECEXP (x, 0, 0));
7241         fprintf (file, "@GOTOFF");
7242         return true;
7243       case UNSPEC_PLT:
7244         output_addr_const (file, XVECEXP (x, 0, 0));
7245         fprintf (file, "@PLT");
7246         return true;
7247       case UNSPEC_PLTOFF:
7248         output_addr_const (file, XVECEXP (x, 0, 0));
7249         fprintf (file, "@PLTOFF");
7250         return true;
7251       case UNSPEC_TLSGD:
7252         output_addr_const (file, XVECEXP (x, 0, 0));
7253         fprintf (file, "@TLSGD");
7254         return true;
7255       case UNSPEC_TLSLDM:
7256         assemble_name (file, get_some_local_dynamic_name ());
7257         fprintf (file, "@TLSLDM");
7258         return true;
7259       case UNSPEC_DTPOFF:
7260         output_addr_const (file, XVECEXP (x, 0, 0));
7261         fprintf (file, "@DTPOFF");
7262         return true;
7263       case UNSPEC_NTPOFF:
7264         output_addr_const (file, XVECEXP (x, 0, 0));
7265         fprintf (file, "@NTPOFF");
7266         return true;
7267       case UNSPEC_GOTNTPOFF:
7268         output_addr_const (file, XVECEXP (x, 0, 0));
7269         fprintf (file, "@GOTNTPOFF");
7270         return true;
7271       case UNSPEC_INDNTPOFF:
7272         output_addr_const (file, XVECEXP (x, 0, 0));
7273         fprintf (file, "@INDNTPOFF");
7274         return true;
7275       }
7276
7277   if (GET_CODE (x) == UNSPEC && XVECLEN (x, 0) == 2)
7278     switch (XINT (x, 1))
7279       {
7280       case UNSPEC_POOL_OFFSET:
7281         x = gen_rtx_MINUS (GET_MODE (x), XVECEXP (x, 0, 0), XVECEXP (x, 0, 1));
7282         output_addr_const (file, x);
7283         return true;
7284       }
7285   return false;
7286 }
7287
7288 /* Output address operand ADDR in assembler syntax to
7289    stdio stream FILE.  */
7290
7291 void
7292 print_operand_address (FILE *file, rtx addr)
7293 {
7294   struct s390_address ad;
7295   memset (&ad, 0, sizeof (s390_address));
7296
7297   if (s390_loadrelative_operand_p (addr, NULL, NULL))
7298     {
7299       if (!TARGET_Z10)
7300         {
7301           output_operand_lossage ("symbolic memory references are "
7302                                   "only supported on z10 or later");
7303           return;
7304         }
7305       output_addr_const (file, addr);
7306       return;
7307     }
7308
7309   if (!s390_decompose_address (addr, &ad)
7310       || (ad.base && !REGNO_OK_FOR_BASE_P (REGNO (ad.base)))
7311       || (ad.indx && !REGNO_OK_FOR_INDEX_P (REGNO (ad.indx))))
7312     output_operand_lossage ("cannot decompose address");
7313
7314   if (ad.disp)
7315     output_addr_const (file, ad.disp);
7316   else
7317     fprintf (file, "0");
7318
7319   if (ad.base && ad.indx)
7320     fprintf (file, "(%s,%s)", reg_names[REGNO (ad.indx)],
7321                               reg_names[REGNO (ad.base)]);
7322   else if (ad.base)
7323     fprintf (file, "(%s)", reg_names[REGNO (ad.base)]);
7324 }
7325
7326 /* Output operand X in assembler syntax to stdio stream FILE.
7327    CODE specified the format flag.  The following format flags
7328    are recognized:
7329
7330     'C': print opcode suffix for branch condition.
7331     'D': print opcode suffix for inverse branch condition.
7332     'E': print opcode suffix for branch on index instruction.
7333     'G': print the size of the operand in bytes.
7334     'J': print tls_load/tls_gdcall/tls_ldcall suffix
7335     'M': print the second word of a TImode operand.
7336     'N': print the second word of a DImode operand.
7337     'O': print only the displacement of a memory reference or address.
7338     'R': print only the base register of a memory reference or address.
7339     'S': print S-type memory reference (base+displacement).
7340     'Y': print address style operand without index (e.g. shift count or setmem
7341          operand).
7342
7343     'b': print integer X as if it's an unsigned byte.
7344     'c': print integer X as if it's an signed byte.
7345     'e': "end" contiguous bitmask X in either DImode or vector inner mode.
7346     'f': "end" contiguous bitmask X in SImode.
7347     'h': print integer X as if it's a signed halfword.
7348     'i': print the first nonzero HImode part of X.
7349     'j': print the first HImode part unequal to -1 of X.
7350     'k': print the first nonzero SImode part of X.
7351     'm': print the first SImode part unequal to -1 of X.
7352     'o': print integer X as if it's an unsigned 32bit word.
7353     's': "start" of contiguous bitmask X in either DImode or vector inner mode.
7354     't': CONST_INT: "start" of contiguous bitmask X in SImode.
7355          CONST_VECTOR: Generate a bitmask for vgbm instruction.
7356     'x': print integer X as if it's an unsigned halfword.
7357     'v': print register number as vector register (v1 instead of f1).
7358 */
7359
7360 void
7361 print_operand (FILE *file, rtx x, int code)
7362 {
7363   HOST_WIDE_INT ival;
7364
7365   switch (code)
7366     {
7367     case 'C':
7368       fprintf (file, s390_branch_condition_mnemonic (x, FALSE));
7369       return;
7370
7371     case 'D':
7372       fprintf (file, s390_branch_condition_mnemonic (x, TRUE));
7373       return;
7374
7375     case 'E':
7376       if (GET_CODE (x) == LE)
7377         fprintf (file, "l");
7378       else if (GET_CODE (x) == GT)
7379         fprintf (file, "h");
7380       else
7381         output_operand_lossage ("invalid comparison operator "
7382                                 "for 'E' output modifier");
7383       return;
7384
7385     case 'J':
7386       if (GET_CODE (x) == SYMBOL_REF)
7387         {
7388           fprintf (file, "%s", ":tls_load:");
7389           output_addr_const (file, x);
7390         }
7391       else if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_TLSGD)
7392         {
7393           fprintf (file, "%s", ":tls_gdcall:");
7394           output_addr_const (file, XVECEXP (x, 0, 0));
7395         }
7396       else if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_TLSLDM)
7397         {
7398           fprintf (file, "%s", ":tls_ldcall:");
7399           const char *name = get_some_local_dynamic_name ();
7400           gcc_assert (name);
7401           assemble_name (file, name);
7402         }
7403       else
7404         output_operand_lossage ("invalid reference for 'J' output modifier");
7405       return;
7406
7407     case 'G':
7408       fprintf (file, "%u", GET_MODE_SIZE (GET_MODE (x)));
7409       return;
7410
7411     case 'O':
7412       {
7413         struct s390_address ad;
7414         int ret;
7415
7416         ret = s390_decompose_address (MEM_P (x) ? XEXP (x, 0) : x, &ad);
7417
7418         if (!ret
7419             || (ad.base && !REGNO_OK_FOR_BASE_P (REGNO (ad.base)))
7420             || ad.indx)
7421           {
7422             output_operand_lossage ("invalid address for 'O' output modifier");
7423             return;
7424           }
7425
7426         if (ad.disp)
7427           output_addr_const (file, ad.disp);
7428         else
7429           fprintf (file, "0");
7430       }
7431       return;
7432
7433     case 'R':
7434       {
7435         struct s390_address ad;
7436         int ret;
7437
7438         ret = s390_decompose_address (MEM_P (x) ? XEXP (x, 0) : x, &ad);
7439
7440         if (!ret
7441             || (ad.base && !REGNO_OK_FOR_BASE_P (REGNO (ad.base)))
7442             || ad.indx)
7443           {
7444             output_operand_lossage ("invalid address for 'R' output modifier");
7445             return;
7446           }
7447
7448         if (ad.base)
7449           fprintf (file, "%s", reg_names[REGNO (ad.base)]);
7450         else
7451           fprintf (file, "0");
7452       }
7453       return;
7454
7455     case 'S':
7456       {
7457         struct s390_address ad;
7458         int ret;
7459
7460         if (!MEM_P (x))
7461           {
7462             output_operand_lossage ("memory reference expected for "
7463                                     "'S' output modifier");
7464             return;
7465           }
7466         ret = s390_decompose_address (XEXP (x, 0), &ad);
7467
7468         if (!ret
7469             || (ad.base && !REGNO_OK_FOR_BASE_P (REGNO (ad.base)))
7470             || ad.indx)
7471           {
7472             output_operand_lossage ("invalid address for 'S' output modifier");
7473             return;
7474           }
7475
7476         if (ad.disp)
7477           output_addr_const (file, ad.disp);
7478         else
7479           fprintf (file, "0");
7480
7481         if (ad.base)
7482           fprintf (file, "(%s)", reg_names[REGNO (ad.base)]);
7483       }
7484       return;
7485
7486     case 'N':
7487       if (GET_CODE (x) == REG)
7488         x = gen_rtx_REG (GET_MODE (x), REGNO (x) + 1);
7489       else if (GET_CODE (x) == MEM)
7490         x = change_address (x, VOIDmode,
7491                             plus_constant (Pmode, XEXP (x, 0), 4));
7492       else
7493         output_operand_lossage ("register or memory expression expected "
7494                                 "for 'N' output modifier");
7495       break;
7496
7497     case 'M':
7498       if (GET_CODE (x) == REG)
7499         x = gen_rtx_REG (GET_MODE (x), REGNO (x) + 1);
7500       else if (GET_CODE (x) == MEM)
7501         x = change_address (x, VOIDmode,
7502                             plus_constant (Pmode, XEXP (x, 0), 8));
7503       else
7504         output_operand_lossage ("register or memory expression expected "
7505                                 "for 'M' output modifier");
7506       break;
7507
7508     case 'Y':
7509       print_addrstyle_operand (file, x);
7510       return;
7511     }
7512
7513   switch (GET_CODE (x))
7514     {
7515     case REG:
7516       /* Print FP regs as fx instead of vx when they are accessed
7517          through non-vector mode.  */
7518       if (code == 'v'
7519           || VECTOR_NOFP_REG_P (x)
7520           || (FP_REG_P (x) && VECTOR_MODE_P (GET_MODE (x)))
7521           || (VECTOR_REG_P (x)
7522               && (GET_MODE_SIZE (GET_MODE (x)) /
7523                   s390_class_max_nregs (FP_REGS, GET_MODE (x))) > 8))
7524         fprintf (file, "%%v%s", reg_names[REGNO (x)] + 2);
7525       else
7526         fprintf (file, "%s", reg_names[REGNO (x)]);
7527       break;
7528
7529     case MEM:
7530       output_address (GET_MODE (x), XEXP (x, 0));
7531       break;
7532
7533     case CONST:
7534     case CODE_LABEL:
7535     case LABEL_REF:
7536     case SYMBOL_REF:
7537       output_addr_const (file, x);
7538       break;
7539
7540     case CONST_INT:
7541       ival = INTVAL (x);
7542       switch (code)
7543         {
7544         case 0:
7545           break;
7546         case 'b':
7547           ival &= 0xff;
7548           break;
7549         case 'c':
7550           ival = ((ival & 0xff) ^ 0x80) - 0x80;
7551           break;
7552         case 'x':
7553           ival &= 0xffff;
7554           break;
7555         case 'h':
7556           ival = ((ival & 0xffff) ^ 0x8000) - 0x8000;
7557           break;
7558         case 'i':
7559           ival = s390_extract_part (x, HImode, 0);
7560           break;
7561         case 'j':
7562           ival = s390_extract_part (x, HImode, -1);
7563           break;
7564         case 'k':
7565           ival = s390_extract_part (x, SImode, 0);
7566           break;
7567         case 'm':
7568           ival = s390_extract_part (x, SImode, -1);
7569           break;
7570         case 'o':
7571           ival &= 0xffffffff;
7572           break;
7573         case 'e': case 'f':
7574         case 's': case 't':
7575           {
7576             int start, end;
7577             int len;
7578             bool ok;
7579
7580             len = (code == 's' || code == 'e' ? 64 : 32);
7581             ok = s390_contiguous_bitmask_p (ival, true, len, &start, &end);
7582             gcc_assert (ok);
7583             if (code == 's' || code == 't')
7584               ival = start;
7585             else
7586               ival = end;
7587           }
7588           break;
7589         default:
7590           output_operand_lossage ("invalid constant for output modifier '%c'", code);
7591         }
7592       fprintf (file, HOST_WIDE_INT_PRINT_DEC, ival);
7593       break;
7594
7595     case CONST_WIDE_INT:
7596       if (code == 'b')
7597         fprintf (file, HOST_WIDE_INT_PRINT_DEC,
7598                  CONST_WIDE_INT_ELT (x, 0) & 0xff);
7599       else if (code == 'x')
7600         fprintf (file, HOST_WIDE_INT_PRINT_DEC,
7601                  CONST_WIDE_INT_ELT (x, 0) & 0xffff);
7602       else if (code == 'h')
7603         fprintf (file, HOST_WIDE_INT_PRINT_DEC,
7604                  ((CONST_WIDE_INT_ELT (x, 0) & 0xffff) ^ 0x8000) - 0x8000);
7605       else
7606         {
7607           if (code == 0)
7608             output_operand_lossage ("invalid constant - try using "
7609                                     "an output modifier");
7610           else
7611             output_operand_lossage ("invalid constant for output modifier '%c'",
7612                                     code);
7613         }
7614       break;
7615     case CONST_VECTOR:
7616       switch (code)
7617         {
7618         case 'h':
7619           gcc_assert (const_vec_duplicate_p (x));
7620           fprintf (file, HOST_WIDE_INT_PRINT_DEC,
7621                    ((INTVAL (XVECEXP (x, 0, 0)) & 0xffff) ^ 0x8000) - 0x8000);
7622           break;
7623         case 'e':
7624         case 's':
7625           {
7626             int start, end;
7627             bool ok;
7628
7629             ok = s390_contiguous_bitmask_vector_p (x, &start, &end);
7630             gcc_assert (ok);
7631             ival = (code == 's') ? start : end;
7632             fprintf (file, HOST_WIDE_INT_PRINT_DEC, ival);
7633           }
7634           break;
7635         case 't':
7636           {
7637             unsigned mask;
7638             bool ok = s390_bytemask_vector_p (x, &mask);
7639             gcc_assert (ok);
7640             fprintf (file, "%u", mask);
7641           }
7642           break;
7643
7644         default:
7645           output_operand_lossage ("invalid constant vector for output "
7646                                   "modifier '%c'", code);
7647         }
7648       break;
7649
7650     default:
7651       if (code == 0)
7652         output_operand_lossage ("invalid expression - try using "
7653                                 "an output modifier");
7654       else
7655         output_operand_lossage ("invalid expression for output "
7656                                 "modifier '%c'", code);
7657       break;
7658     }
7659 }
7660
7661 /* Target hook for assembling integer objects.  We need to define it
7662    here to work a round a bug in some versions of GAS, which couldn't
7663    handle values smaller than INT_MIN when printed in decimal.  */
7664
7665 static bool
7666 s390_assemble_integer (rtx x, unsigned int size, int aligned_p)
7667 {
7668   if (size == 8 && aligned_p
7669       && GET_CODE (x) == CONST_INT && INTVAL (x) < INT_MIN)
7670     {
7671       fprintf (asm_out_file, "\t.quad\t" HOST_WIDE_INT_PRINT_HEX "\n",
7672                INTVAL (x));
7673       return true;
7674     }
7675   return default_assemble_integer (x, size, aligned_p);
7676 }
7677
7678 /* Returns true if register REGNO is used  for forming
7679    a memory address in expression X.  */
7680
7681 static bool
7682 reg_used_in_mem_p (int regno, rtx x)
7683 {
7684   enum rtx_code code = GET_CODE (x);
7685   int i, j;
7686   const char *fmt;
7687
7688   if (code == MEM)
7689     {
7690       if (refers_to_regno_p (regno, XEXP (x, 0)))
7691         return true;
7692     }
7693   else if (code == SET
7694            && GET_CODE (SET_DEST (x)) == PC)
7695     {
7696       if (refers_to_regno_p (regno, SET_SRC (x)))
7697         return true;
7698     }
7699
7700   fmt = GET_RTX_FORMAT (code);
7701   for (i = GET_RTX_LENGTH (code) - 1; i >= 0; i--)
7702     {
7703       if (fmt[i] == 'e'
7704           && reg_used_in_mem_p (regno, XEXP (x, i)))
7705         return true;
7706
7707       else if (fmt[i] == 'E')
7708         for (j = 0; j < XVECLEN (x, i); j++)
7709           if (reg_used_in_mem_p (regno, XVECEXP (x, i, j)))
7710             return true;
7711     }
7712   return false;
7713 }
7714
7715 /* Returns true if expression DEP_RTX sets an address register
7716    used by instruction INSN to address memory.  */
7717
7718 static bool
7719 addr_generation_dependency_p (rtx dep_rtx, rtx_insn *insn)
7720 {
7721   rtx target, pat;
7722
7723   if (NONJUMP_INSN_P (dep_rtx))
7724     dep_rtx = PATTERN (dep_rtx);
7725
7726   if (GET_CODE (dep_rtx) == SET)
7727     {
7728       target = SET_DEST (dep_rtx);
7729       if (GET_CODE (target) == STRICT_LOW_PART)
7730         target = XEXP (target, 0);
7731       while (GET_CODE (target) == SUBREG)
7732         target = SUBREG_REG (target);
7733
7734       if (GET_CODE (target) == REG)
7735         {
7736           int regno = REGNO (target);
7737
7738           if (s390_safe_attr_type (insn) == TYPE_LA)
7739             {
7740               pat = PATTERN (insn);
7741               if (GET_CODE (pat) == PARALLEL)
7742                 {
7743                   gcc_assert (XVECLEN (pat, 0) == 2);
7744                   pat = XVECEXP (pat, 0, 0);
7745                 }
7746               gcc_assert (GET_CODE (pat) == SET);
7747               return refers_to_regno_p (regno, SET_SRC (pat));
7748             }
7749           else if (get_attr_atype (insn) == ATYPE_AGEN)
7750             return reg_used_in_mem_p (regno, PATTERN (insn));
7751         }
7752     }
7753   return false;
7754 }
7755
7756 /* Return 1, if dep_insn sets register used in insn in the agen unit.  */
7757
7758 int
7759 s390_agen_dep_p (rtx_insn *dep_insn, rtx_insn *insn)
7760 {
7761   rtx dep_rtx = PATTERN (dep_insn);
7762   int i;
7763
7764   if (GET_CODE (dep_rtx) == SET
7765       && addr_generation_dependency_p (dep_rtx, insn))
7766     return 1;
7767   else if (GET_CODE (dep_rtx) == PARALLEL)
7768     {
7769       for (i = 0; i < XVECLEN (dep_rtx, 0); i++)
7770         {
7771           if (addr_generation_dependency_p (XVECEXP (dep_rtx, 0, i), insn))
7772             return 1;
7773         }
7774     }
7775   return 0;
7776 }
7777
7778
7779 /* A C statement (sans semicolon) to update the integer scheduling priority
7780    INSN_PRIORITY (INSN).  Increase the priority to execute the INSN earlier,
7781    reduce the priority to execute INSN later.  Do not define this macro if
7782    you do not need to adjust the scheduling priorities of insns.
7783
7784    A STD instruction should be scheduled earlier,
7785    in order to use the bypass.  */
7786 static int
7787 s390_adjust_priority (rtx_insn *insn, int priority)
7788 {
7789   if (! INSN_P (insn))
7790     return priority;
7791
7792   if (s390_tune <= PROCESSOR_2064_Z900)
7793     return priority;
7794
7795   switch (s390_safe_attr_type (insn))
7796     {
7797       case TYPE_FSTOREDF:
7798       case TYPE_FSTORESF:
7799         priority = priority << 3;
7800         break;
7801       case TYPE_STORE:
7802       case TYPE_STM:
7803         priority = priority << 1;
7804         break;
7805       default:
7806         break;
7807     }
7808   return priority;
7809 }
7810
7811
7812 /* The number of instructions that can be issued per cycle.  */
7813
7814 static int
7815 s390_issue_rate (void)
7816 {
7817   switch (s390_tune)
7818     {
7819     case PROCESSOR_2084_Z990:
7820     case PROCESSOR_2094_Z9_109:
7821     case PROCESSOR_2094_Z9_EC:
7822     case PROCESSOR_2817_Z196:
7823       return 3;
7824     case PROCESSOR_2097_Z10:
7825       return 2;
7826     case PROCESSOR_9672_G5:
7827     case PROCESSOR_9672_G6:
7828     case PROCESSOR_2064_Z900:
7829       /* Starting with EC12 we use the sched_reorder hook to take care
7830          of instruction dispatch constraints.  The algorithm only
7831          picks the best instruction and assumes only a single
7832          instruction gets issued per cycle.  */
7833     case PROCESSOR_2827_ZEC12:
7834     case PROCESSOR_2964_Z13:
7835     case PROCESSOR_ARCH12:
7836     default:
7837       return 1;
7838     }
7839 }
7840
7841 static int
7842 s390_first_cycle_multipass_dfa_lookahead (void)
7843 {
7844   return 4;
7845 }
7846
7847 /* Annotate every literal pool reference in X by an UNSPEC_LTREF expression.
7848    Fix up MEMs as required.  */
7849
7850 static void
7851 annotate_constant_pool_refs (rtx *x)
7852 {
7853   int i, j;
7854   const char *fmt;
7855
7856   gcc_assert (GET_CODE (*x) != SYMBOL_REF
7857               || !CONSTANT_POOL_ADDRESS_P (*x));
7858
7859   /* Literal pool references can only occur inside a MEM ...  */
7860   if (GET_CODE (*x) == MEM)
7861     {
7862       rtx memref = XEXP (*x, 0);
7863
7864       if (GET_CODE (memref) == SYMBOL_REF
7865           && CONSTANT_POOL_ADDRESS_P (memref))
7866         {
7867           rtx base = cfun->machine->base_reg;
7868           rtx addr = gen_rtx_UNSPEC (Pmode, gen_rtvec (2, memref, base),
7869                                      UNSPEC_LTREF);
7870
7871           *x = replace_equiv_address (*x, addr);
7872           return;
7873         }
7874
7875       if (GET_CODE (memref) == CONST
7876           && GET_CODE (XEXP (memref, 0)) == PLUS
7877           && GET_CODE (XEXP (XEXP (memref, 0), 1)) == CONST_INT
7878           && GET_CODE (XEXP (XEXP (memref, 0), 0)) == SYMBOL_REF
7879           && CONSTANT_POOL_ADDRESS_P (XEXP (XEXP (memref, 0), 0)))
7880         {
7881           HOST_WIDE_INT off = INTVAL (XEXP (XEXP (memref, 0), 1));
7882           rtx sym = XEXP (XEXP (memref, 0), 0);
7883           rtx base = cfun->machine->base_reg;
7884           rtx addr = gen_rtx_UNSPEC (Pmode, gen_rtvec (2, sym, base),
7885                                      UNSPEC_LTREF);
7886
7887           *x = replace_equiv_address (*x, plus_constant (Pmode, addr, off));
7888           return;
7889         }
7890     }
7891
7892   /* ... or a load-address type pattern.  */
7893   if (GET_CODE (*x) == SET)
7894     {
7895       rtx addrref = SET_SRC (*x);
7896
7897       if (GET_CODE (addrref) == SYMBOL_REF
7898           && CONSTANT_POOL_ADDRESS_P (addrref))
7899         {
7900           rtx base = cfun->machine->base_reg;
7901           rtx addr = gen_rtx_UNSPEC (Pmode, gen_rtvec (2, addrref, base),
7902                                      UNSPEC_LTREF);
7903
7904           SET_SRC (*x) = addr;
7905           return;
7906         }
7907
7908       if (GET_CODE (addrref) == CONST
7909           && GET_CODE (XEXP (addrref, 0)) == PLUS
7910           && GET_CODE (XEXP (XEXP (addrref, 0), 1)) == CONST_INT
7911           && GET_CODE (XEXP (XEXP (addrref, 0), 0)) == SYMBOL_REF
7912           && CONSTANT_POOL_ADDRESS_P (XEXP (XEXP (addrref, 0), 0)))
7913         {
7914           HOST_WIDE_INT off = INTVAL (XEXP (XEXP (addrref, 0), 1));
7915           rtx sym = XEXP (XEXP (addrref, 0), 0);
7916           rtx base = cfun->machine->base_reg;
7917           rtx addr = gen_rtx_UNSPEC (Pmode, gen_rtvec (2, sym, base),
7918                                      UNSPEC_LTREF);
7919
7920           SET_SRC (*x) = plus_constant (Pmode, addr, off);
7921           return;
7922         }
7923     }
7924
7925   /* Annotate LTREL_BASE as well.  */
7926   if (GET_CODE (*x) == UNSPEC
7927       && XINT (*x, 1) == UNSPEC_LTREL_BASE)
7928     {
7929       rtx base = cfun->machine->base_reg;
7930       *x = gen_rtx_UNSPEC (Pmode, gen_rtvec (2, XVECEXP (*x, 0, 0), base),
7931                                   UNSPEC_LTREL_BASE);
7932       return;
7933     }
7934
7935   fmt = GET_RTX_FORMAT (GET_CODE (*x));
7936   for (i = GET_RTX_LENGTH (GET_CODE (*x)) - 1; i >= 0; i--)
7937     {
7938       if (fmt[i] == 'e')
7939         {
7940           annotate_constant_pool_refs (&XEXP (*x, i));
7941         }
7942       else if (fmt[i] == 'E')
7943         {
7944           for (j = 0; j < XVECLEN (*x, i); j++)
7945             annotate_constant_pool_refs (&XVECEXP (*x, i, j));
7946         }
7947     }
7948 }
7949
7950 /* Split all branches that exceed the maximum distance.
7951    Returns true if this created a new literal pool entry.  */
7952
7953 static int
7954 s390_split_branches (void)
7955 {
7956   rtx temp_reg = gen_rtx_REG (Pmode, RETURN_REGNUM);
7957   int new_literal = 0, ret;
7958   rtx_insn *insn;
7959   rtx pat, target;
7960   rtx *label;
7961
7962   /* We need correct insn addresses.  */
7963
7964   shorten_branches (get_insns ());
7965
7966   /* Find all branches that exceed 64KB, and split them.  */
7967
7968   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
7969     {
7970       if (! JUMP_P (insn) || tablejump_p (insn, NULL, NULL))
7971         continue;
7972
7973       pat = PATTERN (insn);
7974       if (GET_CODE (pat) == PARALLEL)
7975         pat = XVECEXP (pat, 0, 0);
7976       if (GET_CODE (pat) != SET || SET_DEST (pat) != pc_rtx)
7977         continue;
7978
7979       if (GET_CODE (SET_SRC (pat)) == LABEL_REF)
7980         {
7981           label = &SET_SRC (pat);
7982         }
7983       else if (GET_CODE (SET_SRC (pat)) == IF_THEN_ELSE)
7984         {
7985           if (GET_CODE (XEXP (SET_SRC (pat), 1)) == LABEL_REF)
7986             label = &XEXP (SET_SRC (pat), 1);
7987           else if (GET_CODE (XEXP (SET_SRC (pat), 2)) == LABEL_REF)
7988             label = &XEXP (SET_SRC (pat), 2);
7989           else
7990             continue;
7991         }
7992       else
7993         continue;
7994
7995       if (get_attr_length (insn) <= 4)
7996         continue;
7997
7998       /* We are going to use the return register as scratch register,
7999          make sure it will be saved/restored by the prologue/epilogue.  */
8000       cfun_frame_layout.save_return_addr_p = 1;
8001
8002       if (!flag_pic)
8003         {
8004           new_literal = 1;
8005           rtx mem = force_const_mem (Pmode, *label);
8006           rtx_insn *set_insn = emit_insn_before (gen_rtx_SET (temp_reg, mem),
8007                                                  insn);
8008           INSN_ADDRESSES_NEW (set_insn, -1);
8009           annotate_constant_pool_refs (&PATTERN (set_insn));
8010
8011           target = temp_reg;
8012         }
8013       else
8014         {
8015           new_literal = 1;
8016           target = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, *label),
8017                                    UNSPEC_LTREL_OFFSET);
8018           target = gen_rtx_CONST (Pmode, target);
8019           target = force_const_mem (Pmode, target);
8020           rtx_insn *set_insn = emit_insn_before (gen_rtx_SET (temp_reg, target),
8021                                                  insn);
8022           INSN_ADDRESSES_NEW (set_insn, -1);
8023           annotate_constant_pool_refs (&PATTERN (set_insn));
8024
8025           target = gen_rtx_UNSPEC (Pmode, gen_rtvec (2, XEXP (target, 0),
8026                                                         cfun->machine->base_reg),
8027                                    UNSPEC_LTREL_BASE);
8028           target = gen_rtx_PLUS (Pmode, temp_reg, target);
8029         }
8030
8031       ret = validate_change (insn, label, target, 0);
8032       gcc_assert (ret);
8033     }
8034
8035   return new_literal;
8036 }
8037
8038
8039 /* Find an annotated literal pool symbol referenced in RTX X,
8040    and store it at REF.  Will abort if X contains references to
8041    more than one such pool symbol; multiple references to the same
8042    symbol are allowed, however.
8043
8044    The rtx pointed to by REF must be initialized to NULL_RTX
8045    by the caller before calling this routine.  */
8046
8047 static void
8048 find_constant_pool_ref (rtx x, rtx *ref)
8049 {
8050   int i, j;
8051   const char *fmt;
8052
8053   /* Ignore LTREL_BASE references.  */
8054   if (GET_CODE (x) == UNSPEC
8055       && XINT (x, 1) == UNSPEC_LTREL_BASE)
8056     return;
8057   /* Likewise POOL_ENTRY insns.  */
8058   if (GET_CODE (x) == UNSPEC_VOLATILE
8059       && XINT (x, 1) == UNSPECV_POOL_ENTRY)
8060     return;
8061
8062   gcc_assert (GET_CODE (x) != SYMBOL_REF
8063               || !CONSTANT_POOL_ADDRESS_P (x));
8064
8065   if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_LTREF)
8066     {
8067       rtx sym = XVECEXP (x, 0, 0);
8068       gcc_assert (GET_CODE (sym) == SYMBOL_REF
8069                   && CONSTANT_POOL_ADDRESS_P (sym));
8070
8071       if (*ref == NULL_RTX)
8072         *ref = sym;
8073       else
8074         gcc_assert (*ref == sym);
8075
8076       return;
8077     }
8078
8079   fmt = GET_RTX_FORMAT (GET_CODE (x));
8080   for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
8081     {
8082       if (fmt[i] == 'e')
8083         {
8084           find_constant_pool_ref (XEXP (x, i), ref);
8085         }
8086       else if (fmt[i] == 'E')
8087         {
8088           for (j = 0; j < XVECLEN (x, i); j++)
8089             find_constant_pool_ref (XVECEXP (x, i, j), ref);
8090         }
8091     }
8092 }
8093
8094 /* Replace every reference to the annotated literal pool
8095    symbol REF in X by its base plus OFFSET.  */
8096
8097 static void
8098 replace_constant_pool_ref (rtx *x, rtx ref, rtx offset)
8099 {
8100   int i, j;
8101   const char *fmt;
8102
8103   gcc_assert (*x != ref);
8104
8105   if (GET_CODE (*x) == UNSPEC
8106       && XINT (*x, 1) == UNSPEC_LTREF
8107       && XVECEXP (*x, 0, 0) == ref)
8108     {
8109       *x = gen_rtx_PLUS (Pmode, XVECEXP (*x, 0, 1), offset);
8110       return;
8111     }
8112
8113   if (GET_CODE (*x) == PLUS
8114       && GET_CODE (XEXP (*x, 1)) == CONST_INT
8115       && GET_CODE (XEXP (*x, 0)) == UNSPEC
8116       && XINT (XEXP (*x, 0), 1) == UNSPEC_LTREF
8117       && XVECEXP (XEXP (*x, 0), 0, 0) == ref)
8118     {
8119       rtx addr = gen_rtx_PLUS (Pmode, XVECEXP (XEXP (*x, 0), 0, 1), offset);
8120       *x = plus_constant (Pmode, addr, INTVAL (XEXP (*x, 1)));
8121       return;
8122     }
8123
8124   fmt = GET_RTX_FORMAT (GET_CODE (*x));
8125   for (i = GET_RTX_LENGTH (GET_CODE (*x)) - 1; i >= 0; i--)
8126     {
8127       if (fmt[i] == 'e')
8128         {
8129           replace_constant_pool_ref (&XEXP (*x, i), ref, offset);
8130         }
8131       else if (fmt[i] == 'E')
8132         {
8133           for (j = 0; j < XVECLEN (*x, i); j++)
8134             replace_constant_pool_ref (&XVECEXP (*x, i, j), ref, offset);
8135         }
8136     }
8137 }
8138
8139 /* Check whether X contains an UNSPEC_LTREL_BASE.
8140    Return its constant pool symbol if found, NULL_RTX otherwise.  */
8141
8142 static rtx
8143 find_ltrel_base (rtx x)
8144 {
8145   int i, j;
8146   const char *fmt;
8147
8148   if (GET_CODE (x) == UNSPEC
8149       && XINT (x, 1) == UNSPEC_LTREL_BASE)
8150     return XVECEXP (x, 0, 0);
8151
8152   fmt = GET_RTX_FORMAT (GET_CODE (x));
8153   for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
8154     {
8155       if (fmt[i] == 'e')
8156         {
8157           rtx fnd = find_ltrel_base (XEXP (x, i));
8158           if (fnd)
8159             return fnd;
8160         }
8161       else if (fmt[i] == 'E')
8162         {
8163           for (j = 0; j < XVECLEN (x, i); j++)
8164             {
8165               rtx fnd = find_ltrel_base (XVECEXP (x, i, j));
8166               if (fnd)
8167                 return fnd;
8168             }
8169         }
8170     }
8171
8172   return NULL_RTX;
8173 }
8174
8175 /* Replace any occurrence of UNSPEC_LTREL_BASE in X with its base.  */
8176
8177 static void
8178 replace_ltrel_base (rtx *x)
8179 {
8180   int i, j;
8181   const char *fmt;
8182
8183   if (GET_CODE (*x) == UNSPEC
8184       && XINT (*x, 1) == UNSPEC_LTREL_BASE)
8185     {
8186       *x = XVECEXP (*x, 0, 1);
8187       return;
8188     }
8189
8190   fmt = GET_RTX_FORMAT (GET_CODE (*x));
8191   for (i = GET_RTX_LENGTH (GET_CODE (*x)) - 1; i >= 0; i--)
8192     {
8193       if (fmt[i] == 'e')
8194         {
8195           replace_ltrel_base (&XEXP (*x, i));
8196         }
8197       else if (fmt[i] == 'E')
8198         {
8199           for (j = 0; j < XVECLEN (*x, i); j++)
8200             replace_ltrel_base (&XVECEXP (*x, i, j));
8201         }
8202     }
8203 }
8204
8205
8206 /* We keep a list of constants which we have to add to internal
8207    constant tables in the middle of large functions.  */
8208
8209 #define NR_C_MODES 32
8210 machine_mode constant_modes[NR_C_MODES] =
8211 {
8212   TFmode, TImode, TDmode,
8213   V16QImode, V8HImode, V4SImode, V2DImode, V1TImode,
8214   V4SFmode, V2DFmode, V1TFmode,
8215   DFmode, DImode, DDmode,
8216   V8QImode, V4HImode, V2SImode, V1DImode, V2SFmode, V1DFmode,
8217   SFmode, SImode, SDmode,
8218   V4QImode, V2HImode, V1SImode,  V1SFmode,
8219   HImode,
8220   V2QImode, V1HImode,
8221   QImode,
8222   V1QImode
8223 };
8224
8225 struct constant
8226 {
8227   struct constant *next;
8228   rtx value;
8229   rtx_code_label *label;
8230 };
8231
8232 struct constant_pool
8233 {
8234   struct constant_pool *next;
8235   rtx_insn *first_insn;
8236   rtx_insn *pool_insn;
8237   bitmap insns;
8238   rtx_insn *emit_pool_after;
8239
8240   struct constant *constants[NR_C_MODES];
8241   struct constant *execute;
8242   rtx_code_label *label;
8243   int size;
8244 };
8245
8246 /* Allocate new constant_pool structure.  */
8247
8248 static struct constant_pool *
8249 s390_alloc_pool (void)
8250 {
8251   struct constant_pool *pool;
8252   int i;
8253
8254   pool = (struct constant_pool *) xmalloc (sizeof *pool);
8255   pool->next = NULL;
8256   for (i = 0; i < NR_C_MODES; i++)
8257     pool->constants[i] = NULL;
8258
8259   pool->execute = NULL;
8260   pool->label = gen_label_rtx ();
8261   pool->first_insn = NULL;
8262   pool->pool_insn = NULL;
8263   pool->insns = BITMAP_ALLOC (NULL);
8264   pool->size = 0;
8265   pool->emit_pool_after = NULL;
8266
8267   return pool;
8268 }
8269
8270 /* Create new constant pool covering instructions starting at INSN
8271    and chain it to the end of POOL_LIST.  */
8272
8273 static struct constant_pool *
8274 s390_start_pool (struct constant_pool **pool_list, rtx_insn *insn)
8275 {
8276   struct constant_pool *pool, **prev;
8277
8278   pool = s390_alloc_pool ();
8279   pool->first_insn = insn;
8280
8281   for (prev = pool_list; *prev; prev = &(*prev)->next)
8282     ;
8283   *prev = pool;
8284
8285   return pool;
8286 }
8287
8288 /* End range of instructions covered by POOL at INSN and emit
8289    placeholder insn representing the pool.  */
8290
8291 static void
8292 s390_end_pool (struct constant_pool *pool, rtx_insn *insn)
8293 {
8294   rtx pool_size = GEN_INT (pool->size + 8 /* alignment slop */);
8295
8296   if (!insn)
8297     insn = get_last_insn ();
8298
8299   pool->pool_insn = emit_insn_after (gen_pool (pool_size), insn);
8300   INSN_ADDRESSES_NEW (pool->pool_insn, -1);
8301 }
8302
8303 /* Add INSN to the list of insns covered by POOL.  */
8304
8305 static void
8306 s390_add_pool_insn (struct constant_pool *pool, rtx insn)
8307 {
8308   bitmap_set_bit (pool->insns, INSN_UID (insn));
8309 }
8310
8311 /* Return pool out of POOL_LIST that covers INSN.  */
8312
8313 static struct constant_pool *
8314 s390_find_pool (struct constant_pool *pool_list, rtx insn)
8315 {
8316   struct constant_pool *pool;
8317
8318   for (pool = pool_list; pool; pool = pool->next)
8319     if (bitmap_bit_p (pool->insns, INSN_UID (insn)))
8320       break;
8321
8322   return pool;
8323 }
8324
8325 /* Add constant VAL of mode MODE to the constant pool POOL.  */
8326
8327 static void
8328 s390_add_constant (struct constant_pool *pool, rtx val, machine_mode mode)
8329 {
8330   struct constant *c;
8331   int i;
8332
8333   for (i = 0; i < NR_C_MODES; i++)
8334     if (constant_modes[i] == mode)
8335       break;
8336   gcc_assert (i != NR_C_MODES);
8337
8338   for (c = pool->constants[i]; c != NULL; c = c->next)
8339     if (rtx_equal_p (val, c->value))
8340       break;
8341
8342   if (c == NULL)
8343     {
8344       c = (struct constant *) xmalloc (sizeof *c);
8345       c->value = val;
8346       c->label = gen_label_rtx ();
8347       c->next = pool->constants[i];
8348       pool->constants[i] = c;
8349       pool->size += GET_MODE_SIZE (mode);
8350     }
8351 }
8352
8353 /* Return an rtx that represents the offset of X from the start of
8354    pool POOL.  */
8355
8356 static rtx
8357 s390_pool_offset (struct constant_pool *pool, rtx x)
8358 {
8359   rtx label;
8360
8361   label = gen_rtx_LABEL_REF (GET_MODE (x), pool->label);
8362   x = gen_rtx_UNSPEC (GET_MODE (x), gen_rtvec (2, x, label),
8363                       UNSPEC_POOL_OFFSET);
8364   return gen_rtx_CONST (GET_MODE (x), x);
8365 }
8366
8367 /* Find constant VAL of mode MODE in the constant pool POOL.
8368    Return an RTX describing the distance from the start of
8369    the pool to the location of the new constant.  */
8370
8371 static rtx
8372 s390_find_constant (struct constant_pool *pool, rtx val,
8373                     machine_mode mode)
8374 {
8375   struct constant *c;
8376   int i;
8377
8378   for (i = 0; i < NR_C_MODES; i++)
8379     if (constant_modes[i] == mode)
8380       break;
8381   gcc_assert (i != NR_C_MODES);
8382
8383   for (c = pool->constants[i]; c != NULL; c = c->next)
8384     if (rtx_equal_p (val, c->value))
8385       break;
8386
8387   gcc_assert (c);
8388
8389   return s390_pool_offset (pool, gen_rtx_LABEL_REF (Pmode, c->label));
8390 }
8391
8392 /* Check whether INSN is an execute.  Return the label_ref to its
8393    execute target template if so, NULL_RTX otherwise.  */
8394
8395 static rtx
8396 s390_execute_label (rtx insn)
8397 {
8398   if (NONJUMP_INSN_P (insn)
8399       && GET_CODE (PATTERN (insn)) == PARALLEL
8400       && GET_CODE (XVECEXP (PATTERN (insn), 0, 0)) == UNSPEC
8401       && XINT (XVECEXP (PATTERN (insn), 0, 0), 1) == UNSPEC_EXECUTE)
8402     return XVECEXP (XVECEXP (PATTERN (insn), 0, 0), 0, 2);
8403
8404   return NULL_RTX;
8405 }
8406
8407 /* Add execute target for INSN to the constant pool POOL.  */
8408
8409 static void
8410 s390_add_execute (struct constant_pool *pool, rtx insn)
8411 {
8412   struct constant *c;
8413
8414   for (c = pool->execute; c != NULL; c = c->next)
8415     if (INSN_UID (insn) == INSN_UID (c->value))
8416       break;
8417
8418   if (c == NULL)
8419     {
8420       c = (struct constant *) xmalloc (sizeof *c);
8421       c->value = insn;
8422       c->label = gen_label_rtx ();
8423       c->next = pool->execute;
8424       pool->execute = c;
8425       pool->size += 6;
8426     }
8427 }
8428
8429 /* Find execute target for INSN in the constant pool POOL.
8430    Return an RTX describing the distance from the start of
8431    the pool to the location of the execute target.  */
8432
8433 static rtx
8434 s390_find_execute (struct constant_pool *pool, rtx insn)
8435 {
8436   struct constant *c;
8437
8438   for (c = pool->execute; c != NULL; c = c->next)
8439     if (INSN_UID (insn) == INSN_UID (c->value))
8440       break;
8441
8442   gcc_assert (c);
8443
8444   return s390_pool_offset (pool, gen_rtx_LABEL_REF (Pmode, c->label));
8445 }
8446
8447 /* For an execute INSN, extract the execute target template.  */
8448
8449 static rtx
8450 s390_execute_target (rtx insn)
8451 {
8452   rtx pattern = PATTERN (insn);
8453   gcc_assert (s390_execute_label (insn));
8454
8455   if (XVECLEN (pattern, 0) == 2)
8456     {
8457       pattern = copy_rtx (XVECEXP (pattern, 0, 1));
8458     }
8459   else
8460     {
8461       rtvec vec = rtvec_alloc (XVECLEN (pattern, 0) - 1);
8462       int i;
8463
8464       for (i = 0; i < XVECLEN (pattern, 0) - 1; i++)
8465         RTVEC_ELT (vec, i) = copy_rtx (XVECEXP (pattern, 0, i + 1));
8466
8467       pattern = gen_rtx_PARALLEL (VOIDmode, vec);
8468     }
8469
8470   return pattern;
8471 }
8472
8473 /* Indicate that INSN cannot be duplicated.  This is the case for
8474    execute insns that carry a unique label.  */
8475
8476 static bool
8477 s390_cannot_copy_insn_p (rtx_insn *insn)
8478 {
8479   rtx label = s390_execute_label (insn);
8480   return label && label != const0_rtx;
8481 }
8482
8483 /* Dump out the constants in POOL.  If REMOTE_LABEL is true,
8484    do not emit the pool base label.  */
8485
8486 static void
8487 s390_dump_pool (struct constant_pool *pool, bool remote_label)
8488 {
8489   struct constant *c;
8490   rtx_insn *insn = pool->pool_insn;
8491   int i;
8492
8493   /* Switch to rodata section.  */
8494   if (TARGET_CPU_ZARCH)
8495     {
8496       insn = emit_insn_after (gen_pool_section_start (), insn);
8497       INSN_ADDRESSES_NEW (insn, -1);
8498     }
8499
8500   /* Ensure minimum pool alignment.  */
8501   if (TARGET_CPU_ZARCH)
8502     insn = emit_insn_after (gen_pool_align (GEN_INT (8)), insn);
8503   else
8504     insn = emit_insn_after (gen_pool_align (GEN_INT (4)), insn);
8505   INSN_ADDRESSES_NEW (insn, -1);
8506
8507   /* Emit pool base label.  */
8508   if (!remote_label)
8509     {
8510       insn = emit_label_after (pool->label, insn);
8511       INSN_ADDRESSES_NEW (insn, -1);
8512     }
8513
8514   /* Dump constants in descending alignment requirement order,
8515      ensuring proper alignment for every constant.  */
8516   for (i = 0; i < NR_C_MODES; i++)
8517     for (c = pool->constants[i]; c; c = c->next)
8518       {
8519         /* Convert UNSPEC_LTREL_OFFSET unspecs to pool-relative references.  */
8520         rtx value = copy_rtx (c->value);
8521         if (GET_CODE (value) == CONST
8522             && GET_CODE (XEXP (value, 0)) == UNSPEC
8523             && XINT (XEXP (value, 0), 1) == UNSPEC_LTREL_OFFSET
8524             && XVECLEN (XEXP (value, 0), 0) == 1)
8525           value = s390_pool_offset (pool, XVECEXP (XEXP (value, 0), 0, 0));
8526
8527         insn = emit_label_after (c->label, insn);
8528         INSN_ADDRESSES_NEW (insn, -1);
8529
8530         value = gen_rtx_UNSPEC_VOLATILE (constant_modes[i],
8531                                          gen_rtvec (1, value),
8532                                          UNSPECV_POOL_ENTRY);
8533         insn = emit_insn_after (value, insn);
8534         INSN_ADDRESSES_NEW (insn, -1);
8535       }
8536
8537   /* Ensure minimum alignment for instructions.  */
8538   insn = emit_insn_after (gen_pool_align (GEN_INT (2)), insn);
8539   INSN_ADDRESSES_NEW (insn, -1);
8540
8541   /* Output in-pool execute template insns.  */
8542   for (c = pool->execute; c; c = c->next)
8543     {
8544       insn = emit_label_after (c->label, insn);
8545       INSN_ADDRESSES_NEW (insn, -1);
8546
8547       insn = emit_insn_after (s390_execute_target (c->value), insn);
8548       INSN_ADDRESSES_NEW (insn, -1);
8549     }
8550
8551   /* Switch back to previous section.  */
8552   if (TARGET_CPU_ZARCH)
8553     {
8554       insn = emit_insn_after (gen_pool_section_end (), insn);
8555       INSN_ADDRESSES_NEW (insn, -1);
8556     }
8557
8558   insn = emit_barrier_after (insn);
8559   INSN_ADDRESSES_NEW (insn, -1);
8560
8561   /* Remove placeholder insn.  */
8562   remove_insn (pool->pool_insn);
8563 }
8564
8565 /* Free all memory used by POOL.  */
8566
8567 static void
8568 s390_free_pool (struct constant_pool *pool)
8569 {
8570   struct constant *c, *next;
8571   int i;
8572
8573   for (i = 0; i < NR_C_MODES; i++)
8574     for (c = pool->constants[i]; c; c = next)
8575       {
8576         next = c->next;
8577         free (c);
8578       }
8579
8580   for (c = pool->execute; c; c = next)
8581     {
8582       next = c->next;
8583       free (c);
8584     }
8585
8586   BITMAP_FREE (pool->insns);
8587   free (pool);
8588 }
8589
8590
8591 /* Collect main literal pool.  Return NULL on overflow.  */
8592
8593 static struct constant_pool *
8594 s390_mainpool_start (void)
8595 {
8596   struct constant_pool *pool;
8597   rtx_insn *insn;
8598
8599   pool = s390_alloc_pool ();
8600
8601   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
8602     {
8603       if (NONJUMP_INSN_P (insn)
8604           && GET_CODE (PATTERN (insn)) == SET
8605           && GET_CODE (SET_SRC (PATTERN (insn))) == UNSPEC_VOLATILE
8606           && XINT (SET_SRC (PATTERN (insn)), 1) == UNSPECV_MAIN_POOL)
8607         {
8608           /* There might be two main_pool instructions if base_reg
8609              is call-clobbered; one for shrink-wrapped code and one
8610              for the rest.  We want to keep the first.  */
8611           if (pool->pool_insn)
8612             {
8613               insn = PREV_INSN (insn);
8614               delete_insn (NEXT_INSN (insn));
8615               continue;
8616             }
8617           pool->pool_insn = insn;
8618         }
8619
8620       if (!TARGET_CPU_ZARCH && s390_execute_label (insn))
8621         {
8622           s390_add_execute (pool, insn);
8623         }
8624       else if (NONJUMP_INSN_P (insn) || CALL_P (insn))
8625         {
8626           rtx pool_ref = NULL_RTX;
8627           find_constant_pool_ref (PATTERN (insn), &pool_ref);
8628           if (pool_ref)
8629             {
8630               rtx constant = get_pool_constant (pool_ref);
8631               machine_mode mode = get_pool_mode (pool_ref);
8632               s390_add_constant (pool, constant, mode);
8633             }
8634         }
8635
8636       /* If hot/cold partitioning is enabled we have to make sure that
8637          the literal pool is emitted in the same section where the
8638          initialization of the literal pool base pointer takes place.
8639          emit_pool_after is only used in the non-overflow case on non
8640          Z cpus where we can emit the literal pool at the end of the
8641          function body within the text section.  */
8642       if (NOTE_P (insn)
8643           && NOTE_KIND (insn) == NOTE_INSN_SWITCH_TEXT_SECTIONS
8644           && !pool->emit_pool_after)
8645         pool->emit_pool_after = PREV_INSN (insn);
8646     }
8647
8648   gcc_assert (pool->pool_insn || pool->size == 0);
8649
8650   if (pool->size >= 4096)
8651     {
8652       /* We're going to chunkify the pool, so remove the main
8653          pool placeholder insn.  */
8654       remove_insn (pool->pool_insn);
8655
8656       s390_free_pool (pool);
8657       pool = NULL;
8658     }
8659
8660   /* If the functions ends with the section where the literal pool
8661      should be emitted set the marker to its end.  */
8662   if (pool && !pool->emit_pool_after)
8663     pool->emit_pool_after = get_last_insn ();
8664
8665   return pool;
8666 }
8667
8668 /* POOL holds the main literal pool as collected by s390_mainpool_start.
8669    Modify the current function to output the pool constants as well as
8670    the pool register setup instruction.  */
8671
8672 static void
8673 s390_mainpool_finish (struct constant_pool *pool)
8674 {
8675   rtx base_reg = cfun->machine->base_reg;
8676
8677   /* If the pool is empty, we're done.  */
8678   if (pool->size == 0)
8679     {
8680       /* We don't actually need a base register after all.  */
8681       cfun->machine->base_reg = NULL_RTX;
8682
8683       if (pool->pool_insn)
8684         remove_insn (pool->pool_insn);
8685       s390_free_pool (pool);
8686       return;
8687     }
8688
8689   /* We need correct insn addresses.  */
8690   shorten_branches (get_insns ());
8691
8692   /* On zSeries, we use a LARL to load the pool register.  The pool is
8693      located in the .rodata section, so we emit it after the function.  */
8694   if (TARGET_CPU_ZARCH)
8695     {
8696       rtx set = gen_main_base_64 (base_reg, pool->label);
8697       rtx_insn *insn = emit_insn_after (set, pool->pool_insn);
8698       INSN_ADDRESSES_NEW (insn, -1);
8699       remove_insn (pool->pool_insn);
8700
8701       insn = get_last_insn ();
8702       pool->pool_insn = emit_insn_after (gen_pool (const0_rtx), insn);
8703       INSN_ADDRESSES_NEW (pool->pool_insn, -1);
8704
8705       s390_dump_pool (pool, 0);
8706     }
8707
8708   /* On S/390, if the total size of the function's code plus literal pool
8709      does not exceed 4096 bytes, we use BASR to set up a function base
8710      pointer, and emit the literal pool at the end of the function.  */
8711   else if (INSN_ADDRESSES (INSN_UID (pool->emit_pool_after))
8712            + pool->size + 8 /* alignment slop */ < 4096)
8713     {
8714       rtx set = gen_main_base_31_small (base_reg, pool->label);
8715       rtx_insn *insn = emit_insn_after (set, pool->pool_insn);
8716       INSN_ADDRESSES_NEW (insn, -1);
8717       remove_insn (pool->pool_insn);
8718
8719       insn = emit_label_after (pool->label, insn);
8720       INSN_ADDRESSES_NEW (insn, -1);
8721
8722       /* emit_pool_after will be set by s390_mainpool_start to the
8723          last insn of the section where the literal pool should be
8724          emitted.  */
8725       insn = pool->emit_pool_after;
8726
8727       pool->pool_insn = emit_insn_after (gen_pool (const0_rtx), insn);
8728       INSN_ADDRESSES_NEW (pool->pool_insn, -1);
8729
8730       s390_dump_pool (pool, 1);
8731     }
8732
8733   /* Otherwise, we emit an inline literal pool and use BASR to branch
8734      over it, setting up the pool register at the same time.  */
8735   else
8736     {
8737       rtx_code_label *pool_end = gen_label_rtx ();
8738
8739       rtx pat = gen_main_base_31_large (base_reg, pool->label, pool_end);
8740       rtx_insn *insn = emit_jump_insn_after (pat, pool->pool_insn);
8741       JUMP_LABEL (insn) = pool_end;
8742       INSN_ADDRESSES_NEW (insn, -1);
8743       remove_insn (pool->pool_insn);
8744
8745       insn = emit_label_after (pool->label, insn);
8746       INSN_ADDRESSES_NEW (insn, -1);
8747
8748       pool->pool_insn = emit_insn_after (gen_pool (const0_rtx), insn);
8749       INSN_ADDRESSES_NEW (pool->pool_insn, -1);
8750
8751       insn = emit_label_after (pool_end, pool->pool_insn);
8752       INSN_ADDRESSES_NEW (insn, -1);
8753
8754       s390_dump_pool (pool, 1);
8755     }
8756
8757
8758   /* Replace all literal pool references.  */
8759
8760   for (rtx_insn *insn = get_insns (); insn; insn = NEXT_INSN (insn))
8761     {
8762       if (INSN_P (insn))
8763         replace_ltrel_base (&PATTERN (insn));
8764
8765       if (NONJUMP_INSN_P (insn) || CALL_P (insn))
8766         {
8767           rtx addr, pool_ref = NULL_RTX;
8768           find_constant_pool_ref (PATTERN (insn), &pool_ref);
8769           if (pool_ref)
8770             {
8771               if (s390_execute_label (insn))
8772                 addr = s390_find_execute (pool, insn);
8773               else
8774                 addr = s390_find_constant (pool, get_pool_constant (pool_ref),
8775                                                  get_pool_mode (pool_ref));
8776
8777               replace_constant_pool_ref (&PATTERN (insn), pool_ref, addr);
8778               INSN_CODE (insn) = -1;
8779             }
8780         }
8781     }
8782
8783
8784   /* Free the pool.  */
8785   s390_free_pool (pool);
8786 }
8787
8788 /* POOL holds the main literal pool as collected by s390_mainpool_start.
8789    We have decided we cannot use this pool, so revert all changes
8790    to the current function that were done by s390_mainpool_start.  */
8791 static void
8792 s390_mainpool_cancel (struct constant_pool *pool)
8793 {
8794   /* We didn't actually change the instruction stream, so simply
8795      free the pool memory.  */
8796   s390_free_pool (pool);
8797 }
8798
8799
8800 /* Chunkify the literal pool.  */
8801
8802 #define S390_POOL_CHUNK_MIN     0xc00
8803 #define S390_POOL_CHUNK_MAX     0xe00
8804
8805 static struct constant_pool *
8806 s390_chunkify_start (void)
8807 {
8808   struct constant_pool *curr_pool = NULL, *pool_list = NULL;
8809   int extra_size = 0;
8810   bitmap far_labels;
8811   rtx pending_ltrel = NULL_RTX;
8812   rtx_insn *insn;
8813
8814   rtx (*gen_reload_base) (rtx, rtx) =
8815     TARGET_CPU_ZARCH? gen_reload_base_64 : gen_reload_base_31;
8816
8817
8818   /* We need correct insn addresses.  */
8819
8820   shorten_branches (get_insns ());
8821
8822   /* Scan all insns and move literals to pool chunks.  */
8823
8824   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
8825     {
8826       bool section_switch_p = false;
8827
8828       /* Check for pending LTREL_BASE.  */
8829       if (INSN_P (insn))
8830         {
8831           rtx ltrel_base = find_ltrel_base (PATTERN (insn));
8832           if (ltrel_base)
8833             {
8834               gcc_assert (ltrel_base == pending_ltrel);
8835               pending_ltrel = NULL_RTX;
8836             }
8837         }
8838
8839       if (!TARGET_CPU_ZARCH && s390_execute_label (insn))
8840         {
8841           if (!curr_pool)
8842             curr_pool = s390_start_pool (&pool_list, insn);
8843
8844           s390_add_execute (curr_pool, insn);
8845           s390_add_pool_insn (curr_pool, insn);
8846         }
8847       else if (NONJUMP_INSN_P (insn) || CALL_P (insn))
8848         {
8849           rtx pool_ref = NULL_RTX;
8850           find_constant_pool_ref (PATTERN (insn), &pool_ref);
8851           if (pool_ref)
8852             {
8853               rtx constant = get_pool_constant (pool_ref);
8854               machine_mode mode = get_pool_mode (pool_ref);
8855
8856               if (!curr_pool)
8857                 curr_pool = s390_start_pool (&pool_list, insn);
8858
8859               s390_add_constant (curr_pool, constant, mode);
8860               s390_add_pool_insn (curr_pool, insn);
8861
8862               /* Don't split the pool chunk between a LTREL_OFFSET load
8863                  and the corresponding LTREL_BASE.  */
8864               if (GET_CODE (constant) == CONST
8865                   && GET_CODE (XEXP (constant, 0)) == UNSPEC
8866                   && XINT (XEXP (constant, 0), 1) == UNSPEC_LTREL_OFFSET)
8867                 {
8868                   gcc_assert (!pending_ltrel);
8869                   pending_ltrel = pool_ref;
8870                 }
8871             }
8872         }
8873
8874       if (JUMP_P (insn) || JUMP_TABLE_DATA_P (insn) || LABEL_P (insn))
8875         {
8876           if (curr_pool)
8877             s390_add_pool_insn (curr_pool, insn);
8878           /* An LTREL_BASE must follow within the same basic block.  */
8879           gcc_assert (!pending_ltrel);
8880         }
8881
8882       if (NOTE_P (insn))
8883         switch (NOTE_KIND (insn))
8884           {
8885           case NOTE_INSN_SWITCH_TEXT_SECTIONS:
8886             section_switch_p = true;
8887             break;
8888           case NOTE_INSN_VAR_LOCATION:
8889           case NOTE_INSN_CALL_ARG_LOCATION:
8890             continue;
8891           default:
8892             break;
8893           }
8894
8895       if (!curr_pool
8896           || INSN_ADDRESSES_SIZE () <= (size_t) INSN_UID (insn)
8897           || INSN_ADDRESSES (INSN_UID (insn)) == -1)
8898         continue;
8899
8900       if (TARGET_CPU_ZARCH)
8901         {
8902           if (curr_pool->size < S390_POOL_CHUNK_MAX)
8903             continue;
8904
8905           s390_end_pool (curr_pool, NULL);
8906           curr_pool = NULL;
8907         }
8908       else
8909         {
8910           int chunk_size = INSN_ADDRESSES (INSN_UID (insn))
8911                            - INSN_ADDRESSES (INSN_UID (curr_pool->first_insn))
8912                          + extra_size;
8913
8914           /* We will later have to insert base register reload insns.
8915              Those will have an effect on code size, which we need to
8916              consider here.  This calculation makes rather pessimistic
8917              worst-case assumptions.  */
8918           if (LABEL_P (insn))
8919             extra_size += 6;
8920
8921           if (chunk_size < S390_POOL_CHUNK_MIN
8922               && curr_pool->size < S390_POOL_CHUNK_MIN
8923               && !section_switch_p)
8924             continue;
8925
8926           /* Pool chunks can only be inserted after BARRIERs ...  */
8927           if (BARRIER_P (insn))
8928             {
8929               s390_end_pool (curr_pool, insn);
8930               curr_pool = NULL;
8931               extra_size = 0;
8932             }
8933
8934           /* ... so if we don't find one in time, create one.  */
8935           else if (chunk_size > S390_POOL_CHUNK_MAX
8936                    || curr_pool->size > S390_POOL_CHUNK_MAX
8937                    || section_switch_p)
8938             {
8939               rtx_insn *label, *jump, *barrier, *next, *prev;
8940
8941               if (!section_switch_p)
8942                 {
8943                   /* We can insert the barrier only after a 'real' insn.  */
8944                   if (! NONJUMP_INSN_P (insn) && ! CALL_P (insn))
8945                     continue;
8946                   if (get_attr_length (insn) == 0)
8947                     continue;
8948                   /* Don't separate LTREL_BASE from the corresponding
8949                      LTREL_OFFSET load.  */
8950                   if (pending_ltrel)
8951                     continue;
8952                   next = insn;
8953                   do
8954                     {
8955                       insn = next;
8956                       next = NEXT_INSN (insn);
8957                     }
8958                   while (next
8959                          && NOTE_P (next)
8960                          && (NOTE_KIND (next) == NOTE_INSN_VAR_LOCATION
8961                              || NOTE_KIND (next) == NOTE_INSN_CALL_ARG_LOCATION));
8962                 }
8963               else
8964                 {
8965                   gcc_assert (!pending_ltrel);
8966
8967                   /* The old pool has to end before the section switch
8968                      note in order to make it part of the current
8969                      section.  */
8970                   insn = PREV_INSN (insn);
8971                 }
8972
8973               label = gen_label_rtx ();
8974               prev = insn;
8975               if (prev && NOTE_P (prev))
8976                 prev = prev_nonnote_insn (prev);
8977               if (prev)
8978                 jump = emit_jump_insn_after_setloc (gen_jump (label), insn,
8979                                                     INSN_LOCATION (prev));
8980               else
8981                 jump = emit_jump_insn_after_noloc (gen_jump (label), insn);
8982               barrier = emit_barrier_after (jump);
8983               insn = emit_label_after (label, barrier);
8984               JUMP_LABEL (jump) = label;
8985               LABEL_NUSES (label) = 1;
8986
8987               INSN_ADDRESSES_NEW (jump, -1);
8988               INSN_ADDRESSES_NEW (barrier, -1);
8989               INSN_ADDRESSES_NEW (insn, -1);
8990
8991               s390_end_pool (curr_pool, barrier);
8992               curr_pool = NULL;
8993               extra_size = 0;
8994             }
8995         }
8996     }
8997
8998   if (curr_pool)
8999     s390_end_pool (curr_pool, NULL);
9000   gcc_assert (!pending_ltrel);
9001
9002   /* Find all labels that are branched into
9003      from an insn belonging to a different chunk.  */
9004
9005   far_labels = BITMAP_ALLOC (NULL);
9006
9007   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
9008     {
9009       rtx_jump_table_data *table;
9010
9011       /* Labels marked with LABEL_PRESERVE_P can be target
9012          of non-local jumps, so we have to mark them.
9013          The same holds for named labels.
9014
9015          Don't do that, however, if it is the label before
9016          a jump table.  */
9017
9018       if (LABEL_P (insn)
9019           && (LABEL_PRESERVE_P (insn) || LABEL_NAME (insn)))
9020         {
9021           rtx_insn *vec_insn = NEXT_INSN (insn);
9022           if (! vec_insn || ! JUMP_TABLE_DATA_P (vec_insn))
9023             bitmap_set_bit (far_labels, CODE_LABEL_NUMBER (insn));
9024         }
9025       /* Check potential targets in a table jump (casesi_jump).  */
9026       else if (tablejump_p (insn, NULL, &table))
9027         {
9028           rtx vec_pat = PATTERN (table);
9029           int i, diff_p = GET_CODE (vec_pat) == ADDR_DIFF_VEC;
9030
9031           for (i = 0; i < XVECLEN (vec_pat, diff_p); i++)
9032             {
9033               rtx label = XEXP (XVECEXP (vec_pat, diff_p, i), 0);
9034
9035               if (s390_find_pool (pool_list, label)
9036                   != s390_find_pool (pool_list, insn))
9037                 bitmap_set_bit (far_labels, CODE_LABEL_NUMBER (label));
9038             }
9039         }
9040       /* If we have a direct jump (conditional or unconditional),
9041          check all potential targets.  */
9042       else if (JUMP_P (insn))
9043         {
9044           rtx pat = PATTERN (insn);
9045
9046           if (GET_CODE (pat) == PARALLEL)
9047             pat = XVECEXP (pat, 0, 0);
9048
9049           if (GET_CODE (pat) == SET)
9050             {
9051               rtx label = JUMP_LABEL (insn);
9052               if (label && !ANY_RETURN_P (label))
9053                 {
9054                   if (s390_find_pool (pool_list, label)
9055                       != s390_find_pool (pool_list, insn))
9056                     bitmap_set_bit (far_labels, CODE_LABEL_NUMBER (label));
9057                 }
9058             }
9059         }
9060     }
9061
9062   /* Insert base register reload insns before every pool.  */
9063
9064   for (curr_pool = pool_list; curr_pool; curr_pool = curr_pool->next)
9065     {
9066       rtx new_insn = gen_reload_base (cfun->machine->base_reg,
9067                                       curr_pool->label);
9068       rtx_insn *insn = curr_pool->first_insn;
9069       INSN_ADDRESSES_NEW (emit_insn_before (new_insn, insn), -1);
9070     }
9071
9072   /* Insert base register reload insns at every far label.  */
9073
9074   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
9075     if (LABEL_P (insn)
9076         && bitmap_bit_p (far_labels, CODE_LABEL_NUMBER (insn)))
9077       {
9078         struct constant_pool *pool = s390_find_pool (pool_list, insn);
9079         if (pool)
9080           {
9081             rtx new_insn = gen_reload_base (cfun->machine->base_reg,
9082                                             pool->label);
9083             INSN_ADDRESSES_NEW (emit_insn_after (new_insn, insn), -1);
9084           }
9085       }
9086
9087
9088   BITMAP_FREE (far_labels);
9089
9090
9091   /* Recompute insn addresses.  */
9092
9093   init_insn_lengths ();
9094   shorten_branches (get_insns ());
9095
9096   return pool_list;
9097 }
9098
9099 /* POOL_LIST is a chunk list as prepared by s390_chunkify_start.
9100    After we have decided to use this list, finish implementing
9101    all changes to the current function as required.  */
9102
9103 static void
9104 s390_chunkify_finish (struct constant_pool *pool_list)
9105 {
9106   struct constant_pool *curr_pool = NULL;
9107   rtx_insn *insn;
9108
9109
9110   /* Replace all literal pool references.  */
9111
9112   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
9113     {
9114       if (INSN_P (insn))
9115         replace_ltrel_base (&PATTERN (insn));
9116
9117       curr_pool = s390_find_pool (pool_list, insn);
9118       if (!curr_pool)
9119         continue;
9120
9121       if (NONJUMP_INSN_P (insn) || CALL_P (insn))
9122         {
9123           rtx addr, pool_ref = NULL_RTX;
9124           find_constant_pool_ref (PATTERN (insn), &pool_ref);
9125           if (pool_ref)
9126             {
9127               if (s390_execute_label (insn))
9128                 addr = s390_find_execute (curr_pool, insn);
9129               else
9130                 addr = s390_find_constant (curr_pool,
9131                                            get_pool_constant (pool_ref),
9132                                            get_pool_mode (pool_ref));
9133
9134               replace_constant_pool_ref (&PATTERN (insn), pool_ref, addr);
9135               INSN_CODE (insn) = -1;
9136             }
9137         }
9138     }
9139
9140   /* Dump out all literal pools.  */
9141
9142   for (curr_pool = pool_list; curr_pool; curr_pool = curr_pool->next)
9143     s390_dump_pool (curr_pool, 0);
9144
9145   /* Free pool list.  */
9146
9147   while (pool_list)
9148     {
9149       struct constant_pool *next = pool_list->next;
9150       s390_free_pool (pool_list);
9151       pool_list = next;
9152     }
9153 }
9154
9155 /* POOL_LIST is a chunk list as prepared by s390_chunkify_start.
9156    We have decided we cannot use this list, so revert all changes
9157    to the current function that were done by s390_chunkify_start.  */
9158
9159 static void
9160 s390_chunkify_cancel (struct constant_pool *pool_list)
9161 {
9162   struct constant_pool *curr_pool = NULL;
9163   rtx_insn *insn;
9164
9165   /* Remove all pool placeholder insns.  */
9166
9167   for (curr_pool = pool_list; curr_pool; curr_pool = curr_pool->next)
9168     {
9169       /* Did we insert an extra barrier?  Remove it.  */
9170       rtx_insn *barrier = PREV_INSN (curr_pool->pool_insn);
9171       rtx_insn *jump = barrier? PREV_INSN (barrier) : NULL;
9172       rtx_insn *label = NEXT_INSN (curr_pool->pool_insn);
9173
9174       if (jump && JUMP_P (jump)
9175           && barrier && BARRIER_P (barrier)
9176           && label && LABEL_P (label)
9177           && GET_CODE (PATTERN (jump)) == SET
9178           && SET_DEST (PATTERN (jump)) == pc_rtx
9179           && GET_CODE (SET_SRC (PATTERN (jump))) == LABEL_REF
9180           && XEXP (SET_SRC (PATTERN (jump)), 0) == label)
9181         {
9182           remove_insn (jump);
9183           remove_insn (barrier);
9184           remove_insn (label);
9185         }
9186
9187       remove_insn (curr_pool->pool_insn);
9188     }
9189
9190   /* Remove all base register reload insns.  */
9191
9192   for (insn = get_insns (); insn; )
9193     {
9194       rtx_insn *next_insn = NEXT_INSN (insn);
9195
9196       if (NONJUMP_INSN_P (insn)
9197           && GET_CODE (PATTERN (insn)) == SET
9198           && GET_CODE (SET_SRC (PATTERN (insn))) == UNSPEC
9199           && XINT (SET_SRC (PATTERN (insn)), 1) == UNSPEC_RELOAD_BASE)
9200         remove_insn (insn);
9201
9202       insn = next_insn;
9203     }
9204
9205   /* Free pool list.  */
9206
9207   while (pool_list)
9208     {
9209       struct constant_pool *next = pool_list->next;
9210       s390_free_pool (pool_list);
9211       pool_list = next;
9212     }
9213 }
9214
9215 /* Output the constant pool entry EXP in mode MODE with alignment ALIGN.  */
9216
9217 void
9218 s390_output_pool_entry (rtx exp, machine_mode mode, unsigned int align)
9219 {
9220   switch (GET_MODE_CLASS (mode))
9221     {
9222     case MODE_FLOAT:
9223     case MODE_DECIMAL_FLOAT:
9224       gcc_assert (GET_CODE (exp) == CONST_DOUBLE);
9225
9226       assemble_real (*CONST_DOUBLE_REAL_VALUE (exp), mode, align);
9227       break;
9228
9229     case MODE_INT:
9230       assemble_integer (exp, GET_MODE_SIZE (mode), align, 1);
9231       mark_symbol_refs_as_used (exp);
9232       break;
9233
9234     case MODE_VECTOR_INT:
9235     case MODE_VECTOR_FLOAT:
9236       {
9237         int i;
9238         machine_mode inner_mode;
9239         gcc_assert (GET_CODE (exp) == CONST_VECTOR);
9240
9241         inner_mode = GET_MODE_INNER (GET_MODE (exp));
9242         for (i = 0; i < XVECLEN (exp, 0); i++)
9243           s390_output_pool_entry (XVECEXP (exp, 0, i),
9244                                   inner_mode,
9245                                   i == 0
9246                                   ? align
9247                                   : GET_MODE_BITSIZE (inner_mode));
9248       }
9249       break;
9250
9251     default:
9252       gcc_unreachable ();
9253     }
9254 }
9255
9256
9257 /* Return an RTL expression representing the value of the return address
9258    for the frame COUNT steps up from the current frame.  FRAME is the
9259    frame pointer of that frame.  */
9260
9261 rtx
9262 s390_return_addr_rtx (int count, rtx frame ATTRIBUTE_UNUSED)
9263 {
9264   int offset;
9265   rtx addr;
9266
9267   /* Without backchain, we fail for all but the current frame.  */
9268
9269   if (!TARGET_BACKCHAIN && count > 0)
9270     return NULL_RTX;
9271
9272   /* For the current frame, we need to make sure the initial
9273      value of RETURN_REGNUM is actually saved.  */
9274
9275   if (count == 0)
9276     {
9277       /* On non-z architectures branch splitting could overwrite r14.  */
9278       if (TARGET_CPU_ZARCH)
9279         return get_hard_reg_initial_val (Pmode, RETURN_REGNUM);
9280       else
9281         {
9282           cfun_frame_layout.save_return_addr_p = true;
9283           return gen_rtx_MEM (Pmode, return_address_pointer_rtx);
9284         }
9285     }
9286
9287   if (TARGET_PACKED_STACK)
9288     offset = -2 * UNITS_PER_LONG;
9289   else
9290     offset = RETURN_REGNUM * UNITS_PER_LONG;
9291
9292   addr = plus_constant (Pmode, frame, offset);
9293   addr = memory_address (Pmode, addr);
9294   return gen_rtx_MEM (Pmode, addr);
9295 }
9296
9297 /* Return an RTL expression representing the back chain stored in
9298    the current stack frame.  */
9299
9300 rtx
9301 s390_back_chain_rtx (void)
9302 {
9303   rtx chain;
9304
9305   gcc_assert (TARGET_BACKCHAIN);
9306
9307   if (TARGET_PACKED_STACK)
9308     chain = plus_constant (Pmode, stack_pointer_rtx,
9309                            STACK_POINTER_OFFSET - UNITS_PER_LONG);
9310   else
9311     chain = stack_pointer_rtx;
9312
9313   chain = gen_rtx_MEM (Pmode, chain);
9314   return chain;
9315 }
9316
9317 /* Find first call clobbered register unused in a function.
9318    This could be used as base register in a leaf function
9319    or for holding the return address before epilogue.  */
9320
9321 static int
9322 find_unused_clobbered_reg (void)
9323 {
9324   int i;
9325   for (i = 0; i < 6; i++)
9326     if (!df_regs_ever_live_p (i))
9327       return i;
9328   return 0;
9329 }
9330
9331
9332 /* Helper function for s390_regs_ever_clobbered.  Sets the fields in DATA for all
9333    clobbered hard regs in SETREG.  */
9334
9335 static void
9336 s390_reg_clobbered_rtx (rtx setreg, const_rtx set_insn ATTRIBUTE_UNUSED, void *data)
9337 {
9338   char *regs_ever_clobbered = (char *)data;
9339   unsigned int i, regno;
9340   machine_mode mode = GET_MODE (setreg);
9341
9342   if (GET_CODE (setreg) == SUBREG)
9343     {
9344       rtx inner = SUBREG_REG (setreg);
9345       if (!GENERAL_REG_P (inner) && !FP_REG_P (inner))
9346         return;
9347       regno = subreg_regno (setreg);
9348     }
9349   else if (GENERAL_REG_P (setreg) || FP_REG_P (setreg))
9350     regno = REGNO (setreg);
9351   else
9352     return;
9353
9354   for (i = regno;
9355        i < regno + HARD_REGNO_NREGS (regno, mode);
9356        i++)
9357     regs_ever_clobbered[i] = 1;
9358 }
9359
9360 /* Walks through all basic blocks of the current function looking
9361    for clobbered hard regs using s390_reg_clobbered_rtx.  The fields
9362    of the passed integer array REGS_EVER_CLOBBERED are set to one for
9363    each of those regs.  */
9364
9365 static void
9366 s390_regs_ever_clobbered (char regs_ever_clobbered[])
9367 {
9368   basic_block cur_bb;
9369   rtx_insn *cur_insn;
9370   unsigned int i;
9371
9372   memset (regs_ever_clobbered, 0, 32);
9373
9374   /* For non-leaf functions we have to consider all call clobbered regs to be
9375      clobbered.  */
9376   if (!crtl->is_leaf)
9377     {
9378       for (i = 0; i < 32; i++)
9379         regs_ever_clobbered[i] = call_really_used_regs[i];
9380     }
9381
9382   /* Make the "magic" eh_return registers live if necessary.  For regs_ever_live
9383      this work is done by liveness analysis (mark_regs_live_at_end).
9384      Special care is needed for functions containing landing pads.  Landing pads
9385      may use the eh registers, but the code which sets these registers is not
9386      contained in that function.  Hence s390_regs_ever_clobbered is not able to
9387      deal with this automatically.  */
9388   if (crtl->calls_eh_return || cfun->machine->has_landing_pad_p)
9389     for (i = 0; EH_RETURN_DATA_REGNO (i) != INVALID_REGNUM ; i++)
9390       if (crtl->calls_eh_return
9391           || (cfun->machine->has_landing_pad_p
9392               && df_regs_ever_live_p (EH_RETURN_DATA_REGNO (i))))
9393         regs_ever_clobbered[EH_RETURN_DATA_REGNO (i)] = 1;
9394
9395   /* For nonlocal gotos all call-saved registers have to be saved.
9396      This flag is also set for the unwinding code in libgcc.
9397      See expand_builtin_unwind_init.  For regs_ever_live this is done by
9398      reload.  */
9399   if (crtl->saves_all_registers)
9400     for (i = 0; i < 32; i++)
9401       if (!call_really_used_regs[i])
9402         regs_ever_clobbered[i] = 1;
9403
9404   FOR_EACH_BB_FN (cur_bb, cfun)
9405     {
9406       FOR_BB_INSNS (cur_bb, cur_insn)
9407         {
9408           rtx pat;
9409
9410           if (!INSN_P (cur_insn))
9411             continue;
9412
9413           pat = PATTERN (cur_insn);
9414
9415           /* Ignore GPR restore insns.  */
9416           if (epilogue_completed && RTX_FRAME_RELATED_P (cur_insn))
9417             {
9418               if (GET_CODE (pat) == SET
9419                   && GENERAL_REG_P (SET_DEST (pat)))
9420                 {
9421                   /* lgdr  */
9422                   if (GET_MODE (SET_SRC (pat)) == DImode
9423                       && FP_REG_P (SET_SRC (pat)))
9424                     continue;
9425
9426                   /* l / lg  */
9427                   if (GET_CODE (SET_SRC (pat)) == MEM)
9428                     continue;
9429                 }
9430
9431               /* lm / lmg */
9432               if (GET_CODE (pat) == PARALLEL
9433                   && load_multiple_operation (pat, VOIDmode))
9434                 continue;
9435             }
9436
9437           note_stores (pat,
9438                        s390_reg_clobbered_rtx,
9439                        regs_ever_clobbered);
9440         }
9441     }
9442 }
9443
9444 /* Determine the frame area which actually has to be accessed
9445    in the function epilogue. The values are stored at the
9446    given pointers AREA_BOTTOM (address of the lowest used stack
9447    address) and AREA_TOP (address of the first item which does
9448    not belong to the stack frame).  */
9449
9450 static void
9451 s390_frame_area (int *area_bottom, int *area_top)
9452 {
9453   int b, t;
9454
9455   b = INT_MAX;
9456   t = INT_MIN;
9457
9458   if (cfun_frame_layout.first_restore_gpr != -1)
9459     {
9460       b = (cfun_frame_layout.gprs_offset
9461            + cfun_frame_layout.first_restore_gpr * UNITS_PER_LONG);
9462       t = b + (cfun_frame_layout.last_restore_gpr
9463                - cfun_frame_layout.first_restore_gpr + 1) * UNITS_PER_LONG;
9464     }
9465
9466   if (TARGET_64BIT && cfun_save_high_fprs_p)
9467     {
9468       b = MIN (b, cfun_frame_layout.f8_offset);
9469       t = MAX (t, (cfun_frame_layout.f8_offset
9470                    + cfun_frame_layout.high_fprs * 8));
9471     }
9472
9473   if (!TARGET_64BIT)
9474     {
9475       if (cfun_fpr_save_p (FPR4_REGNUM))
9476         {
9477           b = MIN (b, cfun_frame_layout.f4_offset);
9478           t = MAX (t, cfun_frame_layout.f4_offset + 8);
9479         }
9480       if (cfun_fpr_save_p (FPR6_REGNUM))
9481         {
9482           b = MIN (b, cfun_frame_layout.f4_offset + 8);
9483           t = MAX (t, cfun_frame_layout.f4_offset + 16);
9484         }
9485     }
9486   *area_bottom = b;
9487   *area_top = t;
9488 }
9489 /* Update gpr_save_slots in the frame layout trying to make use of
9490    FPRs as GPR save slots.
9491    This is a helper routine of s390_register_info.  */
9492
9493 static void
9494 s390_register_info_gprtofpr ()
9495 {
9496   int save_reg_slot = FPR0_REGNUM;
9497   int i, j;
9498
9499   if (!TARGET_Z10 || !TARGET_HARD_FLOAT || !crtl->is_leaf)
9500     return;
9501
9502   for (i = 15; i >= 6; i--)
9503     {
9504       if (cfun_gpr_save_slot (i) == SAVE_SLOT_NONE)
9505         continue;
9506
9507       /* Advance to the next FP register which can be used as a
9508          GPR save slot.  */
9509       while ((!call_really_used_regs[save_reg_slot]
9510               || df_regs_ever_live_p (save_reg_slot)
9511               || cfun_fpr_save_p (save_reg_slot))
9512              && FP_REGNO_P (save_reg_slot))
9513         save_reg_slot++;
9514       if (!FP_REGNO_P (save_reg_slot))
9515         {
9516           /* We only want to use ldgr/lgdr if we can get rid of
9517              stm/lm entirely.  So undo the gpr slot allocation in
9518              case we ran out of FPR save slots.  */
9519           for (j = 6; j <= 15; j++)
9520             if (FP_REGNO_P (cfun_gpr_save_slot (j)))
9521               cfun_gpr_save_slot (j) = SAVE_SLOT_STACK;
9522           break;
9523         }
9524       cfun_gpr_save_slot (i) = save_reg_slot++;
9525     }
9526 }
9527
9528 /* Set the bits in fpr_bitmap for FPRs which need to be saved due to
9529    stdarg.
9530    This is a helper routine for s390_register_info.  */
9531
9532 static void
9533 s390_register_info_stdarg_fpr ()
9534 {
9535   int i;
9536   int min_fpr;
9537   int max_fpr;
9538
9539   /* Save the FP argument regs for stdarg. f0, f2 for 31 bit and
9540      f0-f4 for 64 bit.  */
9541   if (!cfun->stdarg
9542       || !TARGET_HARD_FLOAT
9543       || !cfun->va_list_fpr_size
9544       || crtl->args.info.fprs >= FP_ARG_NUM_REG)
9545     return;
9546
9547   min_fpr = crtl->args.info.fprs;
9548   max_fpr = min_fpr + cfun->va_list_fpr_size - 1;
9549   if (max_fpr >= FP_ARG_NUM_REG)
9550     max_fpr = FP_ARG_NUM_REG - 1;
9551
9552   /* FPR argument regs start at f0.  */
9553   min_fpr += FPR0_REGNUM;
9554   max_fpr += FPR0_REGNUM;
9555
9556   for (i = min_fpr; i <= max_fpr; i++)
9557     cfun_set_fpr_save (i);
9558 }
9559
9560 /* Reserve the GPR save slots for GPRs which need to be saved due to
9561    stdarg.
9562    This is a helper routine for s390_register_info.  */
9563
9564 static void
9565 s390_register_info_stdarg_gpr ()
9566 {
9567   int i;
9568   int min_gpr;
9569   int max_gpr;
9570
9571   if (!cfun->stdarg
9572       || !cfun->va_list_gpr_size
9573       || crtl->args.info.gprs >= GP_ARG_NUM_REG)
9574     return;
9575
9576   min_gpr = crtl->args.info.gprs;
9577   max_gpr = min_gpr + cfun->va_list_gpr_size - 1;
9578   if (max_gpr >= GP_ARG_NUM_REG)
9579     max_gpr = GP_ARG_NUM_REG - 1;
9580
9581   /* GPR argument regs start at r2.  */
9582   min_gpr += GPR2_REGNUM;
9583   max_gpr += GPR2_REGNUM;
9584
9585   /* If r6 was supposed to be saved into an FPR and now needs to go to
9586      the stack for vararg we have to adjust the restore range to make
9587      sure that the restore is done from stack as well.  */
9588   if (FP_REGNO_P (cfun_gpr_save_slot (GPR6_REGNUM))
9589       && min_gpr <= GPR6_REGNUM
9590       && max_gpr >= GPR6_REGNUM)
9591     {
9592       if (cfun_frame_layout.first_restore_gpr == -1
9593           || cfun_frame_layout.first_restore_gpr > GPR6_REGNUM)
9594         cfun_frame_layout.first_restore_gpr = GPR6_REGNUM;
9595       if (cfun_frame_layout.last_restore_gpr == -1
9596           || cfun_frame_layout.last_restore_gpr < GPR6_REGNUM)
9597         cfun_frame_layout.last_restore_gpr = GPR6_REGNUM;
9598     }
9599
9600   if (cfun_frame_layout.first_save_gpr == -1
9601       || cfun_frame_layout.first_save_gpr > min_gpr)
9602     cfun_frame_layout.first_save_gpr = min_gpr;
9603
9604   if (cfun_frame_layout.last_save_gpr == -1
9605       || cfun_frame_layout.last_save_gpr < max_gpr)
9606     cfun_frame_layout.last_save_gpr = max_gpr;
9607
9608   for (i = min_gpr; i <= max_gpr; i++)
9609     cfun_gpr_save_slot (i) = SAVE_SLOT_STACK;
9610 }
9611
9612 /* Calculate the save and restore ranges for stm(g) and lm(g) in the
9613    prologue and epilogue.  */
9614
9615 static void
9616 s390_register_info_set_ranges ()
9617 {
9618   int i, j;
9619
9620   /* Find the first and the last save slot supposed to use the stack
9621      to set the restore range.
9622      Vararg regs might be marked as save to stack but only the
9623      call-saved regs really need restoring (i.e. r6).  This code
9624      assumes that the vararg regs have not yet been recorded in
9625      cfun_gpr_save_slot.  */
9626   for (i = 0; i < 16 && cfun_gpr_save_slot (i) != SAVE_SLOT_STACK; i++);
9627   for (j = 15; j > i && cfun_gpr_save_slot (j) != SAVE_SLOT_STACK; j--);
9628   cfun_frame_layout.first_restore_gpr = (i == 16) ? -1 : i;
9629   cfun_frame_layout.last_restore_gpr = (i == 16) ? -1 : j;
9630   cfun_frame_layout.first_save_gpr = (i == 16) ? -1 : i;
9631   cfun_frame_layout.last_save_gpr = (i == 16) ? -1 : j;
9632 }
9633
9634 /* The GPR and FPR save slots in cfun->machine->frame_layout are set
9635    for registers which need to be saved in function prologue.
9636    This function can be used until the insns emitted for save/restore
9637    of the regs are visible in the RTL stream.  */
9638
9639 static void
9640 s390_register_info ()
9641 {
9642   int i;
9643   char clobbered_regs[32];
9644
9645   gcc_assert (!epilogue_completed);
9646
9647   if (reload_completed)
9648     /* After reload we rely on our own routine to determine which
9649        registers need saving.  */
9650     s390_regs_ever_clobbered (clobbered_regs);
9651   else
9652     /* During reload we use regs_ever_live as a base since reload
9653        does changes in there which we otherwise would not be aware
9654        of.  */
9655     for (i = 0; i < 32; i++)
9656       clobbered_regs[i] = df_regs_ever_live_p (i);
9657
9658   for (i = 0; i < 32; i++)
9659     clobbered_regs[i] = clobbered_regs[i] && !global_regs[i];
9660
9661   /* Mark the call-saved FPRs which need to be saved.
9662      This needs to be done before checking the special GPRs since the
9663      stack pointer usage depends on whether high FPRs have to be saved
9664      or not.  */
9665   cfun_frame_layout.fpr_bitmap = 0;
9666   cfun_frame_layout.high_fprs = 0;
9667   for (i = FPR0_REGNUM; i <= FPR15_REGNUM; i++)
9668     if (clobbered_regs[i] && !call_really_used_regs[i])
9669       {
9670         cfun_set_fpr_save (i);
9671         if (i >= FPR8_REGNUM)
9672           cfun_frame_layout.high_fprs++;
9673       }
9674
9675   /* Register 12 is used for GOT address, but also as temp in prologue
9676      for split-stack stdarg functions (unless r14 is available).  */
9677   clobbered_regs[12]
9678     |= ((flag_pic && df_regs_ever_live_p (PIC_OFFSET_TABLE_REGNUM))
9679         || (flag_split_stack && cfun->stdarg
9680             && (crtl->is_leaf || TARGET_TPF_PROFILING
9681                 || has_hard_reg_initial_val (Pmode, RETURN_REGNUM))));
9682
9683   clobbered_regs[BASE_REGNUM]
9684     |= (cfun->machine->base_reg
9685         && REGNO (cfun->machine->base_reg) == BASE_REGNUM);
9686
9687   clobbered_regs[HARD_FRAME_POINTER_REGNUM]
9688     |= !!frame_pointer_needed;
9689
9690   /* On pre z900 machines this might take until machine dependent
9691      reorg to decide.
9692      save_return_addr_p will only be set on non-zarch machines so
9693      there is no risk that r14 goes into an FPR instead of a stack
9694      slot.  */
9695   clobbered_regs[RETURN_REGNUM]
9696     |= (!crtl->is_leaf
9697         || TARGET_TPF_PROFILING
9698         || cfun->machine->split_branches_pending_p
9699         || cfun_frame_layout.save_return_addr_p
9700         || crtl->calls_eh_return);
9701
9702   clobbered_regs[STACK_POINTER_REGNUM]
9703     |= (!crtl->is_leaf
9704         || TARGET_TPF_PROFILING
9705         || cfun_save_high_fprs_p
9706         || get_frame_size () > 0
9707         || (reload_completed && cfun_frame_layout.frame_size > 0)
9708         || cfun->calls_alloca);
9709
9710   memset (cfun_frame_layout.gpr_save_slots, SAVE_SLOT_NONE, 16);
9711
9712   for (i = 6; i < 16; i++)
9713     if (clobbered_regs[i])
9714       cfun_gpr_save_slot (i) = SAVE_SLOT_STACK;
9715
9716   s390_register_info_stdarg_fpr ();
9717   s390_register_info_gprtofpr ();
9718   s390_register_info_set_ranges ();
9719   /* stdarg functions might need to save GPRs 2 to 6.  This might
9720      override the GPR->FPR save decision made by
9721      s390_register_info_gprtofpr for r6 since vararg regs must go to
9722      the stack.  */
9723   s390_register_info_stdarg_gpr ();
9724 }
9725
9726 /* This function is called by s390_optimize_prologue in order to get
9727    rid of unnecessary GPR save/restore instructions.  The register info
9728    for the GPRs is re-computed and the ranges are re-calculated.  */
9729
9730 static void
9731 s390_optimize_register_info ()
9732 {
9733   char clobbered_regs[32];
9734   int i;
9735
9736   gcc_assert (epilogue_completed);
9737   gcc_assert (!cfun->machine->split_branches_pending_p);
9738
9739   s390_regs_ever_clobbered (clobbered_regs);
9740
9741   for (i = 0; i < 32; i++)
9742     clobbered_regs[i] = clobbered_regs[i] && !global_regs[i];
9743
9744   /* There is still special treatment needed for cases invisible to
9745      s390_regs_ever_clobbered.  */
9746   clobbered_regs[RETURN_REGNUM]
9747     |= (TARGET_TPF_PROFILING
9748         /* When expanding builtin_return_addr in ESA mode we do not
9749            know whether r14 will later be needed as scratch reg when
9750            doing branch splitting.  So the builtin always accesses the
9751            r14 save slot and we need to stick to the save/restore
9752            decision for r14 even if it turns out that it didn't get
9753            clobbered.  */
9754         || cfun_frame_layout.save_return_addr_p
9755         || crtl->calls_eh_return);
9756
9757   memset (cfun_frame_layout.gpr_save_slots, SAVE_SLOT_NONE, 6);
9758
9759   for (i = 6; i < 16; i++)
9760     if (!clobbered_regs[i])
9761       cfun_gpr_save_slot (i) = SAVE_SLOT_NONE;
9762
9763   s390_register_info_set_ranges ();
9764   s390_register_info_stdarg_gpr ();
9765 }
9766
9767 /* Fill cfun->machine with info about frame of current function.  */
9768
9769 static void
9770 s390_frame_info (void)
9771 {
9772   HOST_WIDE_INT lowest_offset;
9773
9774   cfun_frame_layout.first_save_gpr_slot = cfun_frame_layout.first_save_gpr;
9775   cfun_frame_layout.last_save_gpr_slot = cfun_frame_layout.last_save_gpr;
9776
9777   /* The va_arg builtin uses a constant distance of 16 *
9778      UNITS_PER_LONG (r0-r15) to reach the FPRs from the reg_save_area
9779      pointer.  So even if we are going to save the stack pointer in an
9780      FPR we need the stack space in order to keep the offsets
9781      correct.  */
9782   if (cfun->stdarg && cfun_save_arg_fprs_p)
9783     {
9784       cfun_frame_layout.last_save_gpr_slot = STACK_POINTER_REGNUM;
9785
9786       if (cfun_frame_layout.first_save_gpr_slot == -1)
9787         cfun_frame_layout.first_save_gpr_slot = STACK_POINTER_REGNUM;
9788     }
9789
9790   cfun_frame_layout.frame_size = get_frame_size ();
9791   if (!TARGET_64BIT && cfun_frame_layout.frame_size > 0x7fff0000)
9792     fatal_error (input_location,
9793                  "total size of local variables exceeds architecture limit");
9794
9795   if (!TARGET_PACKED_STACK)
9796     {
9797       /* Fixed stack layout.  */
9798       cfun_frame_layout.backchain_offset = 0;
9799       cfun_frame_layout.f0_offset = 16 * UNITS_PER_LONG;
9800       cfun_frame_layout.f4_offset = cfun_frame_layout.f0_offset + 2 * 8;
9801       cfun_frame_layout.f8_offset = -cfun_frame_layout.high_fprs * 8;
9802       cfun_frame_layout.gprs_offset = (cfun_frame_layout.first_save_gpr_slot
9803                                        * UNITS_PER_LONG);
9804     }
9805   else if (TARGET_BACKCHAIN)
9806     {
9807       /* Kernel stack layout - packed stack, backchain, no float  */
9808       gcc_assert (TARGET_SOFT_FLOAT);
9809       cfun_frame_layout.backchain_offset = (STACK_POINTER_OFFSET
9810                                             - UNITS_PER_LONG);
9811
9812       /* The distance between the backchain and the return address
9813          save slot must not change.  So we always need a slot for the
9814          stack pointer which resides in between.  */
9815       cfun_frame_layout.last_save_gpr_slot = STACK_POINTER_REGNUM;
9816
9817       cfun_frame_layout.gprs_offset
9818         = cfun_frame_layout.backchain_offset - cfun_gprs_save_area_size;
9819
9820       /* FPRs will not be saved.  Nevertheless pick sane values to
9821          keep area calculations valid.  */
9822       cfun_frame_layout.f0_offset =
9823         cfun_frame_layout.f4_offset =
9824         cfun_frame_layout.f8_offset = cfun_frame_layout.gprs_offset;
9825     }
9826   else
9827     {
9828       int num_fprs;
9829
9830       /* Packed stack layout without backchain.  */
9831
9832       /* With stdarg FPRs need their dedicated slots.  */
9833       num_fprs = (TARGET_64BIT && cfun->stdarg ? 2
9834                   : (cfun_fpr_save_p (FPR4_REGNUM) +
9835                      cfun_fpr_save_p (FPR6_REGNUM)));
9836       cfun_frame_layout.f4_offset = STACK_POINTER_OFFSET - 8 * num_fprs;
9837
9838       num_fprs = (cfun->stdarg ? 2
9839                   : (cfun_fpr_save_p (FPR0_REGNUM)
9840                      + cfun_fpr_save_p (FPR2_REGNUM)));
9841       cfun_frame_layout.f0_offset = cfun_frame_layout.f4_offset - 8 * num_fprs;
9842
9843       cfun_frame_layout.gprs_offset
9844         = cfun_frame_layout.f0_offset - cfun_gprs_save_area_size;
9845
9846       cfun_frame_layout.f8_offset = (cfun_frame_layout.gprs_offset
9847                                      - cfun_frame_layout.high_fprs * 8);
9848     }
9849
9850   if (cfun_save_high_fprs_p)
9851     cfun_frame_layout.frame_size += cfun_frame_layout.high_fprs * 8;
9852
9853   if (!crtl->is_leaf)
9854     cfun_frame_layout.frame_size += crtl->outgoing_args_size;
9855
9856   /* In the following cases we have to allocate a STACK_POINTER_OFFSET
9857      sized area at the bottom of the stack.  This is required also for
9858      leaf functions.  When GCC generates a local stack reference it
9859      will always add STACK_POINTER_OFFSET to all these references.  */
9860   if (crtl->is_leaf
9861       && !TARGET_TPF_PROFILING
9862       && cfun_frame_layout.frame_size == 0
9863       && !cfun->calls_alloca)
9864     return;
9865
9866   /* Calculate the number of bytes we have used in our own register
9867      save area.  With the packed stack layout we can re-use the
9868      remaining bytes for normal stack elements.  */
9869
9870   if (TARGET_PACKED_STACK)
9871     lowest_offset = MIN (MIN (cfun_frame_layout.f0_offset,
9872                               cfun_frame_layout.f4_offset),
9873                          cfun_frame_layout.gprs_offset);
9874   else
9875     lowest_offset = 0;
9876
9877   if (TARGET_BACKCHAIN)
9878     lowest_offset = MIN (lowest_offset, cfun_frame_layout.backchain_offset);
9879
9880   cfun_frame_layout.frame_size += STACK_POINTER_OFFSET - lowest_offset;
9881
9882   /* If under 31 bit an odd number of gprs has to be saved we have to
9883      adjust the frame size to sustain 8 byte alignment of stack
9884      frames.  */
9885   cfun_frame_layout.frame_size = ((cfun_frame_layout.frame_size +
9886                                    STACK_BOUNDARY / BITS_PER_UNIT - 1)
9887                                   & ~(STACK_BOUNDARY / BITS_PER_UNIT - 1));
9888 }
9889
9890 /* Generate frame layout.  Fills in register and frame data for the current
9891    function in cfun->machine.  This routine can be called multiple times;
9892    it will re-do the complete frame layout every time.  */
9893
9894 static void
9895 s390_init_frame_layout (void)
9896 {
9897   HOST_WIDE_INT frame_size;
9898   int base_used;
9899
9900   /* After LRA the frame layout is supposed to be read-only and should
9901      not be re-computed.  */
9902   if (reload_completed)
9903     return;
9904
9905   /* On S/390 machines, we may need to perform branch splitting, which
9906      will require both base and return address register.  We have no
9907      choice but to assume we're going to need them until right at the
9908      end of the machine dependent reorg phase.  */
9909   if (!TARGET_CPU_ZARCH)
9910     cfun->machine->split_branches_pending_p = true;
9911
9912   do
9913     {
9914       frame_size = cfun_frame_layout.frame_size;
9915
9916       /* Try to predict whether we'll need the base register.  */
9917       base_used = cfun->machine->split_branches_pending_p
9918                   || crtl->uses_const_pool
9919                   || (!DISP_IN_RANGE (frame_size)
9920                       && !CONST_OK_FOR_K (frame_size));
9921
9922       /* Decide which register to use as literal pool base.  In small
9923          leaf functions, try to use an unused call-clobbered register
9924          as base register to avoid save/restore overhead.  */
9925       if (!base_used)
9926         cfun->machine->base_reg = NULL_RTX;
9927       else
9928         {
9929           int br = 0;
9930
9931           if (crtl->is_leaf)
9932             /* Prefer r5 (most likely to be free).  */
9933             for (br = 5; br >= 2 && df_regs_ever_live_p (br); br--)
9934               ;
9935           cfun->machine->base_reg =
9936             gen_rtx_REG (Pmode, (br >= 2) ? br : BASE_REGNUM);
9937         }
9938
9939       s390_register_info ();
9940       s390_frame_info ();
9941     }
9942   while (frame_size != cfun_frame_layout.frame_size);
9943 }
9944
9945 /* Remove the FPR clobbers from a tbegin insn if it can be proven that
9946    the TX is nonescaping.  A transaction is considered escaping if
9947    there is at least one path from tbegin returning CC0 to the
9948    function exit block without an tend.
9949
9950    The check so far has some limitations:
9951    - only single tbegin/tend BBs are supported
9952    - the first cond jump after tbegin must separate the CC0 path from ~CC0
9953    - when CC is copied to a GPR and the CC0 check is done with the GPR
9954      this is not supported
9955 */
9956
9957 static void
9958 s390_optimize_nonescaping_tx (void)
9959 {
9960   const unsigned int CC0 = 1 << 3;
9961   basic_block tbegin_bb = NULL;
9962   basic_block tend_bb = NULL;
9963   basic_block bb;
9964   rtx_insn *insn;
9965   bool result = true;
9966   int bb_index;
9967   rtx_insn *tbegin_insn = NULL;
9968
9969   if (!cfun->machine->tbegin_p)
9970     return;
9971
9972   for (bb_index = 0; bb_index < n_basic_blocks_for_fn (cfun); bb_index++)
9973     {
9974       bb = BASIC_BLOCK_FOR_FN (cfun, bb_index);
9975
9976       if (!bb)
9977         continue;
9978
9979       FOR_BB_INSNS (bb, insn)
9980         {
9981           rtx ite, cc, pat, target;
9982           unsigned HOST_WIDE_INT mask;
9983
9984           if (!INSN_P (insn) || INSN_CODE (insn) <= 0)
9985             continue;
9986
9987           pat = PATTERN (insn);
9988
9989           if (GET_CODE (pat) == PARALLEL)
9990             pat = XVECEXP (pat, 0, 0);
9991
9992           if (GET_CODE (pat) != SET
9993               || GET_CODE (SET_SRC (pat)) != UNSPEC_VOLATILE)
9994             continue;
9995
9996           if (XINT (SET_SRC (pat), 1) == UNSPECV_TBEGIN)
9997             {
9998               rtx_insn *tmp;
9999
10000               tbegin_insn = insn;
10001
10002               /* Just return if the tbegin doesn't have clobbers.  */
10003               if (GET_CODE (PATTERN (insn)) != PARALLEL)
10004                 return;
10005
10006               if (tbegin_bb != NULL)
10007                 return;
10008
10009               /* Find the next conditional jump.  */
10010               for (tmp = NEXT_INSN (insn);
10011                    tmp != NULL_RTX;
10012                    tmp = NEXT_INSN (tmp))
10013                 {
10014                   if (reg_set_p (gen_rtx_REG (CCmode, CC_REGNUM), tmp))
10015                     return;
10016                   if (!JUMP_P (tmp))
10017                     continue;
10018
10019                   ite = SET_SRC (PATTERN (tmp));
10020                   if (GET_CODE (ite) != IF_THEN_ELSE)
10021                     continue;
10022
10023                   cc = XEXP (XEXP (ite, 0), 0);
10024                   if (!REG_P (cc) || !CC_REGNO_P (REGNO (cc))
10025                       || GET_MODE (cc) != CCRAWmode
10026                       || GET_CODE (XEXP (XEXP (ite, 0), 1)) != CONST_INT)
10027                     return;
10028
10029                   if (bb->succs->length () != 2)
10030                     return;
10031
10032                   mask = INTVAL (XEXP (XEXP (ite, 0), 1));
10033                   if (GET_CODE (XEXP (ite, 0)) == NE)
10034                     mask ^= 0xf;
10035
10036                   if (mask == CC0)
10037                     target = XEXP (ite, 1);
10038                   else if (mask == (CC0 ^ 0xf))
10039                     target = XEXP (ite, 2);
10040                   else
10041                     return;
10042
10043                   {
10044                     edge_iterator ei;
10045                     edge e1, e2;
10046
10047                     ei = ei_start (bb->succs);
10048                     e1 = ei_safe_edge (ei);
10049                     ei_next (&ei);
10050                     e2 = ei_safe_edge (ei);
10051
10052                     if (e2->flags & EDGE_FALLTHRU)
10053                       {
10054                         e2 = e1;
10055                         e1 = ei_safe_edge (ei);
10056                       }
10057
10058                     if (!(e1->flags & EDGE_FALLTHRU))
10059                       return;
10060
10061                     tbegin_bb = (target == pc_rtx) ? e1->dest : e2->dest;
10062                   }
10063                   if (tmp == BB_END (bb))
10064                     break;
10065                 }
10066             }
10067
10068           if (XINT (SET_SRC (pat), 1) == UNSPECV_TEND)
10069             {
10070               if (tend_bb != NULL)
10071                 return;
10072               tend_bb = bb;
10073             }
10074         }
10075     }
10076
10077   /* Either we successfully remove the FPR clobbers here or we are not
10078      able to do anything for this TX.  Both cases don't qualify for
10079      another look.  */
10080   cfun->machine->tbegin_p = false;
10081
10082   if (tbegin_bb == NULL || tend_bb == NULL)
10083     return;
10084
10085   calculate_dominance_info (CDI_POST_DOMINATORS);
10086   result = dominated_by_p (CDI_POST_DOMINATORS, tbegin_bb, tend_bb);
10087   free_dominance_info (CDI_POST_DOMINATORS);
10088
10089   if (!result)
10090     return;
10091
10092   PATTERN (tbegin_insn) = gen_rtx_PARALLEL (VOIDmode,
10093                             gen_rtvec (2,
10094                                        XVECEXP (PATTERN (tbegin_insn), 0, 0),
10095                                        XVECEXP (PATTERN (tbegin_insn), 0, 1)));
10096   INSN_CODE (tbegin_insn) = -1;
10097   df_insn_rescan (tbegin_insn);
10098
10099   return;
10100 }
10101
10102 /* Return true if it is legal to put a value with MODE into REGNO.  */
10103
10104 bool
10105 s390_hard_regno_mode_ok (unsigned int regno, machine_mode mode)
10106 {
10107   if (!TARGET_VX && VECTOR_NOFP_REGNO_P (regno))
10108     return false;
10109
10110   switch (REGNO_REG_CLASS (regno))
10111     {
10112     case VEC_REGS:
10113       return ((GET_MODE_CLASS (mode) == MODE_INT
10114                && s390_class_max_nregs (VEC_REGS, mode) == 1)
10115               || mode == DFmode
10116               || (TARGET_VXE && mode == SFmode)
10117               || s390_vector_mode_supported_p (mode));
10118       break;
10119     case FP_REGS:
10120       if (TARGET_VX
10121           && ((GET_MODE_CLASS (mode) == MODE_INT
10122                && s390_class_max_nregs (FP_REGS, mode) == 1)
10123               || mode == DFmode
10124               || s390_vector_mode_supported_p (mode)))
10125         return true;
10126
10127       if (REGNO_PAIR_OK (regno, mode))
10128         {
10129           if (mode == SImode || mode == DImode)
10130             return true;
10131
10132           if (FLOAT_MODE_P (mode) && GET_MODE_CLASS (mode) != MODE_VECTOR_FLOAT)
10133             return true;
10134         }
10135       break;
10136     case ADDR_REGS:
10137       if (FRAME_REGNO_P (regno) && mode == Pmode)
10138         return true;
10139
10140       /* fallthrough */
10141     case GENERAL_REGS:
10142       if (REGNO_PAIR_OK (regno, mode))
10143         {
10144           if (TARGET_ZARCH
10145               || (mode != TFmode && mode != TCmode && mode != TDmode))
10146             return true;
10147         }
10148       break;
10149     case CC_REGS:
10150       if (GET_MODE_CLASS (mode) == MODE_CC)
10151         return true;
10152       break;
10153     case ACCESS_REGS:
10154       if (REGNO_PAIR_OK (regno, mode))
10155         {
10156           if (mode == SImode || mode == Pmode)
10157             return true;
10158         }
10159       break;
10160     default:
10161       return false;
10162     }
10163
10164   return false;
10165 }
10166
10167 /* Return nonzero if register OLD_REG can be renamed to register NEW_REG.  */
10168
10169 bool
10170 s390_hard_regno_rename_ok (unsigned int old_reg, unsigned int new_reg)
10171 {
10172    /* Once we've decided upon a register to use as base register, it must
10173       no longer be used for any other purpose.  */
10174   if (cfun->machine->base_reg)
10175     if (REGNO (cfun->machine->base_reg) == old_reg
10176         || REGNO (cfun->machine->base_reg) == new_reg)
10177       return false;
10178
10179   /* Prevent regrename from using call-saved regs which haven't
10180      actually been saved.  This is necessary since regrename assumes
10181      the backend save/restore decisions are based on
10182      df_regs_ever_live.  Since we have our own routine we have to tell
10183      regrename manually about it.  */
10184   if (GENERAL_REGNO_P (new_reg)
10185       && !call_really_used_regs[new_reg]
10186       && cfun_gpr_save_slot (new_reg) == SAVE_SLOT_NONE)
10187     return false;
10188
10189   return true;
10190 }
10191
10192 /* Return nonzero if register REGNO can be used as a scratch register
10193    in peephole2.  */
10194
10195 static bool
10196 s390_hard_regno_scratch_ok (unsigned int regno)
10197 {
10198   /* See s390_hard_regno_rename_ok.  */
10199   if (GENERAL_REGNO_P (regno)
10200       && !call_really_used_regs[regno]
10201       && cfun_gpr_save_slot (regno) == SAVE_SLOT_NONE)
10202     return false;
10203
10204   return true;
10205 }
10206
10207 /* Maximum number of registers to represent a value of mode MODE
10208    in a register of class RCLASS.  */
10209
10210 int
10211 s390_class_max_nregs (enum reg_class rclass, machine_mode mode)
10212 {
10213   int reg_size;
10214   bool reg_pair_required_p = false;
10215
10216   switch (rclass)
10217     {
10218     case FP_REGS:
10219     case VEC_REGS:
10220       reg_size = TARGET_VX ? 16 : 8;
10221
10222       /* TF and TD modes would fit into a VR but we put them into a
10223          register pair since we do not have 128bit FP instructions on
10224          full VRs.  */
10225       if (TARGET_VX
10226           && SCALAR_FLOAT_MODE_P (mode)
10227           && GET_MODE_SIZE (mode) >= 16)
10228         reg_pair_required_p = true;
10229
10230       /* Even if complex types would fit into a single FPR/VR we force
10231          them into a register pair to deal with the parts more easily.
10232          (FIXME: What about complex ints?)  */
10233       if (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
10234         reg_pair_required_p = true;
10235       break;
10236     case ACCESS_REGS:
10237       reg_size = 4;
10238       break;
10239     default:
10240       reg_size = UNITS_PER_WORD;
10241       break;
10242     }
10243
10244   if (reg_pair_required_p)
10245     return 2 * ((GET_MODE_SIZE (mode) / 2 + reg_size - 1) / reg_size);
10246
10247   return (GET_MODE_SIZE (mode) + reg_size - 1) / reg_size;
10248 }
10249
10250 /* Return TRUE if changing mode from FROM to TO should not be allowed
10251    for register class CLASS.  */
10252
10253 int
10254 s390_cannot_change_mode_class (machine_mode from_mode,
10255                                machine_mode to_mode,
10256                                enum reg_class rclass)
10257 {
10258   machine_mode small_mode;
10259   machine_mode big_mode;
10260
10261   /* V1TF and TF have different representations in vector
10262      registers.  */
10263   if (reg_classes_intersect_p (VEC_REGS, rclass)
10264       && ((from_mode == V1TFmode && to_mode == TFmode)
10265           || (from_mode == TFmode && to_mode == V1TFmode)))
10266     return 1;
10267
10268   if (GET_MODE_SIZE (from_mode) == GET_MODE_SIZE (to_mode))
10269     return 0;
10270
10271   if (GET_MODE_SIZE (from_mode) < GET_MODE_SIZE (to_mode))
10272     {
10273       small_mode = from_mode;
10274       big_mode = to_mode;
10275     }
10276   else
10277     {
10278       small_mode = to_mode;
10279       big_mode = from_mode;
10280     }
10281
10282   /* Values residing in VRs are little-endian style.  All modes are
10283      placed left-aligned in an VR.  This means that we cannot allow
10284      switching between modes with differing sizes.  Also if the vector
10285      facility is available we still place TFmode values in VR register
10286      pairs, since the only instructions we have operating on TFmodes
10287      only deal with register pairs.  Therefore we have to allow DFmode
10288      subregs of TFmodes to enable the TFmode splitters.  */
10289   if (reg_classes_intersect_p (VEC_REGS, rclass)
10290       && (GET_MODE_SIZE (small_mode) < 8
10291           || s390_class_max_nregs (VEC_REGS, big_mode) == 1))
10292     return 1;
10293
10294   /* Likewise for access registers, since they have only half the
10295      word size on 64-bit.  */
10296   if (reg_classes_intersect_p (ACCESS_REGS, rclass))
10297     return 1;
10298
10299   return 0;
10300 }
10301
10302 /* Return true if we use LRA instead of reload pass.  */
10303 static bool
10304 s390_lra_p (void)
10305 {
10306   return s390_lra_flag;
10307 }
10308
10309 /* Return true if register FROM can be eliminated via register TO.  */
10310
10311 static bool
10312 s390_can_eliminate (const int from, const int to)
10313 {
10314   /* On zSeries machines, we have not marked the base register as fixed.
10315      Instead, we have an elimination rule BASE_REGNUM -> BASE_REGNUM.
10316      If a function requires the base register, we say here that this
10317      elimination cannot be performed.  This will cause reload to free
10318      up the base register (as if it were fixed).  On the other hand,
10319      if the current function does *not* require the base register, we
10320      say here the elimination succeeds, which in turn allows reload
10321      to allocate the base register for any other purpose.  */
10322   if (from == BASE_REGNUM && to == BASE_REGNUM)
10323     {
10324       if (TARGET_CPU_ZARCH)
10325         {
10326           s390_init_frame_layout ();
10327           return cfun->machine->base_reg == NULL_RTX;
10328         }
10329
10330       return false;
10331     }
10332
10333   /* Everything else must point into the stack frame.  */
10334   gcc_assert (to == STACK_POINTER_REGNUM
10335               || to == HARD_FRAME_POINTER_REGNUM);
10336
10337   gcc_assert (from == FRAME_POINTER_REGNUM
10338               || from == ARG_POINTER_REGNUM
10339               || from == RETURN_ADDRESS_POINTER_REGNUM);
10340
10341   /* Make sure we actually saved the return address.  */
10342   if (from == RETURN_ADDRESS_POINTER_REGNUM)
10343     if (!crtl->calls_eh_return
10344         && !cfun->stdarg
10345         && !cfun_frame_layout.save_return_addr_p)
10346       return false;
10347
10348   return true;
10349 }
10350
10351 /* Return offset between register FROM and TO initially after prolog.  */
10352
10353 HOST_WIDE_INT
10354 s390_initial_elimination_offset (int from, int to)
10355 {
10356   HOST_WIDE_INT offset;
10357
10358   /* ??? Why are we called for non-eliminable pairs?  */
10359   if (!s390_can_eliminate (from, to))
10360     return 0;
10361
10362   switch (from)
10363     {
10364     case FRAME_POINTER_REGNUM:
10365       offset = (get_frame_size()
10366                 + STACK_POINTER_OFFSET
10367                 + crtl->outgoing_args_size);
10368       break;
10369
10370     case ARG_POINTER_REGNUM:
10371       s390_init_frame_layout ();
10372       offset = cfun_frame_layout.frame_size + STACK_POINTER_OFFSET;
10373       break;
10374
10375     case RETURN_ADDRESS_POINTER_REGNUM:
10376       s390_init_frame_layout ();
10377
10378       if (cfun_frame_layout.first_save_gpr_slot == -1)
10379         {
10380           /* If it turns out that for stdarg nothing went into the reg
10381              save area we also do not need the return address
10382              pointer.  */
10383           if (cfun->stdarg && !cfun_save_arg_fprs_p)
10384             return 0;
10385
10386           gcc_unreachable ();
10387         }
10388
10389       /* In order to make the following work it is not necessary for
10390          r14 to have a save slot.  It is sufficient if one other GPR
10391          got one.  Since the GPRs are always stored without gaps we
10392          are able to calculate where the r14 save slot would
10393          reside.  */
10394       offset = (cfun_frame_layout.frame_size + cfun_frame_layout.gprs_offset +
10395                 (RETURN_REGNUM - cfun_frame_layout.first_save_gpr_slot) *
10396                 UNITS_PER_LONG);
10397       break;
10398
10399     case BASE_REGNUM:
10400       offset = 0;
10401       break;
10402
10403     default:
10404       gcc_unreachable ();
10405     }
10406
10407   return offset;
10408 }
10409
10410 /* Emit insn to save fpr REGNUM at offset OFFSET relative
10411    to register BASE.  Return generated insn.  */
10412
10413 static rtx
10414 save_fpr (rtx base, int offset, int regnum)
10415 {
10416   rtx addr;
10417   addr = gen_rtx_MEM (DFmode, plus_constant (Pmode, base, offset));
10418
10419   if (regnum >= 16 && regnum <= (16 + FP_ARG_NUM_REG))
10420     set_mem_alias_set (addr, get_varargs_alias_set ());
10421   else
10422     set_mem_alias_set (addr, get_frame_alias_set ());
10423
10424   return emit_move_insn (addr, gen_rtx_REG (DFmode, regnum));
10425 }
10426
10427 /* Emit insn to restore fpr REGNUM from offset OFFSET relative
10428    to register BASE.  Return generated insn.  */
10429
10430 static rtx
10431 restore_fpr (rtx base, int offset, int regnum)
10432 {
10433   rtx addr;
10434   addr = gen_rtx_MEM (DFmode, plus_constant (Pmode, base, offset));
10435   set_mem_alias_set (addr, get_frame_alias_set ());
10436
10437   return emit_move_insn (gen_rtx_REG (DFmode, regnum), addr);
10438 }
10439
10440 /* Return true if REGNO is a global register, but not one
10441    of the special ones that need to be saved/restored in anyway.  */
10442
10443 static inline bool
10444 global_not_special_regno_p (int regno)
10445 {
10446   return (global_regs[regno]
10447           /* These registers are special and need to be
10448              restored in any case.  */
10449           && !(regno == STACK_POINTER_REGNUM
10450                || regno == RETURN_REGNUM
10451                || regno == BASE_REGNUM
10452                || (flag_pic && regno == (int)PIC_OFFSET_TABLE_REGNUM)));
10453 }
10454
10455 /* Generate insn to save registers FIRST to LAST into
10456    the register save area located at offset OFFSET
10457    relative to register BASE.  */
10458
10459 static rtx
10460 save_gprs (rtx base, int offset, int first, int last)
10461 {
10462   rtx addr, insn, note;
10463   int i;
10464
10465   addr = plus_constant (Pmode, base, offset);
10466   addr = gen_rtx_MEM (Pmode, addr);
10467
10468   set_mem_alias_set (addr, get_frame_alias_set ());
10469
10470   /* Special-case single register.  */
10471   if (first == last)
10472     {
10473       if (TARGET_64BIT)
10474         insn = gen_movdi (addr, gen_rtx_REG (Pmode, first));
10475       else
10476         insn = gen_movsi (addr, gen_rtx_REG (Pmode, first));
10477
10478       if (!global_not_special_regno_p (first))
10479         RTX_FRAME_RELATED_P (insn) = 1;
10480       return insn;
10481     }
10482
10483
10484   insn = gen_store_multiple (addr,
10485                              gen_rtx_REG (Pmode, first),
10486                              GEN_INT (last - first + 1));
10487
10488   if (first <= 6 && cfun->stdarg)
10489     for (i = 0; i < XVECLEN (PATTERN (insn), 0); i++)
10490       {
10491         rtx mem = XEXP (XVECEXP (PATTERN (insn), 0, i), 0);
10492
10493         if (first + i <= 6)
10494           set_mem_alias_set (mem, get_varargs_alias_set ());
10495       }
10496
10497   /* We need to set the FRAME_RELATED flag on all SETs
10498      inside the store-multiple pattern.
10499
10500      However, we must not emit DWARF records for registers 2..5
10501      if they are stored for use by variable arguments ...
10502
10503      ??? Unfortunately, it is not enough to simply not the
10504      FRAME_RELATED flags for those SETs, because the first SET
10505      of the PARALLEL is always treated as if it had the flag
10506      set, even if it does not.  Therefore we emit a new pattern
10507      without those registers as REG_FRAME_RELATED_EXPR note.  */
10508
10509   if (first >= 6 && !global_not_special_regno_p (first))
10510     {
10511       rtx pat = PATTERN (insn);
10512
10513       for (i = 0; i < XVECLEN (pat, 0); i++)
10514         if (GET_CODE (XVECEXP (pat, 0, i)) == SET
10515             && !global_not_special_regno_p (REGNO (SET_SRC (XVECEXP (pat,
10516                                                                      0, i)))))
10517           RTX_FRAME_RELATED_P (XVECEXP (pat, 0, i)) = 1;
10518
10519       RTX_FRAME_RELATED_P (insn) = 1;
10520     }
10521   else if (last >= 6)
10522     {
10523       int start;
10524
10525       for (start = first >= 6 ? first : 6; start <= last; start++)
10526         if (!global_not_special_regno_p (start))
10527           break;
10528
10529       if (start > last)
10530         return insn;
10531
10532       addr = plus_constant (Pmode, base,
10533                             offset + (start - first) * UNITS_PER_LONG);
10534
10535       if (start == last)
10536         {
10537           if (TARGET_64BIT)
10538             note = gen_movdi (gen_rtx_MEM (Pmode, addr),
10539                               gen_rtx_REG (Pmode, start));
10540           else
10541             note = gen_movsi (gen_rtx_MEM (Pmode, addr),
10542                               gen_rtx_REG (Pmode, start));
10543           note = PATTERN (note);
10544
10545           add_reg_note (insn, REG_FRAME_RELATED_EXPR, note);
10546           RTX_FRAME_RELATED_P (insn) = 1;
10547
10548           return insn;
10549         }
10550
10551       note = gen_store_multiple (gen_rtx_MEM (Pmode, addr),
10552                                  gen_rtx_REG (Pmode, start),
10553                                  GEN_INT (last - start + 1));
10554       note = PATTERN (note);
10555
10556       add_reg_note (insn, REG_FRAME_RELATED_EXPR, note);
10557
10558       for (i = 0; i < XVECLEN (note, 0); i++)
10559         if (GET_CODE (XVECEXP (note, 0, i)) == SET
10560             && !global_not_special_regno_p (REGNO (SET_SRC (XVECEXP (note,
10561                                                                      0, i)))))
10562           RTX_FRAME_RELATED_P (XVECEXP (note, 0, i)) = 1;
10563
10564       RTX_FRAME_RELATED_P (insn) = 1;
10565     }
10566
10567   return insn;
10568 }
10569
10570 /* Generate insn to restore registers FIRST to LAST from
10571    the register save area located at offset OFFSET
10572    relative to register BASE.  */
10573
10574 static rtx
10575 restore_gprs (rtx base, int offset, int first, int last)
10576 {
10577   rtx addr, insn;
10578
10579   addr = plus_constant (Pmode, base, offset);
10580   addr = gen_rtx_MEM (Pmode, addr);
10581   set_mem_alias_set (addr, get_frame_alias_set ());
10582
10583   /* Special-case single register.  */
10584   if (first == last)
10585     {
10586       if (TARGET_64BIT)
10587         insn = gen_movdi (gen_rtx_REG (Pmode, first), addr);
10588       else
10589         insn = gen_movsi (gen_rtx_REG (Pmode, first), addr);
10590
10591       RTX_FRAME_RELATED_P (insn) = 1;
10592       return insn;
10593     }
10594
10595   insn = gen_load_multiple (gen_rtx_REG (Pmode, first),
10596                             addr,
10597                             GEN_INT (last - first + 1));
10598   RTX_FRAME_RELATED_P (insn) = 1;
10599   return insn;
10600 }
10601
10602 /* Return insn sequence to load the GOT register.  */
10603
10604 static GTY(()) rtx got_symbol;
10605 rtx_insn *
10606 s390_load_got (void)
10607 {
10608   rtx_insn *insns;
10609
10610   /* We cannot use pic_offset_table_rtx here since we use this
10611      function also for non-pic if __tls_get_offset is called and in
10612      that case PIC_OFFSET_TABLE_REGNUM as well as pic_offset_table_rtx
10613      aren't usable.  */
10614   rtx got_rtx = gen_rtx_REG (Pmode, 12);
10615
10616   if (!got_symbol)
10617     {
10618       got_symbol = gen_rtx_SYMBOL_REF (Pmode, "_GLOBAL_OFFSET_TABLE_");
10619       SYMBOL_REF_FLAGS (got_symbol) = SYMBOL_FLAG_LOCAL;
10620     }
10621
10622   start_sequence ();
10623
10624   if (TARGET_CPU_ZARCH)
10625     {
10626       emit_move_insn (got_rtx, got_symbol);
10627     }
10628   else
10629     {
10630       rtx offset;
10631
10632       offset = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, got_symbol),
10633                                UNSPEC_LTREL_OFFSET);
10634       offset = gen_rtx_CONST (Pmode, offset);
10635       offset = force_const_mem (Pmode, offset);
10636
10637       emit_move_insn (got_rtx, offset);
10638
10639       offset = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, XEXP (offset, 0)),
10640                                UNSPEC_LTREL_BASE);
10641       offset = gen_rtx_PLUS (Pmode, got_rtx, offset);
10642
10643       emit_move_insn (got_rtx, offset);
10644     }
10645
10646   insns = get_insns ();
10647   end_sequence ();
10648   return insns;
10649 }
10650
10651 /* This ties together stack memory (MEM with an alias set of frame_alias_set)
10652    and the change to the stack pointer.  */
10653
10654 static void
10655 s390_emit_stack_tie (void)
10656 {
10657   rtx mem = gen_frame_mem (BLKmode,
10658                            gen_rtx_REG (Pmode, STACK_POINTER_REGNUM));
10659
10660   emit_insn (gen_stack_tie (mem));
10661 }
10662
10663 /* Copy GPRS into FPR save slots.  */
10664
10665 static void
10666 s390_save_gprs_to_fprs (void)
10667 {
10668   int i;
10669
10670   if (!TARGET_Z10 || !TARGET_HARD_FLOAT || !crtl->is_leaf)
10671     return;
10672
10673   for (i = 6; i < 16; i++)
10674     {
10675       if (FP_REGNO_P (cfun_gpr_save_slot (i)))
10676         {
10677           rtx_insn *insn =
10678             emit_move_insn (gen_rtx_REG (DImode, cfun_gpr_save_slot (i)),
10679                             gen_rtx_REG (DImode, i));
10680           RTX_FRAME_RELATED_P (insn) = 1;
10681           /* This prevents dwarf2cfi from interpreting the set.  Doing
10682              so it might emit def_cfa_register infos setting an FPR as
10683              new CFA.  */
10684           add_reg_note (insn, REG_CFA_REGISTER, copy_rtx (PATTERN (insn)));
10685         }
10686     }
10687 }
10688
10689 /* Restore GPRs from FPR save slots.  */
10690
10691 static void
10692 s390_restore_gprs_from_fprs (void)
10693 {
10694   int i;
10695
10696   if (!TARGET_Z10 || !TARGET_HARD_FLOAT || !crtl->is_leaf)
10697     return;
10698
10699   for (i = 6; i < 16; i++)
10700     {
10701       rtx_insn *insn;
10702
10703       if (!FP_REGNO_P (cfun_gpr_save_slot (i)))
10704         continue;
10705
10706       rtx fpr = gen_rtx_REG (DImode, cfun_gpr_save_slot (i));
10707
10708       if (i == STACK_POINTER_REGNUM)
10709         insn = emit_insn (gen_stack_restore_from_fpr (fpr));
10710       else
10711         insn = emit_move_insn (gen_rtx_REG (DImode, i), fpr);
10712
10713       df_set_regs_ever_live (i, true);
10714       add_reg_note (insn, REG_CFA_RESTORE, gen_rtx_REG (DImode, i));
10715       if (i == STACK_POINTER_REGNUM)
10716         add_reg_note (insn, REG_CFA_DEF_CFA,
10717                       plus_constant (Pmode, stack_pointer_rtx,
10718                                      STACK_POINTER_OFFSET));
10719       RTX_FRAME_RELATED_P (insn) = 1;
10720     }
10721 }
10722
10723
10724 /* A pass run immediately before shrink-wrapping and prologue and epilogue
10725    generation.  */
10726
10727 namespace {
10728
10729 const pass_data pass_data_s390_early_mach =
10730 {
10731   RTL_PASS, /* type */
10732   "early_mach", /* name */
10733   OPTGROUP_NONE, /* optinfo_flags */
10734   TV_MACH_DEP, /* tv_id */
10735   0, /* properties_required */
10736   0, /* properties_provided */
10737   0, /* properties_destroyed */
10738   0, /* todo_flags_start */
10739   ( TODO_df_verify | TODO_df_finish ), /* todo_flags_finish */
10740 };
10741
10742 class pass_s390_early_mach : public rtl_opt_pass
10743 {
10744 public:
10745   pass_s390_early_mach (gcc::context *ctxt)
10746     : rtl_opt_pass (pass_data_s390_early_mach, ctxt)
10747   {}
10748
10749   /* opt_pass methods: */
10750   virtual unsigned int execute (function *);
10751
10752 }; // class pass_s390_early_mach
10753
10754 unsigned int
10755 pass_s390_early_mach::execute (function *fun)
10756 {
10757   rtx_insn *insn;
10758
10759   /* Try to get rid of the FPR clobbers.  */
10760   s390_optimize_nonescaping_tx ();
10761
10762   /* Re-compute register info.  */
10763   s390_register_info ();
10764
10765   /* If we're using a base register, ensure that it is always valid for
10766      the first non-prologue instruction.  */
10767   if (fun->machine->base_reg)
10768     emit_insn_at_entry (gen_main_pool (fun->machine->base_reg));
10769
10770   /* Annotate all constant pool references to let the scheduler know
10771      they implicitly use the base register.  */
10772   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
10773     if (INSN_P (insn))
10774       {
10775         annotate_constant_pool_refs (&PATTERN (insn));
10776         df_insn_rescan (insn);
10777       }
10778   return 0;
10779 }
10780
10781 } // anon namespace
10782
10783 /* Expand the prologue into a bunch of separate insns.  */
10784
10785 void
10786 s390_emit_prologue (void)
10787 {
10788   rtx insn, addr;
10789   rtx temp_reg;
10790   int i;
10791   int offset;
10792   int next_fpr = 0;
10793
10794   /* Choose best register to use for temp use within prologue.
10795      TPF with profiling must avoid the register 14 - the tracing function
10796      needs the original contents of r14 to be preserved.  */
10797
10798   if (!has_hard_reg_initial_val (Pmode, RETURN_REGNUM)
10799       && !crtl->is_leaf
10800       && !TARGET_TPF_PROFILING)
10801     temp_reg = gen_rtx_REG (Pmode, RETURN_REGNUM);
10802   else if (flag_split_stack && cfun->stdarg)
10803     temp_reg = gen_rtx_REG (Pmode, 12);
10804   else
10805     temp_reg = gen_rtx_REG (Pmode, 1);
10806
10807   s390_save_gprs_to_fprs ();
10808
10809   /* Save call saved gprs.  */
10810   if (cfun_frame_layout.first_save_gpr != -1)
10811     {
10812       insn = save_gprs (stack_pointer_rtx,
10813                         cfun_frame_layout.gprs_offset +
10814                         UNITS_PER_LONG * (cfun_frame_layout.first_save_gpr
10815                                           - cfun_frame_layout.first_save_gpr_slot),
10816                         cfun_frame_layout.first_save_gpr,
10817                         cfun_frame_layout.last_save_gpr);
10818       emit_insn (insn);
10819     }
10820
10821   /* Dummy insn to mark literal pool slot.  */
10822
10823   if (cfun->machine->base_reg)
10824     emit_insn (gen_main_pool (cfun->machine->base_reg));
10825
10826   offset = cfun_frame_layout.f0_offset;
10827
10828   /* Save f0 and f2.  */
10829   for (i = FPR0_REGNUM; i <= FPR0_REGNUM + 1; i++)
10830     {
10831       if (cfun_fpr_save_p (i))
10832         {
10833           save_fpr (stack_pointer_rtx, offset, i);
10834           offset += 8;
10835         }
10836       else if (!TARGET_PACKED_STACK || cfun->stdarg)
10837         offset += 8;
10838     }
10839
10840   /* Save f4 and f6.  */
10841   offset = cfun_frame_layout.f4_offset;
10842   for (i = FPR4_REGNUM; i <= FPR4_REGNUM + 1; i++)
10843     {
10844       if (cfun_fpr_save_p (i))
10845         {
10846           insn = save_fpr (stack_pointer_rtx, offset, i);
10847           offset += 8;
10848
10849           /* If f4 and f6 are call clobbered they are saved due to
10850              stdargs and therefore are not frame related.  */
10851           if (!call_really_used_regs[i])
10852             RTX_FRAME_RELATED_P (insn) = 1;
10853         }
10854       else if (!TARGET_PACKED_STACK || call_really_used_regs[i])
10855         offset += 8;
10856     }
10857
10858   if (TARGET_PACKED_STACK
10859       && cfun_save_high_fprs_p
10860       && cfun_frame_layout.f8_offset + cfun_frame_layout.high_fprs * 8 > 0)
10861     {
10862       offset = (cfun_frame_layout.f8_offset
10863                 + (cfun_frame_layout.high_fprs - 1) * 8);
10864
10865       for (i = FPR15_REGNUM; i >= FPR8_REGNUM && offset >= 0; i--)
10866         if (cfun_fpr_save_p (i))
10867           {
10868             insn = save_fpr (stack_pointer_rtx, offset, i);
10869
10870             RTX_FRAME_RELATED_P (insn) = 1;
10871             offset -= 8;
10872           }
10873       if (offset >= cfun_frame_layout.f8_offset)
10874         next_fpr = i;
10875     }
10876
10877   if (!TARGET_PACKED_STACK)
10878     next_fpr = cfun_save_high_fprs_p ? FPR15_REGNUM : 0;
10879
10880   if (flag_stack_usage_info)
10881     current_function_static_stack_size = cfun_frame_layout.frame_size;
10882
10883   /* Decrement stack pointer.  */
10884
10885   if (cfun_frame_layout.frame_size > 0)
10886     {
10887       rtx frame_off = GEN_INT (-cfun_frame_layout.frame_size);
10888       rtx real_frame_off;
10889
10890       if (s390_stack_size)
10891         {
10892           HOST_WIDE_INT stack_guard;
10893
10894           if (s390_stack_guard)
10895             stack_guard = s390_stack_guard;
10896           else
10897             {
10898               /* If no value for stack guard is provided the smallest power of 2
10899                  larger than the current frame size is chosen.  */
10900               stack_guard = 1;
10901               while (stack_guard < cfun_frame_layout.frame_size)
10902                 stack_guard <<= 1;
10903             }
10904
10905           if (cfun_frame_layout.frame_size >= s390_stack_size)
10906             {
10907               warning (0, "frame size of function %qs is %wd"
10908                        " bytes exceeding user provided stack limit of "
10909                        "%d bytes.  "
10910                        "An unconditional trap is added.",
10911                        current_function_name(), cfun_frame_layout.frame_size,
10912                        s390_stack_size);
10913               emit_insn (gen_trap ());
10914               emit_barrier ();
10915             }
10916           else
10917             {
10918               /* stack_guard has to be smaller than s390_stack_size.
10919                  Otherwise we would emit an AND with zero which would
10920                  not match the test under mask pattern.  */
10921               if (stack_guard >= s390_stack_size)
10922                 {
10923                   warning (0, "frame size of function %qs is %wd"
10924                            " bytes which is more than half the stack size. "
10925                            "The dynamic check would not be reliable. "
10926                            "No check emitted for this function.",
10927                            current_function_name(),
10928                            cfun_frame_layout.frame_size);
10929                 }
10930               else
10931                 {
10932                   HOST_WIDE_INT stack_check_mask = ((s390_stack_size - 1)
10933                                                     & ~(stack_guard - 1));
10934
10935                   rtx t = gen_rtx_AND (Pmode, stack_pointer_rtx,
10936                                        GEN_INT (stack_check_mask));
10937                   if (TARGET_64BIT)
10938                     emit_insn (gen_ctrapdi4 (gen_rtx_EQ (VOIDmode,
10939                                                          t, const0_rtx),
10940                                              t, const0_rtx, const0_rtx));
10941                   else
10942                     emit_insn (gen_ctrapsi4 (gen_rtx_EQ (VOIDmode,
10943                                                          t, const0_rtx),
10944                                              t, const0_rtx, const0_rtx));
10945                 }
10946             }
10947         }
10948
10949       if (s390_warn_framesize > 0
10950           && cfun_frame_layout.frame_size >= s390_warn_framesize)
10951         warning (0, "frame size of %qs is %wd bytes",
10952                  current_function_name (), cfun_frame_layout.frame_size);
10953
10954       if (s390_warn_dynamicstack_p && cfun->calls_alloca)
10955         warning (0, "%qs uses dynamic stack allocation", current_function_name ());
10956
10957       /* Save incoming stack pointer into temp reg.  */
10958       if (TARGET_BACKCHAIN || next_fpr)
10959         insn = emit_insn (gen_move_insn (temp_reg, stack_pointer_rtx));
10960
10961       /* Subtract frame size from stack pointer.  */
10962
10963       if (DISP_IN_RANGE (INTVAL (frame_off)))
10964         {
10965           insn = gen_rtx_SET (stack_pointer_rtx,
10966                               gen_rtx_PLUS (Pmode, stack_pointer_rtx,
10967                                             frame_off));
10968           insn = emit_insn (insn);
10969         }
10970       else
10971         {
10972           if (!CONST_OK_FOR_K (INTVAL (frame_off)))
10973             frame_off = force_const_mem (Pmode, frame_off);
10974
10975           insn = emit_insn (gen_add2_insn (stack_pointer_rtx, frame_off));
10976           annotate_constant_pool_refs (&PATTERN (insn));
10977         }
10978
10979       RTX_FRAME_RELATED_P (insn) = 1;
10980       real_frame_off = GEN_INT (-cfun_frame_layout.frame_size);
10981       add_reg_note (insn, REG_FRAME_RELATED_EXPR,
10982                     gen_rtx_SET (stack_pointer_rtx,
10983                                  gen_rtx_PLUS (Pmode, stack_pointer_rtx,
10984                                                real_frame_off)));
10985
10986       /* Set backchain.  */
10987
10988       if (TARGET_BACKCHAIN)
10989         {
10990           if (cfun_frame_layout.backchain_offset)
10991             addr = gen_rtx_MEM (Pmode,
10992                                 plus_constant (Pmode, stack_pointer_rtx,
10993                                   cfun_frame_layout.backchain_offset));
10994           else
10995             addr = gen_rtx_MEM (Pmode, stack_pointer_rtx);
10996           set_mem_alias_set (addr, get_frame_alias_set ());
10997           insn = emit_insn (gen_move_insn (addr, temp_reg));
10998         }
10999
11000       /* If we support non-call exceptions (e.g. for Java),
11001          we need to make sure the backchain pointer is set up
11002          before any possibly trapping memory access.  */
11003       if (TARGET_BACKCHAIN && cfun->can_throw_non_call_exceptions)
11004         {
11005           addr = gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (VOIDmode));
11006           emit_clobber (addr);
11007         }
11008     }
11009
11010   /* Save fprs 8 - 15 (64 bit ABI).  */
11011
11012   if (cfun_save_high_fprs_p && next_fpr)
11013     {
11014       /* If the stack might be accessed through a different register
11015          we have to make sure that the stack pointer decrement is not
11016          moved below the use of the stack slots.  */
11017       s390_emit_stack_tie ();
11018
11019       insn = emit_insn (gen_add2_insn (temp_reg,
11020                                        GEN_INT (cfun_frame_layout.f8_offset)));
11021
11022       offset = 0;
11023
11024       for (i = FPR8_REGNUM; i <= next_fpr; i++)
11025         if (cfun_fpr_save_p (i))
11026           {
11027             rtx addr = plus_constant (Pmode, stack_pointer_rtx,
11028                                       cfun_frame_layout.frame_size
11029                                       + cfun_frame_layout.f8_offset
11030                                       + offset);
11031
11032             insn = save_fpr (temp_reg, offset, i);
11033             offset += 8;
11034             RTX_FRAME_RELATED_P (insn) = 1;
11035             add_reg_note (insn, REG_FRAME_RELATED_EXPR,
11036                           gen_rtx_SET (gen_rtx_MEM (DFmode, addr),
11037                                        gen_rtx_REG (DFmode, i)));
11038           }
11039     }
11040
11041   /* Set frame pointer, if needed.  */
11042
11043   if (frame_pointer_needed)
11044     {
11045       insn = emit_move_insn (hard_frame_pointer_rtx, stack_pointer_rtx);
11046       RTX_FRAME_RELATED_P (insn) = 1;
11047     }
11048
11049   /* Set up got pointer, if needed.  */
11050
11051   if (flag_pic && df_regs_ever_live_p (PIC_OFFSET_TABLE_REGNUM))
11052     {
11053       rtx_insn *insns = s390_load_got ();
11054
11055       for (rtx_insn *insn = insns; insn; insn = NEXT_INSN (insn))
11056         annotate_constant_pool_refs (&PATTERN (insn));
11057
11058       emit_insn (insns);
11059     }
11060
11061   if (TARGET_TPF_PROFILING)
11062     {
11063       /* Generate a BAS instruction to serve as a function
11064          entry intercept to facilitate the use of tracing
11065          algorithms located at the branch target.  */
11066       emit_insn (gen_prologue_tpf ());
11067
11068       /* Emit a blockage here so that all code
11069          lies between the profiling mechanisms.  */
11070       emit_insn (gen_blockage ());
11071     }
11072 }
11073
11074 /* Expand the epilogue into a bunch of separate insns.  */
11075
11076 void
11077 s390_emit_epilogue (bool sibcall)
11078 {
11079   rtx frame_pointer, return_reg, cfa_restores = NULL_RTX;
11080   int area_bottom, area_top, offset = 0;
11081   int next_offset;
11082   rtvec p;
11083   int i;
11084
11085   if (TARGET_TPF_PROFILING)
11086     {
11087
11088       /* Generate a BAS instruction to serve as a function
11089          entry intercept to facilitate the use of tracing
11090          algorithms located at the branch target.  */
11091
11092       /* Emit a blockage here so that all code
11093          lies between the profiling mechanisms.  */
11094       emit_insn (gen_blockage ());
11095
11096       emit_insn (gen_epilogue_tpf ());
11097     }
11098
11099   /* Check whether to use frame or stack pointer for restore.  */
11100
11101   frame_pointer = (frame_pointer_needed
11102                    ? hard_frame_pointer_rtx : stack_pointer_rtx);
11103
11104   s390_frame_area (&area_bottom, &area_top);
11105
11106   /* Check whether we can access the register save area.
11107      If not, increment the frame pointer as required.  */
11108
11109   if (area_top <= area_bottom)
11110     {
11111       /* Nothing to restore.  */
11112     }
11113   else if (DISP_IN_RANGE (cfun_frame_layout.frame_size + area_bottom)
11114            && DISP_IN_RANGE (cfun_frame_layout.frame_size + area_top - 1))
11115     {
11116       /* Area is in range.  */
11117       offset = cfun_frame_layout.frame_size;
11118     }
11119   else
11120     {
11121       rtx insn, frame_off, cfa;
11122
11123       offset = area_bottom < 0 ? -area_bottom : 0;
11124       frame_off = GEN_INT (cfun_frame_layout.frame_size - offset);
11125
11126       cfa = gen_rtx_SET (frame_pointer,
11127                          gen_rtx_PLUS (Pmode, frame_pointer, frame_off));
11128       if (DISP_IN_RANGE (INTVAL (frame_off)))
11129         {
11130           insn = gen_rtx_SET (frame_pointer,
11131                               gen_rtx_PLUS (Pmode, frame_pointer, frame_off));
11132           insn = emit_insn (insn);
11133         }
11134       else
11135         {
11136           if (!CONST_OK_FOR_K (INTVAL (frame_off)))
11137             frame_off = force_const_mem (Pmode, frame_off);
11138
11139           insn = emit_insn (gen_add2_insn (frame_pointer, frame_off));
11140           annotate_constant_pool_refs (&PATTERN (insn));
11141         }
11142       add_reg_note (insn, REG_CFA_ADJUST_CFA, cfa);
11143       RTX_FRAME_RELATED_P (insn) = 1;
11144     }
11145
11146   /* Restore call saved fprs.  */
11147
11148   if (TARGET_64BIT)
11149     {
11150       if (cfun_save_high_fprs_p)
11151         {
11152           next_offset = cfun_frame_layout.f8_offset;
11153           for (i = FPR8_REGNUM; i <= FPR15_REGNUM; i++)
11154             {
11155               if (cfun_fpr_save_p (i))
11156                 {
11157                   restore_fpr (frame_pointer,
11158                                offset + next_offset, i);
11159                   cfa_restores
11160                     = alloc_reg_note (REG_CFA_RESTORE,
11161                                       gen_rtx_REG (DFmode, i), cfa_restores);
11162                   next_offset += 8;
11163                 }
11164             }
11165         }
11166
11167     }
11168   else
11169     {
11170       next_offset = cfun_frame_layout.f4_offset;
11171       /* f4, f6 */
11172       for (i = FPR4_REGNUM; i <= FPR4_REGNUM + 1; i++)
11173         {
11174           if (cfun_fpr_save_p (i))
11175             {
11176               restore_fpr (frame_pointer,
11177                            offset + next_offset, i);
11178               cfa_restores
11179                 = alloc_reg_note (REG_CFA_RESTORE,
11180                                   gen_rtx_REG (DFmode, i), cfa_restores);
11181               next_offset += 8;
11182             }
11183           else if (!TARGET_PACKED_STACK)
11184             next_offset += 8;
11185         }
11186
11187     }
11188
11189   /* Return register.  */
11190
11191   return_reg = gen_rtx_REG (Pmode, RETURN_REGNUM);
11192
11193   /* Restore call saved gprs.  */
11194
11195   if (cfun_frame_layout.first_restore_gpr != -1)
11196     {
11197       rtx insn, addr;
11198       int i;
11199
11200       /* Check for global register and save them
11201          to stack location from where they get restored.  */
11202
11203       for (i = cfun_frame_layout.first_restore_gpr;
11204            i <= cfun_frame_layout.last_restore_gpr;
11205            i++)
11206         {
11207           if (global_not_special_regno_p (i))
11208             {
11209               addr = plus_constant (Pmode, frame_pointer,
11210                                     offset + cfun_frame_layout.gprs_offset
11211                                     + (i - cfun_frame_layout.first_save_gpr_slot)
11212                                     * UNITS_PER_LONG);
11213               addr = gen_rtx_MEM (Pmode, addr);
11214               set_mem_alias_set (addr, get_frame_alias_set ());
11215               emit_move_insn (addr, gen_rtx_REG (Pmode, i));
11216             }
11217           else
11218             cfa_restores
11219               = alloc_reg_note (REG_CFA_RESTORE,
11220                                 gen_rtx_REG (Pmode, i), cfa_restores);
11221         }
11222
11223       if (! sibcall)
11224         {
11225           /* Fetch return address from stack before load multiple,
11226              this will do good for scheduling.
11227
11228              Only do this if we already decided that r14 needs to be
11229              saved to a stack slot. (And not just because r14 happens to
11230              be in between two GPRs which need saving.)  Otherwise it
11231              would be difficult to take that decision back in
11232              s390_optimize_prologue.  */
11233           if (cfun_gpr_save_slot (RETURN_REGNUM) == SAVE_SLOT_STACK)
11234             {
11235               int return_regnum = find_unused_clobbered_reg();
11236               if (!return_regnum)
11237                 return_regnum = 4;
11238               return_reg = gen_rtx_REG (Pmode, return_regnum);
11239
11240               addr = plus_constant (Pmode, frame_pointer,
11241                                     offset + cfun_frame_layout.gprs_offset
11242                                     + (RETURN_REGNUM
11243                                        - cfun_frame_layout.first_save_gpr_slot)
11244                                     * UNITS_PER_LONG);
11245               addr = gen_rtx_MEM (Pmode, addr);
11246               set_mem_alias_set (addr, get_frame_alias_set ());
11247               emit_move_insn (return_reg, addr);
11248
11249               /* Once we did that optimization we have to make sure
11250                  s390_optimize_prologue does not try to remove the
11251                  store of r14 since we will not be able to find the
11252                  load issued here.  */
11253               cfun_frame_layout.save_return_addr_p = true;
11254             }
11255         }
11256
11257       insn = restore_gprs (frame_pointer,
11258                            offset + cfun_frame_layout.gprs_offset
11259                            + (cfun_frame_layout.first_restore_gpr
11260                               - cfun_frame_layout.first_save_gpr_slot)
11261                            * UNITS_PER_LONG,
11262                            cfun_frame_layout.first_restore_gpr,
11263                            cfun_frame_layout.last_restore_gpr);
11264       insn = emit_insn (insn);
11265       REG_NOTES (insn) = cfa_restores;
11266       add_reg_note (insn, REG_CFA_DEF_CFA,
11267                     plus_constant (Pmode, stack_pointer_rtx,
11268                                    STACK_POINTER_OFFSET));
11269       RTX_FRAME_RELATED_P (insn) = 1;
11270     }
11271
11272   s390_restore_gprs_from_fprs ();
11273
11274   if (! sibcall)
11275     {
11276
11277       /* Return to caller.  */
11278
11279       p = rtvec_alloc (2);
11280
11281       RTVEC_ELT (p, 0) = ret_rtx;
11282       RTVEC_ELT (p, 1) = gen_rtx_USE (VOIDmode, return_reg);
11283       emit_jump_insn (gen_rtx_PARALLEL (VOIDmode, p));
11284     }
11285 }
11286
11287 /* Implement TARGET_SET_UP_BY_PROLOGUE.  */
11288
11289 static void
11290 s300_set_up_by_prologue (hard_reg_set_container *regs)
11291 {
11292   if (cfun->machine->base_reg
11293       && !call_really_used_regs[REGNO (cfun->machine->base_reg)])
11294     SET_HARD_REG_BIT (regs->set, REGNO (cfun->machine->base_reg));
11295 }
11296
11297 /* -fsplit-stack support.  */
11298
11299 /* A SYMBOL_REF for __morestack.  */
11300 static GTY(()) rtx morestack_ref;
11301
11302 /* When using -fsplit-stack, the allocation routines set a field in
11303    the TCB to the bottom of the stack plus this much space, measured
11304    in bytes.  */
11305
11306 #define SPLIT_STACK_AVAILABLE 1024
11307
11308 /* Emit -fsplit-stack prologue, which goes before the regular function
11309    prologue.  */
11310
11311 void
11312 s390_expand_split_stack_prologue (void)
11313 {
11314   rtx r1, guard, cc = NULL;
11315   rtx_insn *insn;
11316   /* Offset from thread pointer to __private_ss.  */
11317   int psso = TARGET_64BIT ? 0x38 : 0x20;
11318   /* Pointer size in bytes.  */
11319   /* Frame size and argument size - the two parameters to __morestack.  */
11320   HOST_WIDE_INT frame_size = cfun_frame_layout.frame_size;
11321   /* Align argument size to 8 bytes - simplifies __morestack code.  */
11322   HOST_WIDE_INT args_size = crtl->args.size >= 0
11323                             ? ((crtl->args.size + 7) & ~7)
11324                             : 0;
11325   /* Label to be called by __morestack.  */
11326   rtx_code_label *call_done = NULL;
11327   rtx_code_label *parm_base = NULL;
11328   rtx tmp;
11329
11330   gcc_assert (flag_split_stack && reload_completed);
11331   if (!TARGET_CPU_ZARCH)
11332     {
11333       sorry ("CPUs older than z900 are not supported for -fsplit-stack");
11334       return;
11335     }
11336
11337   r1 = gen_rtx_REG (Pmode, 1);
11338
11339   /* If no stack frame will be allocated, don't do anything.  */
11340   if (!frame_size)
11341     {
11342       if (cfun->machine->split_stack_varargs_pointer != NULL_RTX)
11343         {
11344           /* If va_start is used, just use r15.  */
11345           emit_move_insn (r1,
11346                          gen_rtx_PLUS (Pmode, stack_pointer_rtx,
11347                                        GEN_INT (STACK_POINTER_OFFSET)));
11348
11349         }
11350       return;
11351     }
11352
11353   if (morestack_ref == NULL_RTX)
11354     {
11355       morestack_ref = gen_rtx_SYMBOL_REF (Pmode, "__morestack");
11356       SYMBOL_REF_FLAGS (morestack_ref) |= (SYMBOL_FLAG_LOCAL
11357                                            | SYMBOL_FLAG_FUNCTION);
11358     }
11359
11360   if (CONST_OK_FOR_K (frame_size) || CONST_OK_FOR_Op (frame_size))
11361     {
11362       /* If frame_size will fit in an add instruction, do a stack space
11363          check, and only call __morestack if there's not enough space.  */
11364
11365       /* Get thread pointer.  r1 is the only register we can always destroy - r0
11366          could contain a static chain (and cannot be used to address memory
11367          anyway), r2-r6 can contain parameters, and r6-r15 are callee-saved.  */
11368       emit_move_insn (r1, gen_rtx_REG (Pmode, TP_REGNUM));
11369       /* Aim at __private_ss.  */
11370       guard = gen_rtx_MEM (Pmode, plus_constant (Pmode, r1, psso));
11371
11372       /* If less that 1kiB used, skip addition and compare directly with
11373          __private_ss.  */
11374       if (frame_size > SPLIT_STACK_AVAILABLE)
11375         {
11376           emit_move_insn (r1, guard);
11377           if (TARGET_64BIT)
11378             emit_insn (gen_adddi3 (r1, r1, GEN_INT (frame_size)));
11379           else
11380             emit_insn (gen_addsi3 (r1, r1, GEN_INT (frame_size)));
11381           guard = r1;
11382         }
11383
11384       /* Compare the (maybe adjusted) guard with the stack pointer.  */
11385       cc = s390_emit_compare (LT, stack_pointer_rtx, guard);
11386     }
11387
11388   call_done = gen_label_rtx ();
11389   parm_base = gen_label_rtx ();
11390
11391   /* Emit the parameter block.  */
11392   tmp = gen_split_stack_data (parm_base, call_done,
11393                               GEN_INT (frame_size),
11394                               GEN_INT (args_size));
11395   insn = emit_insn (tmp);
11396   add_reg_note (insn, REG_LABEL_OPERAND, call_done);
11397   LABEL_NUSES (call_done)++;
11398   add_reg_note (insn, REG_LABEL_OPERAND, parm_base);
11399   LABEL_NUSES (parm_base)++;
11400
11401   /* %r1 = litbase.  */
11402   insn = emit_move_insn (r1, gen_rtx_LABEL_REF (VOIDmode, parm_base));
11403   add_reg_note (insn, REG_LABEL_OPERAND, parm_base);
11404   LABEL_NUSES (parm_base)++;
11405
11406   /* Now, we need to call __morestack.  It has very special calling
11407      conventions: it preserves param/return/static chain registers for
11408      calling main function body, and looks for its own parameters at %r1. */
11409
11410   if (cc != NULL)
11411     {
11412       tmp = gen_split_stack_cond_call (morestack_ref, cc, call_done);
11413
11414       insn = emit_jump_insn (tmp);
11415       JUMP_LABEL (insn) = call_done;
11416       LABEL_NUSES (call_done)++;
11417
11418       /* Mark the jump as very unlikely to be taken.  */
11419       add_int_reg_note (insn, REG_BR_PROB, REG_BR_PROB_BASE / 100);
11420
11421       if (cfun->machine->split_stack_varargs_pointer != NULL_RTX)
11422         {
11423           /* If va_start is used, and __morestack was not called, just use
11424              r15.  */
11425           emit_move_insn (r1,
11426                          gen_rtx_PLUS (Pmode, stack_pointer_rtx,
11427                                        GEN_INT (STACK_POINTER_OFFSET)));
11428         }
11429     }
11430   else
11431     {
11432       tmp = gen_split_stack_call (morestack_ref, call_done);
11433       insn = emit_jump_insn (tmp);
11434       JUMP_LABEL (insn) = call_done;
11435       LABEL_NUSES (call_done)++;
11436       emit_barrier ();
11437     }
11438
11439   /* __morestack will call us here.  */
11440
11441   emit_label (call_done);
11442 }
11443
11444 /* We may have to tell the dataflow pass that the split stack prologue
11445    is initializing a register.  */
11446
11447 static void
11448 s390_live_on_entry (bitmap regs)
11449 {
11450   if (cfun->machine->split_stack_varargs_pointer != NULL_RTX)
11451     {
11452       gcc_assert (flag_split_stack);
11453       bitmap_set_bit (regs, 1);
11454     }
11455 }
11456
11457 /* Return true if the function can use simple_return to return outside
11458    of a shrink-wrapped region.  At present shrink-wrapping is supported
11459    in all cases.  */
11460
11461 bool
11462 s390_can_use_simple_return_insn (void)
11463 {
11464   return true;
11465 }
11466
11467 /* Return true if the epilogue is guaranteed to contain only a return
11468    instruction and if a direct return can therefore be used instead.
11469    One of the main advantages of using direct return instructions
11470    is that we can then use conditional returns.  */
11471
11472 bool
11473 s390_can_use_return_insn (void)
11474 {
11475   int i;
11476
11477   if (!reload_completed)
11478     return false;
11479
11480   if (crtl->profile)
11481     return false;
11482
11483   if (TARGET_TPF_PROFILING)
11484     return false;
11485
11486   for (i = 0; i < 16; i++)
11487     if (cfun_gpr_save_slot (i) != SAVE_SLOT_NONE)
11488       return false;
11489
11490   /* For 31 bit this is not covered by the frame_size check below
11491      since f4, f6 are saved in the register save area without needing
11492      additional stack space.  */
11493   if (!TARGET_64BIT
11494       && (cfun_fpr_save_p (FPR4_REGNUM) || cfun_fpr_save_p (FPR6_REGNUM)))
11495     return false;
11496
11497   if (cfun->machine->base_reg
11498       && !call_really_used_regs[REGNO (cfun->machine->base_reg)])
11499     return false;
11500
11501   return cfun_frame_layout.frame_size == 0;
11502 }
11503
11504 /* The VX ABI differs for vararg functions.  Therefore we need the
11505    prototype of the callee to be available when passing vector type
11506    values.  */
11507 static const char *
11508 s390_invalid_arg_for_unprototyped_fn (const_tree typelist, const_tree funcdecl, const_tree val)
11509 {
11510   return ((TARGET_VX_ABI
11511            && typelist == 0
11512            && VECTOR_TYPE_P (TREE_TYPE (val))
11513            && (funcdecl == NULL_TREE
11514                || (TREE_CODE (funcdecl) == FUNCTION_DECL
11515                    && DECL_BUILT_IN_CLASS (funcdecl) != BUILT_IN_MD)))
11516           ? N_("vector argument passed to unprototyped function")
11517           : NULL);
11518 }
11519
11520
11521 /* Return the size in bytes of a function argument of
11522    type TYPE and/or mode MODE.  At least one of TYPE or
11523    MODE must be specified.  */
11524
11525 static int
11526 s390_function_arg_size (machine_mode mode, const_tree type)
11527 {
11528   if (type)
11529     return int_size_in_bytes (type);
11530
11531   /* No type info available for some library calls ...  */
11532   if (mode != BLKmode)
11533     return GET_MODE_SIZE (mode);
11534
11535   /* If we have neither type nor mode, abort */
11536   gcc_unreachable ();
11537 }
11538
11539 /* Return true if a function argument of type TYPE and mode MODE
11540    is to be passed in a vector register, if available.  */
11541
11542 bool
11543 s390_function_arg_vector (machine_mode mode, const_tree type)
11544 {
11545   if (!TARGET_VX_ABI)
11546     return false;
11547
11548   if (s390_function_arg_size (mode, type) > 16)
11549     return false;
11550
11551   /* No type info available for some library calls ...  */
11552   if (!type)
11553     return VECTOR_MODE_P (mode);
11554
11555   /* The ABI says that record types with a single member are treated
11556      just like that member would be.  */
11557   while (TREE_CODE (type) == RECORD_TYPE)
11558     {
11559       tree field, single = NULL_TREE;
11560
11561       for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
11562         {
11563           if (TREE_CODE (field) != FIELD_DECL)
11564             continue;
11565
11566           if (single == NULL_TREE)
11567             single = TREE_TYPE (field);
11568           else
11569             return false;
11570         }
11571
11572       if (single == NULL_TREE)
11573         return false;
11574       else
11575         {
11576           /* If the field declaration adds extra byte due to
11577              e.g. padding this is not accepted as vector type.  */
11578           if (int_size_in_bytes (single) <= 0
11579               || int_size_in_bytes (single) != int_size_in_bytes (type))
11580             return false;
11581           type = single;
11582         }
11583     }
11584
11585   return VECTOR_TYPE_P (type);
11586 }
11587
11588 /* Return true if a function argument of type TYPE and mode MODE
11589    is to be passed in a floating-point register, if available.  */
11590
11591 static bool
11592 s390_function_arg_float (machine_mode mode, const_tree type)
11593 {
11594   if (s390_function_arg_size (mode, type) > 8)
11595     return false;
11596
11597   /* Soft-float changes the ABI: no floating-point registers are used.  */
11598   if (TARGET_SOFT_FLOAT)
11599     return false;
11600
11601   /* No type info available for some library calls ...  */
11602   if (!type)
11603     return mode == SFmode || mode == DFmode || mode == SDmode || mode == DDmode;
11604
11605   /* The ABI says that record types with a single member are treated
11606      just like that member would be.  */
11607   while (TREE_CODE (type) == RECORD_TYPE)
11608     {
11609       tree field, single = NULL_TREE;
11610
11611       for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
11612         {
11613           if (TREE_CODE (field) != FIELD_DECL)
11614             continue;
11615
11616           if (single == NULL_TREE)
11617             single = TREE_TYPE (field);
11618           else
11619             return false;
11620         }
11621
11622       if (single == NULL_TREE)
11623         return false;
11624       else
11625         type = single;
11626     }
11627
11628   return TREE_CODE (type) == REAL_TYPE;
11629 }
11630
11631 /* Return true if a function argument of type TYPE and mode MODE
11632    is to be passed in an integer register, or a pair of integer
11633    registers, if available.  */
11634
11635 static bool
11636 s390_function_arg_integer (machine_mode mode, const_tree type)
11637 {
11638   int size = s390_function_arg_size (mode, type);
11639   if (size > 8)
11640     return false;
11641
11642   /* No type info available for some library calls ...  */
11643   if (!type)
11644     return GET_MODE_CLASS (mode) == MODE_INT
11645            || (TARGET_SOFT_FLOAT &&  SCALAR_FLOAT_MODE_P (mode));
11646
11647   /* We accept small integral (and similar) types.  */
11648   if (INTEGRAL_TYPE_P (type)
11649       || POINTER_TYPE_P (type)
11650       || TREE_CODE (type) == NULLPTR_TYPE
11651       || TREE_CODE (type) == OFFSET_TYPE
11652       || (TARGET_SOFT_FLOAT && TREE_CODE (type) == REAL_TYPE))
11653     return true;
11654
11655   /* We also accept structs of size 1, 2, 4, 8 that are not
11656      passed in floating-point registers.  */
11657   if (AGGREGATE_TYPE_P (type)
11658       && exact_log2 (size) >= 0
11659       && !s390_function_arg_float (mode, type))
11660     return true;
11661
11662   return false;
11663 }
11664
11665 /* Return 1 if a function argument of type TYPE and mode MODE
11666    is to be passed by reference.  The ABI specifies that only
11667    structures of size 1, 2, 4, or 8 bytes are passed by value,
11668    all other structures (and complex numbers) are passed by
11669    reference.  */
11670
11671 static bool
11672 s390_pass_by_reference (cumulative_args_t ca ATTRIBUTE_UNUSED,
11673                         machine_mode mode, const_tree type,
11674                         bool named ATTRIBUTE_UNUSED)
11675 {
11676   int size = s390_function_arg_size (mode, type);
11677
11678   if (s390_function_arg_vector (mode, type))
11679     return false;
11680
11681   if (size > 8)
11682     return true;
11683
11684   if (type)
11685     {
11686       if (AGGREGATE_TYPE_P (type) && exact_log2 (size) < 0)
11687         return true;
11688
11689       if (TREE_CODE (type) == COMPLEX_TYPE
11690           || TREE_CODE (type) == VECTOR_TYPE)
11691         return true;
11692     }
11693
11694   return false;
11695 }
11696
11697 /* Update the data in CUM to advance over an argument of mode MODE and
11698    data type TYPE.  (TYPE is null for libcalls where that information
11699    may not be available.).  The boolean NAMED specifies whether the
11700    argument is a named argument (as opposed to an unnamed argument
11701    matching an ellipsis).  */
11702
11703 static void
11704 s390_function_arg_advance (cumulative_args_t cum_v, machine_mode mode,
11705                            const_tree type, bool named)
11706 {
11707   CUMULATIVE_ARGS *cum = get_cumulative_args (cum_v);
11708
11709   if (s390_function_arg_vector (mode, type))
11710     {
11711       /* We are called for unnamed vector stdarg arguments which are
11712          passed on the stack.  In this case this hook does not have to
11713          do anything since stack arguments are tracked by common
11714          code.  */
11715       if (!named)
11716         return;
11717       cum->vrs += 1;
11718     }
11719   else if (s390_function_arg_float (mode, type))
11720     {
11721       cum->fprs += 1;
11722     }
11723   else if (s390_function_arg_integer (mode, type))
11724     {
11725       int size = s390_function_arg_size (mode, type);
11726       cum->gprs += ((size + UNITS_PER_LONG - 1) / UNITS_PER_LONG);
11727     }
11728   else
11729     gcc_unreachable ();
11730 }
11731
11732 /* Define where to put the arguments to a function.
11733    Value is zero to push the argument on the stack,
11734    or a hard register in which to store the argument.
11735
11736    MODE is the argument's machine mode.
11737    TYPE is the data type of the argument (as a tree).
11738     This is null for libcalls where that information may
11739     not be available.
11740    CUM is a variable of type CUMULATIVE_ARGS which gives info about
11741     the preceding args and about the function being called.
11742    NAMED is nonzero if this argument is a named parameter
11743     (otherwise it is an extra parameter matching an ellipsis).
11744
11745    On S/390, we use general purpose registers 2 through 6 to
11746    pass integer, pointer, and certain structure arguments, and
11747    floating point registers 0 and 2 (0, 2, 4, and 6 on 64-bit)
11748    to pass floating point arguments.  All remaining arguments
11749    are pushed to the stack.  */
11750
11751 static rtx
11752 s390_function_arg (cumulative_args_t cum_v, machine_mode mode,
11753                    const_tree type, bool named)
11754 {
11755   CUMULATIVE_ARGS *cum = get_cumulative_args (cum_v);
11756
11757   if (!named)
11758     s390_check_type_for_vector_abi (type, true, false);
11759
11760   if (s390_function_arg_vector (mode, type))
11761     {
11762       /* Vector arguments being part of the ellipsis are passed on the
11763          stack.  */
11764       if (!named || (cum->vrs + 1 > VEC_ARG_NUM_REG))
11765         return NULL_RTX;
11766
11767       return gen_rtx_REG (mode, cum->vrs + FIRST_VEC_ARG_REGNO);
11768     }
11769   else if (s390_function_arg_float (mode, type))
11770     {
11771       if (cum->fprs + 1 > FP_ARG_NUM_REG)
11772         return NULL_RTX;
11773       else
11774         return gen_rtx_REG (mode, cum->fprs + 16);
11775     }
11776   else if (s390_function_arg_integer (mode, type))
11777     {
11778       int size = s390_function_arg_size (mode, type);
11779       int n_gprs = (size + UNITS_PER_LONG - 1) / UNITS_PER_LONG;
11780
11781       if (cum->gprs + n_gprs > GP_ARG_NUM_REG)
11782         return NULL_RTX;
11783       else if (n_gprs == 1 || UNITS_PER_WORD == UNITS_PER_LONG)
11784         return gen_rtx_REG (mode, cum->gprs + 2);
11785       else if (n_gprs == 2)
11786         {
11787           rtvec p = rtvec_alloc (2);
11788
11789           RTVEC_ELT (p, 0)
11790             = gen_rtx_EXPR_LIST (SImode, gen_rtx_REG (SImode, cum->gprs + 2),
11791                                          const0_rtx);
11792           RTVEC_ELT (p, 1)
11793             = gen_rtx_EXPR_LIST (SImode, gen_rtx_REG (SImode, cum->gprs + 3),
11794                                          GEN_INT (4));
11795
11796           return gen_rtx_PARALLEL (mode, p);
11797         }
11798     }
11799
11800   /* After the real arguments, expand_call calls us once again
11801      with a void_type_node type.  Whatever we return here is
11802      passed as operand 2 to the call expanders.
11803
11804      We don't need this feature ...  */
11805   else if (type == void_type_node)
11806     return const0_rtx;
11807
11808   gcc_unreachable ();
11809 }
11810
11811 /* Return true if return values of type TYPE should be returned
11812    in a memory buffer whose address is passed by the caller as
11813    hidden first argument.  */
11814
11815 static bool
11816 s390_return_in_memory (const_tree type, const_tree fundecl ATTRIBUTE_UNUSED)
11817 {
11818   /* We accept small integral (and similar) types.  */
11819   if (INTEGRAL_TYPE_P (type)
11820       || POINTER_TYPE_P (type)
11821       || TREE_CODE (type) == OFFSET_TYPE
11822       || TREE_CODE (type) == REAL_TYPE)
11823     return int_size_in_bytes (type) > 8;
11824
11825   /* vector types which fit into a VR.  */
11826   if (TARGET_VX_ABI
11827       && VECTOR_TYPE_P (type)
11828       && int_size_in_bytes (type) <= 16)
11829     return false;
11830
11831   /* Aggregates and similar constructs are always returned
11832      in memory.  */
11833   if (AGGREGATE_TYPE_P (type)
11834       || TREE_CODE (type) == COMPLEX_TYPE
11835       || VECTOR_TYPE_P (type))
11836     return true;
11837
11838   /* ??? We get called on all sorts of random stuff from
11839      aggregate_value_p.  We can't abort, but it's not clear
11840      what's safe to return.  Pretend it's a struct I guess.  */
11841   return true;
11842 }
11843
11844 /* Function arguments and return values are promoted to word size.  */
11845
11846 static machine_mode
11847 s390_promote_function_mode (const_tree type, machine_mode mode,
11848                             int *punsignedp,
11849                             const_tree fntype ATTRIBUTE_UNUSED,
11850                             int for_return ATTRIBUTE_UNUSED)
11851 {
11852   if (INTEGRAL_MODE_P (mode)
11853       && GET_MODE_SIZE (mode) < UNITS_PER_LONG)
11854     {
11855       if (type != NULL_TREE && POINTER_TYPE_P (type))
11856         *punsignedp = POINTERS_EXTEND_UNSIGNED;
11857       return Pmode;
11858     }
11859
11860   return mode;
11861 }
11862
11863 /* Define where to return a (scalar) value of type RET_TYPE.
11864    If RET_TYPE is null, define where to return a (scalar)
11865    value of mode MODE from a libcall.  */
11866
11867 static rtx
11868 s390_function_and_libcall_value (machine_mode mode,
11869                                  const_tree ret_type,
11870                                  const_tree fntype_or_decl,
11871                                  bool outgoing ATTRIBUTE_UNUSED)
11872 {
11873   /* For vector return types it is important to use the RET_TYPE
11874      argument whenever available since the middle-end might have
11875      changed the mode to a scalar mode.  */
11876   bool vector_ret_type_p = ((ret_type && VECTOR_TYPE_P (ret_type))
11877                             || (!ret_type && VECTOR_MODE_P (mode)));
11878
11879   /* For normal functions perform the promotion as
11880      promote_function_mode would do.  */
11881   if (ret_type)
11882     {
11883       int unsignedp = TYPE_UNSIGNED (ret_type);
11884       mode = promote_function_mode (ret_type, mode, &unsignedp,
11885                                     fntype_or_decl, 1);
11886     }
11887
11888   gcc_assert (GET_MODE_CLASS (mode) == MODE_INT
11889               || SCALAR_FLOAT_MODE_P (mode)
11890               || (TARGET_VX_ABI && vector_ret_type_p));
11891   gcc_assert (GET_MODE_SIZE (mode) <= (TARGET_VX_ABI ? 16 : 8));
11892
11893   if (TARGET_VX_ABI && vector_ret_type_p)
11894     return gen_rtx_REG (mode, FIRST_VEC_ARG_REGNO);
11895   else if (TARGET_HARD_FLOAT && SCALAR_FLOAT_MODE_P (mode))
11896     return gen_rtx_REG (mode, 16);
11897   else if (GET_MODE_SIZE (mode) <= UNITS_PER_LONG
11898            || UNITS_PER_LONG == UNITS_PER_WORD)
11899     return gen_rtx_REG (mode, 2);
11900   else if (GET_MODE_SIZE (mode) == 2 * UNITS_PER_LONG)
11901     {
11902       /* This case is triggered when returning a 64 bit value with
11903          -m31 -mzarch.  Although the value would fit into a single
11904          register it has to be forced into a 32 bit register pair in
11905          order to match the ABI.  */
11906       rtvec p = rtvec_alloc (2);
11907
11908       RTVEC_ELT (p, 0)
11909         = gen_rtx_EXPR_LIST (SImode, gen_rtx_REG (SImode, 2), const0_rtx);
11910       RTVEC_ELT (p, 1)
11911         = gen_rtx_EXPR_LIST (SImode, gen_rtx_REG (SImode, 3), GEN_INT (4));
11912
11913       return gen_rtx_PARALLEL (mode, p);
11914     }
11915
11916   gcc_unreachable ();
11917 }
11918
11919 /* Define where to return a scalar return value of type RET_TYPE.  */
11920
11921 static rtx
11922 s390_function_value (const_tree ret_type, const_tree fn_decl_or_type,
11923                      bool outgoing)
11924 {
11925   return s390_function_and_libcall_value (TYPE_MODE (ret_type), ret_type,
11926                                           fn_decl_or_type, outgoing);
11927 }
11928
11929 /* Define where to return a scalar libcall return value of mode
11930    MODE.  */
11931
11932 static rtx
11933 s390_libcall_value (machine_mode mode, const_rtx fun ATTRIBUTE_UNUSED)
11934 {
11935   return s390_function_and_libcall_value (mode, NULL_TREE,
11936                                           NULL_TREE, true);
11937 }
11938
11939
11940 /* Create and return the va_list datatype.
11941
11942    On S/390, va_list is an array type equivalent to
11943
11944       typedef struct __va_list_tag
11945         {
11946             long __gpr;
11947             long __fpr;
11948             void *__overflow_arg_area;
11949             void *__reg_save_area;
11950         } va_list[1];
11951
11952    where __gpr and __fpr hold the number of general purpose
11953    or floating point arguments used up to now, respectively,
11954    __overflow_arg_area points to the stack location of the
11955    next argument passed on the stack, and __reg_save_area
11956    always points to the start of the register area in the
11957    call frame of the current function.  The function prologue
11958    saves all registers used for argument passing into this
11959    area if the function uses variable arguments.  */
11960
11961 static tree
11962 s390_build_builtin_va_list (void)
11963 {
11964   tree f_gpr, f_fpr, f_ovf, f_sav, record, type_decl;
11965
11966   record = lang_hooks.types.make_type (RECORD_TYPE);
11967
11968   type_decl =
11969     build_decl (BUILTINS_LOCATION,
11970                 TYPE_DECL, get_identifier ("__va_list_tag"), record);
11971
11972   f_gpr = build_decl (BUILTINS_LOCATION,
11973                       FIELD_DECL, get_identifier ("__gpr"),
11974                       long_integer_type_node);
11975   f_fpr = build_decl (BUILTINS_LOCATION,
11976                       FIELD_DECL, get_identifier ("__fpr"),
11977                       long_integer_type_node);
11978   f_ovf = build_decl (BUILTINS_LOCATION,
11979                       FIELD_DECL, get_identifier ("__overflow_arg_area"),
11980                       ptr_type_node);
11981   f_sav = build_decl (BUILTINS_LOCATION,
11982                       FIELD_DECL, get_identifier ("__reg_save_area"),
11983                       ptr_type_node);
11984
11985   va_list_gpr_counter_field = f_gpr;
11986   va_list_fpr_counter_field = f_fpr;
11987
11988   DECL_FIELD_CONTEXT (f_gpr) = record;
11989   DECL_FIELD_CONTEXT (f_fpr) = record;
11990   DECL_FIELD_CONTEXT (f_ovf) = record;
11991   DECL_FIELD_CONTEXT (f_sav) = record;
11992
11993   TYPE_STUB_DECL (record) = type_decl;
11994   TYPE_NAME (record) = type_decl;
11995   TYPE_FIELDS (record) = f_gpr;
11996   DECL_CHAIN (f_gpr) = f_fpr;
11997   DECL_CHAIN (f_fpr) = f_ovf;
11998   DECL_CHAIN (f_ovf) = f_sav;
11999
12000   layout_type (record);
12001
12002   /* The correct type is an array type of one element.  */
12003   return build_array_type (record, build_index_type (size_zero_node));
12004 }
12005
12006 /* Implement va_start by filling the va_list structure VALIST.
12007    STDARG_P is always true, and ignored.
12008    NEXTARG points to the first anonymous stack argument.
12009
12010    The following global variables are used to initialize
12011    the va_list structure:
12012
12013      crtl->args.info:
12014        holds number of gprs and fprs used for named arguments.
12015      crtl->args.arg_offset_rtx:
12016        holds the offset of the first anonymous stack argument
12017        (relative to the virtual arg pointer).  */
12018
12019 static void
12020 s390_va_start (tree valist, rtx nextarg ATTRIBUTE_UNUSED)
12021 {
12022   HOST_WIDE_INT n_gpr, n_fpr;
12023   int off;
12024   tree f_gpr, f_fpr, f_ovf, f_sav;
12025   tree gpr, fpr, ovf, sav, t;
12026
12027   f_gpr = TYPE_FIELDS (TREE_TYPE (va_list_type_node));
12028   f_fpr = DECL_CHAIN (f_gpr);
12029   f_ovf = DECL_CHAIN (f_fpr);
12030   f_sav = DECL_CHAIN (f_ovf);
12031
12032   valist = build_simple_mem_ref (valist);
12033   gpr = build3 (COMPONENT_REF, TREE_TYPE (f_gpr), valist, f_gpr, NULL_TREE);
12034   fpr = build3 (COMPONENT_REF, TREE_TYPE (f_fpr), valist, f_fpr, NULL_TREE);
12035   ovf = build3 (COMPONENT_REF, TREE_TYPE (f_ovf), valist, f_ovf, NULL_TREE);
12036   sav = build3 (COMPONENT_REF, TREE_TYPE (f_sav), valist, f_sav, NULL_TREE);
12037
12038   /* Count number of gp and fp argument registers used.  */
12039
12040   n_gpr = crtl->args.info.gprs;
12041   n_fpr = crtl->args.info.fprs;
12042
12043   if (cfun->va_list_gpr_size)
12044     {
12045       t = build2 (MODIFY_EXPR, TREE_TYPE (gpr), gpr,
12046                   build_int_cst (NULL_TREE, n_gpr));
12047       TREE_SIDE_EFFECTS (t) = 1;
12048       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
12049     }
12050
12051   if (cfun->va_list_fpr_size)
12052     {
12053       t = build2 (MODIFY_EXPR, TREE_TYPE (fpr), fpr,
12054                   build_int_cst (NULL_TREE, n_fpr));
12055       TREE_SIDE_EFFECTS (t) = 1;
12056       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
12057     }
12058
12059   if (flag_split_stack
12060      && (lookup_attribute ("no_split_stack", DECL_ATTRIBUTES (cfun->decl))
12061          == NULL)
12062      && cfun->machine->split_stack_varargs_pointer == NULL_RTX)
12063     {
12064       rtx reg;
12065       rtx_insn *seq;
12066
12067       reg = gen_reg_rtx (Pmode);
12068       cfun->machine->split_stack_varargs_pointer = reg;
12069
12070       start_sequence ();
12071       emit_move_insn (reg, gen_rtx_REG (Pmode, 1));
12072       seq = get_insns ();
12073       end_sequence ();
12074
12075       push_topmost_sequence ();
12076       emit_insn_after (seq, entry_of_function ());
12077       pop_topmost_sequence ();
12078     }
12079
12080   /* Find the overflow area.
12081      FIXME: This currently is too pessimistic when the vector ABI is
12082      enabled.  In that case we *always* set up the overflow area
12083      pointer.  */
12084   if (n_gpr + cfun->va_list_gpr_size > GP_ARG_NUM_REG
12085       || n_fpr + cfun->va_list_fpr_size > FP_ARG_NUM_REG
12086       || TARGET_VX_ABI)
12087     {
12088       if (cfun->machine->split_stack_varargs_pointer == NULL_RTX)
12089         t = make_tree (TREE_TYPE (ovf), virtual_incoming_args_rtx);
12090       else
12091         t = make_tree (TREE_TYPE (ovf), cfun->machine->split_stack_varargs_pointer);
12092
12093       off = INTVAL (crtl->args.arg_offset_rtx);
12094       off = off < 0 ? 0 : off;
12095       if (TARGET_DEBUG_ARG)
12096         fprintf (stderr, "va_start: n_gpr = %d, n_fpr = %d off %d\n",
12097                  (int)n_gpr, (int)n_fpr, off);
12098
12099       t = fold_build_pointer_plus_hwi (t, off);
12100
12101       t = build2 (MODIFY_EXPR, TREE_TYPE (ovf), ovf, t);
12102       TREE_SIDE_EFFECTS (t) = 1;
12103       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
12104     }
12105
12106   /* Find the register save area.  */
12107   if ((cfun->va_list_gpr_size && n_gpr < GP_ARG_NUM_REG)
12108       || (cfun->va_list_fpr_size && n_fpr < FP_ARG_NUM_REG))
12109     {
12110       t = make_tree (TREE_TYPE (sav), return_address_pointer_rtx);
12111       t = fold_build_pointer_plus_hwi (t, -RETURN_REGNUM * UNITS_PER_LONG);
12112
12113       t = build2 (MODIFY_EXPR, TREE_TYPE (sav), sav, t);
12114       TREE_SIDE_EFFECTS (t) = 1;
12115       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
12116     }
12117 }
12118
12119 /* Implement va_arg by updating the va_list structure
12120    VALIST as required to retrieve an argument of type
12121    TYPE, and returning that argument.
12122
12123    Generates code equivalent to:
12124
12125    if (integral value) {
12126      if (size  <= 4 && args.gpr < 5 ||
12127          size  > 4 && args.gpr < 4 )
12128        ret = args.reg_save_area[args.gpr+8]
12129      else
12130        ret = *args.overflow_arg_area++;
12131    } else if (vector value) {
12132        ret = *args.overflow_arg_area;
12133        args.overflow_arg_area += size / 8;
12134    } else if (float value) {
12135      if (args.fgpr < 2)
12136        ret = args.reg_save_area[args.fpr+64]
12137      else
12138        ret = *args.overflow_arg_area++;
12139    } else if (aggregate value) {
12140      if (args.gpr < 5)
12141        ret = *args.reg_save_area[args.gpr]
12142      else
12143        ret = **args.overflow_arg_area++;
12144    } */
12145
12146 static tree
12147 s390_gimplify_va_arg (tree valist, tree type, gimple_seq *pre_p,
12148                       gimple_seq *post_p ATTRIBUTE_UNUSED)
12149 {
12150   tree f_gpr, f_fpr, f_ovf, f_sav;
12151   tree gpr, fpr, ovf, sav, reg, t, u;
12152   int indirect_p, size, n_reg, sav_ofs, sav_scale, max_reg;
12153   tree lab_false, lab_over = NULL_TREE;
12154   tree addr = create_tmp_var (ptr_type_node, "addr");
12155   bool left_align_p; /* How a value < UNITS_PER_LONG is aligned within
12156                         a stack slot.  */
12157
12158   f_gpr = TYPE_FIELDS (TREE_TYPE (va_list_type_node));
12159   f_fpr = DECL_CHAIN (f_gpr);
12160   f_ovf = DECL_CHAIN (f_fpr);
12161   f_sav = DECL_CHAIN (f_ovf);
12162
12163   gpr = build3 (COMPONENT_REF, TREE_TYPE (f_gpr), valist, f_gpr, NULL_TREE);
12164   fpr = build3 (COMPONENT_REF, TREE_TYPE (f_fpr), valist, f_fpr, NULL_TREE);
12165   sav = build3 (COMPONENT_REF, TREE_TYPE (f_sav), valist, f_sav, NULL_TREE);
12166
12167   /* The tree for args* cannot be shared between gpr/fpr and ovf since
12168      both appear on a lhs.  */
12169   valist = unshare_expr (valist);
12170   ovf = build3 (COMPONENT_REF, TREE_TYPE (f_ovf), valist, f_ovf, NULL_TREE);
12171
12172   size = int_size_in_bytes (type);
12173
12174   s390_check_type_for_vector_abi (type, true, false);
12175
12176   if (pass_by_reference (NULL, TYPE_MODE (type), type, false))
12177     {
12178       if (TARGET_DEBUG_ARG)
12179         {
12180           fprintf (stderr, "va_arg: aggregate type");
12181           debug_tree (type);
12182         }
12183
12184       /* Aggregates are passed by reference.  */
12185       indirect_p = 1;
12186       reg = gpr;
12187       n_reg = 1;
12188
12189       /* kernel stack layout on 31 bit: It is assumed here that no padding
12190          will be added by s390_frame_info because for va_args always an even
12191          number of gprs has to be saved r15-r2 = 14 regs.  */
12192       sav_ofs = 2 * UNITS_PER_LONG;
12193       sav_scale = UNITS_PER_LONG;
12194       size = UNITS_PER_LONG;
12195       max_reg = GP_ARG_NUM_REG - n_reg;
12196       left_align_p = false;
12197     }
12198   else if (s390_function_arg_vector (TYPE_MODE (type), type))
12199     {
12200       if (TARGET_DEBUG_ARG)
12201         {
12202           fprintf (stderr, "va_arg: vector type");
12203           debug_tree (type);
12204         }
12205
12206       indirect_p = 0;
12207       reg = NULL_TREE;
12208       n_reg = 0;
12209       sav_ofs = 0;
12210       sav_scale = 8;
12211       max_reg = 0;
12212       left_align_p = true;
12213     }
12214   else if (s390_function_arg_float (TYPE_MODE (type), type))
12215     {
12216       if (TARGET_DEBUG_ARG)
12217         {
12218           fprintf (stderr, "va_arg: float type");
12219           debug_tree (type);
12220         }
12221
12222       /* FP args go in FP registers, if present.  */
12223       indirect_p = 0;
12224       reg = fpr;
12225       n_reg = 1;
12226       sav_ofs = 16 * UNITS_PER_LONG;
12227       sav_scale = 8;
12228       max_reg = FP_ARG_NUM_REG - n_reg;
12229       left_align_p = false;
12230     }
12231   else
12232     {
12233       if (TARGET_DEBUG_ARG)
12234         {
12235           fprintf (stderr, "va_arg: other type");
12236           debug_tree (type);
12237         }
12238
12239       /* Otherwise into GP registers.  */
12240       indirect_p = 0;
12241       reg = gpr;
12242       n_reg = (size + UNITS_PER_LONG - 1) / UNITS_PER_LONG;
12243
12244       /* kernel stack layout on 31 bit: It is assumed here that no padding
12245          will be added by s390_frame_info because for va_args always an even
12246          number of gprs has to be saved r15-r2 = 14 regs.  */
12247       sav_ofs = 2 * UNITS_PER_LONG;
12248
12249       if (size < UNITS_PER_LONG)
12250         sav_ofs += UNITS_PER_LONG - size;
12251
12252       sav_scale = UNITS_PER_LONG;
12253       max_reg = GP_ARG_NUM_REG - n_reg;
12254       left_align_p = false;
12255     }
12256
12257   /* Pull the value out of the saved registers ...  */
12258
12259   if (reg != NULL_TREE)
12260     {
12261       /*
12262         if (reg > ((typeof (reg))max_reg))
12263           goto lab_false;
12264
12265         addr = sav + sav_ofs + reg * save_scale;
12266
12267         goto lab_over;
12268
12269         lab_false:
12270       */
12271
12272       lab_false = create_artificial_label (UNKNOWN_LOCATION);
12273       lab_over = create_artificial_label (UNKNOWN_LOCATION);
12274
12275       t = fold_convert (TREE_TYPE (reg), size_int (max_reg));
12276       t = build2 (GT_EXPR, boolean_type_node, reg, t);
12277       u = build1 (GOTO_EXPR, void_type_node, lab_false);
12278       t = build3 (COND_EXPR, void_type_node, t, u, NULL_TREE);
12279       gimplify_and_add (t, pre_p);
12280
12281       t = fold_build_pointer_plus_hwi (sav, sav_ofs);
12282       u = build2 (MULT_EXPR, TREE_TYPE (reg), reg,
12283                   fold_convert (TREE_TYPE (reg), size_int (sav_scale)));
12284       t = fold_build_pointer_plus (t, u);
12285
12286       gimplify_assign (addr, t, pre_p);
12287
12288       gimple_seq_add_stmt (pre_p, gimple_build_goto (lab_over));
12289
12290       gimple_seq_add_stmt (pre_p, gimple_build_label (lab_false));
12291     }
12292
12293   /* ... Otherwise out of the overflow area.  */
12294
12295   t = ovf;
12296   if (size < UNITS_PER_LONG && !left_align_p)
12297     t = fold_build_pointer_plus_hwi (t, UNITS_PER_LONG - size);
12298
12299   gimplify_expr (&t, pre_p, NULL, is_gimple_val, fb_rvalue);
12300
12301   gimplify_assign (addr, t, pre_p);
12302
12303   if (size < UNITS_PER_LONG && left_align_p)
12304     t = fold_build_pointer_plus_hwi (t, UNITS_PER_LONG);
12305   else
12306     t = fold_build_pointer_plus_hwi (t, size);
12307
12308   gimplify_assign (ovf, t, pre_p);
12309
12310   if (reg != NULL_TREE)
12311     gimple_seq_add_stmt (pre_p, gimple_build_label (lab_over));
12312
12313
12314   /* Increment register save count.  */
12315
12316   if (n_reg > 0)
12317     {
12318       u = build2 (PREINCREMENT_EXPR, TREE_TYPE (reg), reg,
12319                   fold_convert (TREE_TYPE (reg), size_int (n_reg)));
12320       gimplify_and_add (u, pre_p);
12321     }
12322
12323   if (indirect_p)
12324     {
12325       t = build_pointer_type_for_mode (build_pointer_type (type),
12326                                        ptr_mode, true);
12327       addr = fold_convert (t, addr);
12328       addr = build_va_arg_indirect_ref (addr);
12329     }
12330   else
12331     {
12332       t = build_pointer_type_for_mode (type, ptr_mode, true);
12333       addr = fold_convert (t, addr);
12334     }
12335
12336   return build_va_arg_indirect_ref (addr);
12337 }
12338
12339 /* Emit rtl for the tbegin or tbegin_retry (RETRY != NULL_RTX)
12340    expanders.
12341    DEST  - Register location where CC will be stored.
12342    TDB   - Pointer to a 256 byte area where to store the transaction.
12343            diagnostic block. NULL if TDB is not needed.
12344    RETRY - Retry count value.  If non-NULL a retry loop for CC2
12345            is emitted
12346    CLOBBER_FPRS_P - If true clobbers for all FPRs are emitted as part
12347                     of the tbegin instruction pattern.  */
12348
12349 void
12350 s390_expand_tbegin (rtx dest, rtx tdb, rtx retry, bool clobber_fprs_p)
12351 {
12352   rtx retry_plus_two = gen_reg_rtx (SImode);
12353   rtx retry_reg = gen_reg_rtx (SImode);
12354   rtx_code_label *retry_label = NULL;
12355
12356   if (retry != NULL_RTX)
12357     {
12358       emit_move_insn (retry_reg, retry);
12359       emit_insn (gen_addsi3 (retry_plus_two, retry_reg, const2_rtx));
12360       emit_insn (gen_addsi3 (retry_reg, retry_reg, const1_rtx));
12361       retry_label = gen_label_rtx ();
12362       emit_label (retry_label);
12363     }
12364
12365   if (clobber_fprs_p)
12366     {
12367       if (TARGET_VX)
12368         emit_insn (gen_tbegin_1_z13 (gen_rtx_CONST_INT (VOIDmode, TBEGIN_MASK),
12369                                      tdb));
12370       else
12371         emit_insn (gen_tbegin_1 (gen_rtx_CONST_INT (VOIDmode, TBEGIN_MASK),
12372                                  tdb));
12373     }
12374   else
12375     emit_insn (gen_tbegin_nofloat_1 (gen_rtx_CONST_INT (VOIDmode, TBEGIN_MASK),
12376                                      tdb));
12377
12378   emit_move_insn (dest, gen_rtx_UNSPEC (SImode,
12379                                         gen_rtvec (1, gen_rtx_REG (CCRAWmode,
12380                                                                    CC_REGNUM)),
12381                                         UNSPEC_CC_TO_INT));
12382   if (retry != NULL_RTX)
12383     {
12384       const int CC0 = 1 << 3;
12385       const int CC1 = 1 << 2;
12386       const int CC3 = 1 << 0;
12387       rtx jump;
12388       rtx count = gen_reg_rtx (SImode);
12389       rtx_code_label *leave_label = gen_label_rtx ();
12390
12391       /* Exit for success and permanent failures.  */
12392       jump = s390_emit_jump (leave_label,
12393                              gen_rtx_EQ (VOIDmode,
12394                                gen_rtx_REG (CCRAWmode, CC_REGNUM),
12395                                gen_rtx_CONST_INT (VOIDmode, CC0 | CC1 | CC3)));
12396       LABEL_NUSES (leave_label) = 1;
12397
12398       /* CC2 - transient failure. Perform retry with ppa.  */
12399       emit_move_insn (count, retry_plus_two);
12400       emit_insn (gen_subsi3 (count, count, retry_reg));
12401       emit_insn (gen_tx_assist (count));
12402       jump = emit_jump_insn (gen_doloop_si64 (retry_label,
12403                                               retry_reg,
12404                                               retry_reg));
12405       JUMP_LABEL (jump) = retry_label;
12406       LABEL_NUSES (retry_label) = 1;
12407       emit_label (leave_label);
12408     }
12409 }
12410
12411
12412 /* Return the decl for the target specific builtin with the function
12413    code FCODE.  */
12414
12415 static tree
12416 s390_builtin_decl (unsigned fcode, bool initialized_p ATTRIBUTE_UNUSED)
12417 {
12418   if (fcode >= S390_BUILTIN_MAX)
12419     return error_mark_node;
12420
12421   return s390_builtin_decls[fcode];
12422 }
12423
12424 /* We call mcount before the function prologue.  So a profiled leaf
12425    function should stay a leaf function.  */
12426
12427 static bool
12428 s390_keep_leaf_when_profiled ()
12429 {
12430   return true;
12431 }
12432
12433 /* Output assembly code for the trampoline template to
12434    stdio stream FILE.
12435
12436    On S/390, we use gpr 1 internally in the trampoline code;
12437    gpr 0 is used to hold the static chain.  */
12438
12439 static void
12440 s390_asm_trampoline_template (FILE *file)
12441 {
12442   rtx op[2];
12443   op[0] = gen_rtx_REG (Pmode, 0);
12444   op[1] = gen_rtx_REG (Pmode, 1);
12445
12446   if (TARGET_64BIT)
12447     {
12448       output_asm_insn ("basr\t%1,0", op);         /* 2 byte */
12449       output_asm_insn ("lmg\t%0,%1,14(%1)", op);  /* 6 byte */
12450       output_asm_insn ("br\t%1", op);             /* 2 byte */
12451       ASM_OUTPUT_SKIP (file, (HOST_WIDE_INT)(TRAMPOLINE_SIZE - 10));
12452     }
12453   else
12454     {
12455       output_asm_insn ("basr\t%1,0", op);         /* 2 byte */
12456       output_asm_insn ("lm\t%0,%1,6(%1)", op);    /* 4 byte */
12457       output_asm_insn ("br\t%1", op);             /* 2 byte */
12458       ASM_OUTPUT_SKIP (file, (HOST_WIDE_INT)(TRAMPOLINE_SIZE - 8));
12459     }
12460 }
12461
12462 /* Emit RTL insns to initialize the variable parts of a trampoline.
12463    FNADDR is an RTX for the address of the function's pure code.
12464    CXT is an RTX for the static chain value for the function.  */
12465
12466 static void
12467 s390_trampoline_init (rtx m_tramp, tree fndecl, rtx cxt)
12468 {
12469   rtx fnaddr = XEXP (DECL_RTL (fndecl), 0);
12470   rtx mem;
12471
12472   emit_block_move (m_tramp, assemble_trampoline_template (),
12473                    GEN_INT (2 * UNITS_PER_LONG), BLOCK_OP_NORMAL);
12474
12475   mem = adjust_address (m_tramp, Pmode, 2 * UNITS_PER_LONG);
12476   emit_move_insn (mem, cxt);
12477   mem = adjust_address (m_tramp, Pmode, 3 * UNITS_PER_LONG);
12478   emit_move_insn (mem, fnaddr);
12479 }
12480
12481 /* Output assembler code to FILE to increment profiler label # LABELNO
12482    for profiling a function entry.  */
12483
12484 void
12485 s390_function_profiler (FILE *file, int labelno)
12486 {
12487   rtx op[7];
12488
12489   char label[128];
12490   ASM_GENERATE_INTERNAL_LABEL (label, "LP", labelno);
12491
12492   fprintf (file, "# function profiler \n");
12493
12494   op[0] = gen_rtx_REG (Pmode, RETURN_REGNUM);
12495   op[1] = gen_rtx_REG (Pmode, STACK_POINTER_REGNUM);
12496   op[1] = gen_rtx_MEM (Pmode, plus_constant (Pmode, op[1], UNITS_PER_LONG));
12497
12498   op[2] = gen_rtx_REG (Pmode, 1);
12499   op[3] = gen_rtx_SYMBOL_REF (Pmode, label);
12500   SYMBOL_REF_FLAGS (op[3]) = SYMBOL_FLAG_LOCAL;
12501
12502   op[4] = gen_rtx_SYMBOL_REF (Pmode, "_mcount");
12503   if (flag_pic)
12504     {
12505       op[4] = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, op[4]), UNSPEC_PLT);
12506       op[4] = gen_rtx_CONST (Pmode, op[4]);
12507     }
12508
12509   if (TARGET_64BIT)
12510     {
12511       output_asm_insn ("stg\t%0,%1", op);
12512       output_asm_insn ("larl\t%2,%3", op);
12513       output_asm_insn ("brasl\t%0,%4", op);
12514       output_asm_insn ("lg\t%0,%1", op);
12515     }
12516   else if (TARGET_CPU_ZARCH)
12517     {
12518       output_asm_insn ("st\t%0,%1", op);
12519       output_asm_insn ("larl\t%2,%3", op);
12520       output_asm_insn ("brasl\t%0,%4", op);
12521       output_asm_insn ("l\t%0,%1", op);
12522     }
12523   else if (!flag_pic)
12524     {
12525       op[6] = gen_label_rtx ();
12526
12527       output_asm_insn ("st\t%0,%1", op);
12528       output_asm_insn ("bras\t%2,%l6", op);
12529       output_asm_insn (".long\t%4", op);
12530       output_asm_insn (".long\t%3", op);
12531       targetm.asm_out.internal_label (file, "L", CODE_LABEL_NUMBER (op[6]));
12532       output_asm_insn ("l\t%0,0(%2)", op);
12533       output_asm_insn ("l\t%2,4(%2)", op);
12534       output_asm_insn ("basr\t%0,%0", op);
12535       output_asm_insn ("l\t%0,%1", op);
12536     }
12537   else
12538     {
12539       op[5] = gen_label_rtx ();
12540       op[6] = gen_label_rtx ();
12541
12542       output_asm_insn ("st\t%0,%1", op);
12543       output_asm_insn ("bras\t%2,%l6", op);
12544       targetm.asm_out.internal_label (file, "L", CODE_LABEL_NUMBER (op[5]));
12545       output_asm_insn (".long\t%4-%l5", op);
12546       output_asm_insn (".long\t%3-%l5", op);
12547       targetm.asm_out.internal_label (file, "L", CODE_LABEL_NUMBER (op[6]));
12548       output_asm_insn ("lr\t%0,%2", op);
12549       output_asm_insn ("a\t%0,0(%2)", op);
12550       output_asm_insn ("a\t%2,4(%2)", op);
12551       output_asm_insn ("basr\t%0,%0", op);
12552       output_asm_insn ("l\t%0,%1", op);
12553     }
12554 }
12555
12556 /* Encode symbol attributes (local vs. global, tls model) of a SYMBOL_REF
12557    into its SYMBOL_REF_FLAGS.  */
12558
12559 static void
12560 s390_encode_section_info (tree decl, rtx rtl, int first)
12561 {
12562   default_encode_section_info (decl, rtl, first);
12563
12564   if (TREE_CODE (decl) == VAR_DECL)
12565     {
12566       /* Store the alignment to be able to check if we can use
12567          a larl/load-relative instruction.  We only handle the cases
12568          that can go wrong (i.e. no FUNC_DECLs).  */
12569       if (DECL_ALIGN (decl) == 0 || DECL_ALIGN (decl) % 16)
12570         SYMBOL_FLAG_SET_NOTALIGN2 (XEXP (rtl, 0));
12571       else if (DECL_ALIGN (decl) % 32)
12572         SYMBOL_FLAG_SET_NOTALIGN4 (XEXP (rtl, 0));
12573       else if (DECL_ALIGN (decl) % 64)
12574         SYMBOL_FLAG_SET_NOTALIGN8 (XEXP (rtl, 0));
12575     }
12576
12577   /* Literal pool references don't have a decl so they are handled
12578      differently here.  We rely on the information in the MEM_ALIGN
12579      entry to decide upon the alignment.  */
12580   if (MEM_P (rtl)
12581       && GET_CODE (XEXP (rtl, 0)) == SYMBOL_REF
12582       && TREE_CONSTANT_POOL_ADDRESS_P (XEXP (rtl, 0)))
12583     {
12584       if (MEM_ALIGN (rtl) == 0 || MEM_ALIGN (rtl) % 16)
12585         SYMBOL_FLAG_SET_NOTALIGN2 (XEXP (rtl, 0));
12586       else if (MEM_ALIGN (rtl) % 32)
12587         SYMBOL_FLAG_SET_NOTALIGN4 (XEXP (rtl, 0));
12588       else if (MEM_ALIGN (rtl) % 64)
12589         SYMBOL_FLAG_SET_NOTALIGN8 (XEXP (rtl, 0));
12590     }
12591 }
12592
12593 /* Output thunk to FILE that implements a C++ virtual function call (with
12594    multiple inheritance) to FUNCTION.  The thunk adjusts the this pointer
12595    by DELTA, and unless VCALL_OFFSET is zero, applies an additional adjustment
12596    stored at VCALL_OFFSET in the vtable whose address is located at offset 0
12597    relative to the resulting this pointer.  */
12598
12599 static void
12600 s390_output_mi_thunk (FILE *file, tree thunk ATTRIBUTE_UNUSED,
12601                       HOST_WIDE_INT delta, HOST_WIDE_INT vcall_offset,
12602                       tree function)
12603 {
12604   rtx op[10];
12605   int nonlocal = 0;
12606
12607   /* Make sure unwind info is emitted for the thunk if needed.  */
12608   final_start_function (emit_barrier (), file, 1);
12609
12610   /* Operand 0 is the target function.  */
12611   op[0] = XEXP (DECL_RTL (function), 0);
12612   if (flag_pic && !SYMBOL_REF_LOCAL_P (op[0]))
12613     {
12614       nonlocal = 1;
12615       op[0] = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, op[0]),
12616                               TARGET_64BIT ? UNSPEC_PLT : UNSPEC_GOT);
12617       op[0] = gen_rtx_CONST (Pmode, op[0]);
12618     }
12619
12620   /* Operand 1 is the 'this' pointer.  */
12621   if (aggregate_value_p (TREE_TYPE (TREE_TYPE (function)), function))
12622     op[1] = gen_rtx_REG (Pmode, 3);
12623   else
12624     op[1] = gen_rtx_REG (Pmode, 2);
12625
12626   /* Operand 2 is the delta.  */
12627   op[2] = GEN_INT (delta);
12628
12629   /* Operand 3 is the vcall_offset.  */
12630   op[3] = GEN_INT (vcall_offset);
12631
12632   /* Operand 4 is the temporary register.  */
12633   op[4] = gen_rtx_REG (Pmode, 1);
12634
12635   /* Operands 5 to 8 can be used as labels.  */
12636   op[5] = NULL_RTX;
12637   op[6] = NULL_RTX;
12638   op[7] = NULL_RTX;
12639   op[8] = NULL_RTX;
12640
12641   /* Operand 9 can be used for temporary register.  */
12642   op[9] = NULL_RTX;
12643
12644   /* Generate code.  */
12645   if (TARGET_64BIT)
12646     {
12647       /* Setup literal pool pointer if required.  */
12648       if ((!DISP_IN_RANGE (delta)
12649            && !CONST_OK_FOR_K (delta)
12650            && !CONST_OK_FOR_Os (delta))
12651           || (!DISP_IN_RANGE (vcall_offset)
12652               && !CONST_OK_FOR_K (vcall_offset)
12653               && !CONST_OK_FOR_Os (vcall_offset)))
12654         {
12655           op[5] = gen_label_rtx ();
12656           output_asm_insn ("larl\t%4,%5", op);
12657         }
12658
12659       /* Add DELTA to this pointer.  */
12660       if (delta)
12661         {
12662           if (CONST_OK_FOR_J (delta))
12663             output_asm_insn ("la\t%1,%2(%1)", op);
12664           else if (DISP_IN_RANGE (delta))
12665             output_asm_insn ("lay\t%1,%2(%1)", op);
12666           else if (CONST_OK_FOR_K (delta))
12667             output_asm_insn ("aghi\t%1,%2", op);
12668           else if (CONST_OK_FOR_Os (delta))
12669             output_asm_insn ("agfi\t%1,%2", op);
12670           else
12671             {
12672               op[6] = gen_label_rtx ();
12673               output_asm_insn ("agf\t%1,%6-%5(%4)", op);
12674             }
12675         }
12676
12677       /* Perform vcall adjustment.  */
12678       if (vcall_offset)
12679         {
12680           if (DISP_IN_RANGE (vcall_offset))
12681             {
12682               output_asm_insn ("lg\t%4,0(%1)", op);
12683               output_asm_insn ("ag\t%1,%3(%4)", op);
12684             }
12685           else if (CONST_OK_FOR_K (vcall_offset))
12686             {
12687               output_asm_insn ("lghi\t%4,%3", op);
12688               output_asm_insn ("ag\t%4,0(%1)", op);
12689               output_asm_insn ("ag\t%1,0(%4)", op);
12690             }
12691           else if (CONST_OK_FOR_Os (vcall_offset))
12692             {
12693               output_asm_insn ("lgfi\t%4,%3", op);
12694               output_asm_insn ("ag\t%4,0(%1)", op);
12695               output_asm_insn ("ag\t%1,0(%4)", op);
12696             }
12697           else
12698             {
12699               op[7] = gen_label_rtx ();
12700               output_asm_insn ("llgf\t%4,%7-%5(%4)", op);
12701               output_asm_insn ("ag\t%4,0(%1)", op);
12702               output_asm_insn ("ag\t%1,0(%4)", op);
12703             }
12704         }
12705
12706       /* Jump to target.  */
12707       output_asm_insn ("jg\t%0", op);
12708
12709       /* Output literal pool if required.  */
12710       if (op[5])
12711         {
12712           output_asm_insn (".align\t4", op);
12713           targetm.asm_out.internal_label (file, "L",
12714                                           CODE_LABEL_NUMBER (op[5]));
12715         }
12716       if (op[6])
12717         {
12718           targetm.asm_out.internal_label (file, "L",
12719                                           CODE_LABEL_NUMBER (op[6]));
12720           output_asm_insn (".long\t%2", op);
12721         }
12722       if (op[7])
12723         {
12724           targetm.asm_out.internal_label (file, "L",
12725                                           CODE_LABEL_NUMBER (op[7]));
12726           output_asm_insn (".long\t%3", op);
12727         }
12728     }
12729   else
12730     {
12731       /* Setup base pointer if required.  */
12732       if (!vcall_offset
12733           || (!DISP_IN_RANGE (delta)
12734               && !CONST_OK_FOR_K (delta)
12735               && !CONST_OK_FOR_Os (delta))
12736           || (!DISP_IN_RANGE (delta)
12737               && !CONST_OK_FOR_K (vcall_offset)
12738               && !CONST_OK_FOR_Os (vcall_offset)))
12739         {
12740           op[5] = gen_label_rtx ();
12741           output_asm_insn ("basr\t%4,0", op);
12742           targetm.asm_out.internal_label (file, "L",
12743                                           CODE_LABEL_NUMBER (op[5]));
12744         }
12745
12746       /* Add DELTA to this pointer.  */
12747       if (delta)
12748         {
12749           if (CONST_OK_FOR_J (delta))
12750             output_asm_insn ("la\t%1,%2(%1)", op);
12751           else if (DISP_IN_RANGE (delta))
12752             output_asm_insn ("lay\t%1,%2(%1)", op);
12753           else if (CONST_OK_FOR_K (delta))
12754             output_asm_insn ("ahi\t%1,%2", op);
12755           else if (CONST_OK_FOR_Os (delta))
12756             output_asm_insn ("afi\t%1,%2", op);
12757           else
12758             {
12759               op[6] = gen_label_rtx ();
12760               output_asm_insn ("a\t%1,%6-%5(%4)", op);
12761             }
12762         }
12763
12764       /* Perform vcall adjustment.  */
12765       if (vcall_offset)
12766         {
12767           if (CONST_OK_FOR_J (vcall_offset))
12768             {
12769               output_asm_insn ("l\t%4,0(%1)", op);
12770               output_asm_insn ("a\t%1,%3(%4)", op);
12771             }
12772           else if (DISP_IN_RANGE (vcall_offset))
12773             {
12774               output_asm_insn ("l\t%4,0(%1)", op);
12775               output_asm_insn ("ay\t%1,%3(%4)", op);
12776             }
12777           else if (CONST_OK_FOR_K (vcall_offset))
12778             {
12779               output_asm_insn ("lhi\t%4,%3", op);
12780               output_asm_insn ("a\t%4,0(%1)", op);
12781               output_asm_insn ("a\t%1,0(%4)", op);
12782             }
12783           else if (CONST_OK_FOR_Os (vcall_offset))
12784             {
12785               output_asm_insn ("iilf\t%4,%3", op);
12786               output_asm_insn ("a\t%4,0(%1)", op);
12787               output_asm_insn ("a\t%1,0(%4)", op);
12788             }
12789           else
12790             {
12791               op[7] = gen_label_rtx ();
12792               output_asm_insn ("l\t%4,%7-%5(%4)", op);
12793               output_asm_insn ("a\t%4,0(%1)", op);
12794               output_asm_insn ("a\t%1,0(%4)", op);
12795             }
12796
12797           /* We had to clobber the base pointer register.
12798              Re-setup the base pointer (with a different base).  */
12799           op[5] = gen_label_rtx ();
12800           output_asm_insn ("basr\t%4,0", op);
12801           targetm.asm_out.internal_label (file, "L",
12802                                           CODE_LABEL_NUMBER (op[5]));
12803         }
12804
12805       /* Jump to target.  */
12806       op[8] = gen_label_rtx ();
12807
12808       if (!flag_pic)
12809         output_asm_insn ("l\t%4,%8-%5(%4)", op);
12810       else if (!nonlocal)
12811         output_asm_insn ("a\t%4,%8-%5(%4)", op);
12812       /* We cannot call through .plt, since .plt requires %r12 loaded.  */
12813       else if (flag_pic == 1)
12814         {
12815           output_asm_insn ("a\t%4,%8-%5(%4)", op);
12816           output_asm_insn ("l\t%4,%0(%4)", op);
12817         }
12818       else if (flag_pic == 2)
12819         {
12820           op[9] = gen_rtx_REG (Pmode, 0);
12821           output_asm_insn ("l\t%9,%8-4-%5(%4)", op);
12822           output_asm_insn ("a\t%4,%8-%5(%4)", op);
12823           output_asm_insn ("ar\t%4,%9", op);
12824           output_asm_insn ("l\t%4,0(%4)", op);
12825         }
12826
12827       output_asm_insn ("br\t%4", op);
12828
12829       /* Output literal pool.  */
12830       output_asm_insn (".align\t4", op);
12831
12832       if (nonlocal && flag_pic == 2)
12833         output_asm_insn (".long\t%0", op);
12834       if (nonlocal)
12835         {
12836           op[0] = gen_rtx_SYMBOL_REF (Pmode, "_GLOBAL_OFFSET_TABLE_");
12837           SYMBOL_REF_FLAGS (op[0]) = SYMBOL_FLAG_LOCAL;
12838         }
12839
12840       targetm.asm_out.internal_label (file, "L", CODE_LABEL_NUMBER (op[8]));
12841       if (!flag_pic)
12842         output_asm_insn (".long\t%0", op);
12843       else
12844         output_asm_insn (".long\t%0-%5", op);
12845
12846       if (op[6])
12847         {
12848           targetm.asm_out.internal_label (file, "L",
12849                                           CODE_LABEL_NUMBER (op[6]));
12850           output_asm_insn (".long\t%2", op);
12851         }
12852       if (op[7])
12853         {
12854           targetm.asm_out.internal_label (file, "L",
12855                                           CODE_LABEL_NUMBER (op[7]));
12856           output_asm_insn (".long\t%3", op);
12857         }
12858     }
12859   final_end_function ();
12860 }
12861
12862 static bool
12863 s390_valid_pointer_mode (machine_mode mode)
12864 {
12865   return (mode == SImode || (TARGET_64BIT && mode == DImode));
12866 }
12867
12868 /* Checks whether the given CALL_EXPR would use a caller
12869    saved register.  This is used to decide whether sibling call
12870    optimization could be performed on the respective function
12871    call.  */
12872
12873 static bool
12874 s390_call_saved_register_used (tree call_expr)
12875 {
12876   CUMULATIVE_ARGS cum_v;
12877   cumulative_args_t cum;
12878   tree parameter;
12879   machine_mode mode;
12880   tree type;
12881   rtx parm_rtx;
12882   int reg, i;
12883
12884   INIT_CUMULATIVE_ARGS (cum_v, NULL, NULL, 0, 0);
12885   cum = pack_cumulative_args (&cum_v);
12886
12887   for (i = 0; i < call_expr_nargs (call_expr); i++)
12888     {
12889       parameter = CALL_EXPR_ARG (call_expr, i);
12890       gcc_assert (parameter);
12891
12892       /* For an undeclared variable passed as parameter we will get
12893          an ERROR_MARK node here.  */
12894       if (TREE_CODE (parameter) == ERROR_MARK)
12895         return true;
12896
12897       type = TREE_TYPE (parameter);
12898       gcc_assert (type);
12899
12900       mode = TYPE_MODE (type);
12901       gcc_assert (mode);
12902
12903       /* We assume that in the target function all parameters are
12904          named.  This only has an impact on vector argument register
12905          usage none of which is call-saved.  */
12906       if (pass_by_reference (&cum_v, mode, type, true))
12907         {
12908           mode = Pmode;
12909           type = build_pointer_type (type);
12910         }
12911
12912        parm_rtx = s390_function_arg (cum, mode, type, true);
12913
12914        s390_function_arg_advance (cum, mode, type, true);
12915
12916        if (!parm_rtx)
12917          continue;
12918
12919        if (REG_P (parm_rtx))
12920          {
12921            for (reg = 0;
12922                 reg < HARD_REGNO_NREGS (REGNO (parm_rtx), GET_MODE (parm_rtx));
12923                 reg++)
12924              if (!call_used_regs[reg + REGNO (parm_rtx)])
12925                return true;
12926          }
12927
12928        if (GET_CODE (parm_rtx) == PARALLEL)
12929          {
12930            int i;
12931
12932            for (i = 0; i < XVECLEN (parm_rtx, 0); i++)
12933              {
12934                rtx r = XEXP (XVECEXP (parm_rtx, 0, i), 0);
12935
12936                gcc_assert (REG_P (r));
12937
12938                for (reg = 0;
12939                     reg < HARD_REGNO_NREGS (REGNO (r), GET_MODE (r));
12940                     reg++)
12941                  if (!call_used_regs[reg + REGNO (r)])
12942                    return true;
12943              }
12944          }
12945
12946     }
12947   return false;
12948 }
12949
12950 /* Return true if the given call expression can be
12951    turned into a sibling call.
12952    DECL holds the declaration of the function to be called whereas
12953    EXP is the call expression itself.  */
12954
12955 static bool
12956 s390_function_ok_for_sibcall (tree decl, tree exp)
12957 {
12958   /* The TPF epilogue uses register 1.  */
12959   if (TARGET_TPF_PROFILING)
12960     return false;
12961
12962   /* The 31 bit PLT code uses register 12 (GOT pointer - caller saved)
12963      which would have to be restored before the sibcall.  */
12964   if (!TARGET_64BIT && flag_pic && decl && !targetm.binds_local_p (decl))
12965     return false;
12966
12967   /* Register 6 on s390 is available as an argument register but unfortunately
12968      "caller saved". This makes functions needing this register for arguments
12969      not suitable for sibcalls.  */
12970   return !s390_call_saved_register_used (exp);
12971 }
12972
12973 /* Return the fixed registers used for condition codes.  */
12974
12975 static bool
12976 s390_fixed_condition_code_regs (unsigned int *p1, unsigned int *p2)
12977 {
12978   *p1 = CC_REGNUM;
12979   *p2 = INVALID_REGNUM;
12980
12981   return true;
12982 }
12983
12984 /* This function is used by the call expanders of the machine description.
12985    It emits the call insn itself together with the necessary operations
12986    to adjust the target address and returns the emitted insn.
12987    ADDR_LOCATION is the target address rtx
12988    TLS_CALL the location of the thread-local symbol
12989    RESULT_REG the register where the result of the call should be stored
12990    RETADDR_REG the register where the return address should be stored
12991                If this parameter is NULL_RTX the call is considered
12992                to be a sibling call.  */
12993
12994 rtx_insn *
12995 s390_emit_call (rtx addr_location, rtx tls_call, rtx result_reg,
12996                 rtx retaddr_reg)
12997 {
12998   bool plt_call = false;
12999   rtx_insn *insn;
13000   rtx call;
13001   rtx clobber;
13002   rtvec vec;
13003
13004   /* Direct function calls need special treatment.  */
13005   if (GET_CODE (addr_location) == SYMBOL_REF)
13006     {
13007       /* When calling a global routine in PIC mode, we must
13008          replace the symbol itself with the PLT stub.  */
13009       if (flag_pic && !SYMBOL_REF_LOCAL_P (addr_location))
13010         {
13011           if (TARGET_64BIT || retaddr_reg != NULL_RTX)
13012             {
13013               addr_location = gen_rtx_UNSPEC (Pmode,
13014                                               gen_rtvec (1, addr_location),
13015                                               UNSPEC_PLT);
13016               addr_location = gen_rtx_CONST (Pmode, addr_location);
13017               plt_call = true;
13018             }
13019           else
13020             /* For -fpic code the PLT entries might use r12 which is
13021                call-saved.  Therefore we cannot do a sibcall when
13022                calling directly using a symbol ref.  When reaching
13023                this point we decided (in s390_function_ok_for_sibcall)
13024                to do a sibcall for a function pointer but one of the
13025                optimizers was able to get rid of the function pointer
13026                by propagating the symbol ref into the call.  This
13027                optimization is illegal for S/390 so we turn the direct
13028                call into a indirect call again.  */
13029             addr_location = force_reg (Pmode, addr_location);
13030         }
13031
13032       /* Unless we can use the bras(l) insn, force the
13033          routine address into a register.  */
13034       if (!TARGET_SMALL_EXEC && !TARGET_CPU_ZARCH)
13035         {
13036           if (flag_pic)
13037             addr_location = legitimize_pic_address (addr_location, 0);
13038           else
13039             addr_location = force_reg (Pmode, addr_location);
13040         }
13041     }
13042
13043   /* If it is already an indirect call or the code above moved the
13044      SYMBOL_REF to somewhere else make sure the address can be found in
13045      register 1.  */
13046   if (retaddr_reg == NULL_RTX
13047       && GET_CODE (addr_location) != SYMBOL_REF
13048       && !plt_call)
13049     {
13050       emit_move_insn (gen_rtx_REG (Pmode, SIBCALL_REGNUM), addr_location);
13051       addr_location = gen_rtx_REG (Pmode, SIBCALL_REGNUM);
13052     }
13053
13054   addr_location = gen_rtx_MEM (QImode, addr_location);
13055   call = gen_rtx_CALL (VOIDmode, addr_location, const0_rtx);
13056
13057   if (result_reg != NULL_RTX)
13058     call = gen_rtx_SET (result_reg, call);
13059
13060   if (retaddr_reg != NULL_RTX)
13061     {
13062       clobber = gen_rtx_CLOBBER (VOIDmode, retaddr_reg);
13063
13064       if (tls_call != NULL_RTX)
13065         vec = gen_rtvec (3, call, clobber,
13066                          gen_rtx_USE (VOIDmode, tls_call));
13067       else
13068         vec = gen_rtvec (2, call, clobber);
13069
13070       call = gen_rtx_PARALLEL (VOIDmode, vec);
13071     }
13072
13073   insn = emit_call_insn (call);
13074
13075   /* 31-bit PLT stubs and tls calls use the GOT register implicitly.  */
13076   if ((!TARGET_64BIT && plt_call) || tls_call != NULL_RTX)
13077     {
13078       /* s390_function_ok_for_sibcall should
13079          have denied sibcalls in this case.  */
13080       gcc_assert (retaddr_reg != NULL_RTX);
13081       use_reg (&CALL_INSN_FUNCTION_USAGE (insn), gen_rtx_REG (Pmode, 12));
13082     }
13083   return insn;
13084 }
13085
13086 /* Implement TARGET_CONDITIONAL_REGISTER_USAGE.  */
13087
13088 static void
13089 s390_conditional_register_usage (void)
13090 {
13091   int i;
13092
13093   if (flag_pic)
13094     {
13095       fixed_regs[PIC_OFFSET_TABLE_REGNUM] = 1;
13096       call_used_regs[PIC_OFFSET_TABLE_REGNUM] = 1;
13097     }
13098   if (TARGET_CPU_ZARCH)
13099     {
13100       fixed_regs[BASE_REGNUM] = 0;
13101       call_used_regs[BASE_REGNUM] = 0;
13102       fixed_regs[RETURN_REGNUM] = 0;
13103       call_used_regs[RETURN_REGNUM] = 0;
13104     }
13105   if (TARGET_64BIT)
13106     {
13107       for (i = FPR8_REGNUM; i <= FPR15_REGNUM; i++)
13108         call_used_regs[i] = call_really_used_regs[i] = 0;
13109     }
13110   else
13111     {
13112       call_used_regs[FPR4_REGNUM] = call_really_used_regs[FPR4_REGNUM] = 0;
13113       call_used_regs[FPR6_REGNUM] = call_really_used_regs[FPR6_REGNUM] = 0;
13114     }
13115
13116   if (TARGET_SOFT_FLOAT)
13117     {
13118       for (i = FPR0_REGNUM; i <= FPR15_REGNUM; i++)
13119         call_used_regs[i] = fixed_regs[i] = 1;
13120     }
13121
13122   /* Disable v16 - v31 for non-vector target.  */
13123   if (!TARGET_VX)
13124     {
13125       for (i = VR16_REGNUM; i <= VR31_REGNUM; i++)
13126         fixed_regs[i] = call_used_regs[i] = call_really_used_regs[i] = 1;
13127     }
13128 }
13129
13130 /* Corresponding function to eh_return expander.  */
13131
13132 static GTY(()) rtx s390_tpf_eh_return_symbol;
13133 void
13134 s390_emit_tpf_eh_return (rtx target)
13135 {
13136   rtx_insn *insn;
13137   rtx reg, orig_ra;
13138
13139   if (!s390_tpf_eh_return_symbol)
13140     s390_tpf_eh_return_symbol = gen_rtx_SYMBOL_REF (Pmode, "__tpf_eh_return");
13141
13142   reg = gen_rtx_REG (Pmode, 2);
13143   orig_ra = gen_rtx_REG (Pmode, 3);
13144
13145   emit_move_insn (reg, target);
13146   emit_move_insn (orig_ra, get_hard_reg_initial_val (Pmode, RETURN_REGNUM));
13147   insn = s390_emit_call (s390_tpf_eh_return_symbol, NULL_RTX, reg,
13148                                      gen_rtx_REG (Pmode, RETURN_REGNUM));
13149   use_reg (&CALL_INSN_FUNCTION_USAGE (insn), reg);
13150   use_reg (&CALL_INSN_FUNCTION_USAGE (insn), orig_ra);
13151
13152   emit_move_insn (EH_RETURN_HANDLER_RTX, reg);
13153 }
13154
13155 /* Rework the prologue/epilogue to avoid saving/restoring
13156    registers unnecessarily.  */
13157
13158 static void
13159 s390_optimize_prologue (void)
13160 {
13161   rtx_insn *insn, *new_insn, *next_insn;
13162
13163   /* Do a final recompute of the frame-related data.  */
13164   s390_optimize_register_info ();
13165
13166   /* If all special registers are in fact used, there's nothing we
13167      can do, so no point in walking the insn list.  */
13168
13169   if (cfun_frame_layout.first_save_gpr <= BASE_REGNUM
13170       && cfun_frame_layout.last_save_gpr >= BASE_REGNUM
13171       && (TARGET_CPU_ZARCH
13172           || (cfun_frame_layout.first_save_gpr <= RETURN_REGNUM
13173               && cfun_frame_layout.last_save_gpr >= RETURN_REGNUM)))
13174     return;
13175
13176   /* Search for prologue/epilogue insns and replace them.  */
13177
13178   for (insn = get_insns (); insn; insn = next_insn)
13179     {
13180       int first, last, off;
13181       rtx set, base, offset;
13182       rtx pat;
13183
13184       next_insn = NEXT_INSN (insn);
13185
13186       if (! NONJUMP_INSN_P (insn) || ! RTX_FRAME_RELATED_P (insn))
13187         continue;
13188
13189       pat = PATTERN (insn);
13190
13191       /* Remove ldgr/lgdr instructions used for saving and restore
13192          GPRs if possible.  */
13193       if (TARGET_Z10)
13194         {
13195           rtx tmp_pat = pat;
13196
13197           if (INSN_CODE (insn) == CODE_FOR_stack_restore_from_fpr)
13198             tmp_pat = XVECEXP (pat, 0, 0);
13199
13200           if (GET_CODE (tmp_pat) == SET
13201               && GET_MODE (SET_SRC (tmp_pat)) == DImode
13202               && REG_P (SET_SRC (tmp_pat))
13203               && REG_P (SET_DEST (tmp_pat)))
13204             {
13205               int src_regno = REGNO (SET_SRC (tmp_pat));
13206               int dest_regno = REGNO (SET_DEST (tmp_pat));
13207               int gpr_regno;
13208               int fpr_regno;
13209
13210               if (!((GENERAL_REGNO_P (src_regno)
13211                      && FP_REGNO_P (dest_regno))
13212                     || (FP_REGNO_P (src_regno)
13213                         && GENERAL_REGNO_P (dest_regno))))
13214                 continue;
13215
13216               gpr_regno = GENERAL_REGNO_P (src_regno) ? src_regno : dest_regno;
13217               fpr_regno = FP_REGNO_P (src_regno) ? src_regno : dest_regno;
13218
13219               /* GPR must be call-saved, FPR must be call-clobbered.  */
13220               if (!call_really_used_regs[fpr_regno]
13221                   || call_really_used_regs[gpr_regno])
13222                 continue;
13223
13224               /* It must not happen that what we once saved in an FPR now
13225                  needs a stack slot.  */
13226               gcc_assert (cfun_gpr_save_slot (gpr_regno) != SAVE_SLOT_STACK);
13227
13228               if (cfun_gpr_save_slot (gpr_regno) == SAVE_SLOT_NONE)
13229                 {
13230                   remove_insn (insn);
13231                   continue;
13232                 }
13233             }
13234         }
13235
13236       if (GET_CODE (pat) == PARALLEL
13237           && store_multiple_operation (pat, VOIDmode))
13238         {
13239           set = XVECEXP (pat, 0, 0);
13240           first = REGNO (SET_SRC (set));
13241           last = first + XVECLEN (pat, 0) - 1;
13242           offset = const0_rtx;
13243           base = eliminate_constant_term (XEXP (SET_DEST (set), 0), &offset);
13244           off = INTVAL (offset);
13245
13246           if (GET_CODE (base) != REG || off < 0)
13247             continue;
13248           if (cfun_frame_layout.first_save_gpr != -1
13249               && (cfun_frame_layout.first_save_gpr < first
13250                   || cfun_frame_layout.last_save_gpr > last))
13251             continue;
13252           if (REGNO (base) != STACK_POINTER_REGNUM
13253               && REGNO (base) != HARD_FRAME_POINTER_REGNUM)
13254             continue;
13255           if (first > BASE_REGNUM || last < BASE_REGNUM)
13256             continue;
13257
13258           if (cfun_frame_layout.first_save_gpr != -1)
13259             {
13260               rtx s_pat = save_gprs (base,
13261                                      off + (cfun_frame_layout.first_save_gpr
13262                                             - first) * UNITS_PER_LONG,
13263                                      cfun_frame_layout.first_save_gpr,
13264                                      cfun_frame_layout.last_save_gpr);
13265               new_insn = emit_insn_before (s_pat, insn);
13266               INSN_ADDRESSES_NEW (new_insn, -1);
13267             }
13268
13269           remove_insn (insn);
13270           continue;
13271         }
13272
13273       if (cfun_frame_layout.first_save_gpr == -1
13274           && GET_CODE (pat) == SET
13275           && GENERAL_REG_P (SET_SRC (pat))
13276           && GET_CODE (SET_DEST (pat)) == MEM)
13277         {
13278           set = pat;
13279           first = REGNO (SET_SRC (set));
13280           offset = const0_rtx;
13281           base = eliminate_constant_term (XEXP (SET_DEST (set), 0), &offset);
13282           off = INTVAL (offset);
13283
13284           if (GET_CODE (base) != REG || off < 0)
13285             continue;
13286           if (REGNO (base) != STACK_POINTER_REGNUM
13287               && REGNO (base) != HARD_FRAME_POINTER_REGNUM)
13288             continue;
13289
13290           remove_insn (insn);
13291           continue;
13292         }
13293
13294       if (GET_CODE (pat) == PARALLEL
13295           && load_multiple_operation (pat, VOIDmode))
13296         {
13297           set = XVECEXP (pat, 0, 0);
13298           first = REGNO (SET_DEST (set));
13299           last = first + XVECLEN (pat, 0) - 1;
13300           offset = const0_rtx;
13301           base = eliminate_constant_term (XEXP (SET_SRC (set), 0), &offset);
13302           off = INTVAL (offset);
13303
13304           if (GET_CODE (base) != REG || off < 0)
13305             continue;
13306
13307           if (cfun_frame_layout.first_restore_gpr != -1
13308               && (cfun_frame_layout.first_restore_gpr < first
13309                   || cfun_frame_layout.last_restore_gpr > last))
13310             continue;
13311           if (REGNO (base) != STACK_POINTER_REGNUM
13312               && REGNO (base) != HARD_FRAME_POINTER_REGNUM)
13313             continue;
13314           if (first > BASE_REGNUM || last < BASE_REGNUM)
13315             continue;
13316
13317           if (cfun_frame_layout.first_restore_gpr != -1)
13318             {
13319               rtx rpat = restore_gprs (base,
13320                                        off + (cfun_frame_layout.first_restore_gpr
13321                                               - first) * UNITS_PER_LONG,
13322                                        cfun_frame_layout.first_restore_gpr,
13323                                        cfun_frame_layout.last_restore_gpr);
13324
13325               /* Remove REG_CFA_RESTOREs for registers that we no
13326                  longer need to save.  */
13327               REG_NOTES (rpat) = REG_NOTES (insn);
13328               for (rtx *ptr = &REG_NOTES (rpat); *ptr; )
13329                 if (REG_NOTE_KIND (*ptr) == REG_CFA_RESTORE
13330                     && ((int) REGNO (XEXP (*ptr, 0))
13331                         < cfun_frame_layout.first_restore_gpr))
13332                   *ptr = XEXP (*ptr, 1);
13333                 else
13334                   ptr = &XEXP (*ptr, 1);
13335               new_insn = emit_insn_before (rpat, insn);
13336               RTX_FRAME_RELATED_P (new_insn) = 1;
13337               INSN_ADDRESSES_NEW (new_insn, -1);
13338             }
13339
13340           remove_insn (insn);
13341           continue;
13342         }
13343
13344       if (cfun_frame_layout.first_restore_gpr == -1
13345           && GET_CODE (pat) == SET
13346           && GENERAL_REG_P (SET_DEST (pat))
13347           && GET_CODE (SET_SRC (pat)) == MEM)
13348         {
13349           set = pat;
13350           first = REGNO (SET_DEST (set));
13351           offset = const0_rtx;
13352           base = eliminate_constant_term (XEXP (SET_SRC (set), 0), &offset);
13353           off = INTVAL (offset);
13354
13355           if (GET_CODE (base) != REG || off < 0)
13356             continue;
13357
13358           if (REGNO (base) != STACK_POINTER_REGNUM
13359               && REGNO (base) != HARD_FRAME_POINTER_REGNUM)
13360             continue;
13361
13362           remove_insn (insn);
13363           continue;
13364         }
13365     }
13366 }
13367
13368 /* On z10 and later the dynamic branch prediction must see the
13369    backward jump within a certain windows.  If not it falls back to
13370    the static prediction.  This function rearranges the loop backward
13371    branch in a way which makes the static prediction always correct.
13372    The function returns true if it added an instruction.  */
13373 static bool
13374 s390_fix_long_loop_prediction (rtx_insn *insn)
13375 {
13376   rtx set = single_set (insn);
13377   rtx code_label, label_ref;
13378   rtx_insn *uncond_jump;
13379   rtx_insn *cur_insn;
13380   rtx tmp;
13381   int distance;
13382
13383   /* This will exclude branch on count and branch on index patterns
13384      since these are correctly statically predicted.  */
13385   if (!set
13386       || SET_DEST (set) != pc_rtx
13387       || GET_CODE (SET_SRC(set)) != IF_THEN_ELSE)
13388     return false;
13389
13390   /* Skip conditional returns.  */
13391   if (ANY_RETURN_P (XEXP (SET_SRC (set), 1))
13392       && XEXP (SET_SRC (set), 2) == pc_rtx)
13393     return false;
13394
13395   label_ref = (GET_CODE (XEXP (SET_SRC (set), 1)) == LABEL_REF ?
13396                XEXP (SET_SRC (set), 1) : XEXP (SET_SRC (set), 2));
13397
13398   gcc_assert (GET_CODE (label_ref) == LABEL_REF);
13399
13400   code_label = XEXP (label_ref, 0);
13401
13402   if (INSN_ADDRESSES (INSN_UID (code_label)) == -1
13403       || INSN_ADDRESSES (INSN_UID (insn)) == -1
13404       || (INSN_ADDRESSES (INSN_UID (insn))
13405           - INSN_ADDRESSES (INSN_UID (code_label)) < PREDICT_DISTANCE))
13406     return false;
13407
13408   for (distance = 0, cur_insn = PREV_INSN (insn);
13409        distance < PREDICT_DISTANCE - 6;
13410        distance += get_attr_length (cur_insn), cur_insn = PREV_INSN (cur_insn))
13411     if (!cur_insn || JUMP_P (cur_insn) || LABEL_P (cur_insn))
13412       return false;
13413
13414   rtx_code_label *new_label = gen_label_rtx ();
13415   uncond_jump = emit_jump_insn_after (
13416                   gen_rtx_SET (pc_rtx,
13417                                gen_rtx_LABEL_REF (VOIDmode, code_label)),
13418                   insn);
13419   emit_label_after (new_label, uncond_jump);
13420
13421   tmp = XEXP (SET_SRC (set), 1);
13422   XEXP (SET_SRC (set), 1) = XEXP (SET_SRC (set), 2);
13423   XEXP (SET_SRC (set), 2) = tmp;
13424   INSN_CODE (insn) = -1;
13425
13426   XEXP (label_ref, 0) = new_label;
13427   JUMP_LABEL (insn) = new_label;
13428   JUMP_LABEL (uncond_jump) = code_label;
13429
13430   return true;
13431 }
13432
13433 /* Returns 1 if INSN reads the value of REG for purposes not related
13434    to addressing of memory, and 0 otherwise.  */
13435 static int
13436 s390_non_addr_reg_read_p (rtx reg, rtx_insn *insn)
13437 {
13438   return reg_referenced_p (reg, PATTERN (insn))
13439     && !reg_used_in_mem_p (REGNO (reg), PATTERN (insn));
13440 }
13441
13442 /* Starting from INSN find_cond_jump looks downwards in the insn
13443    stream for a single jump insn which is the last user of the
13444    condition code set in INSN.  */
13445 static rtx_insn *
13446 find_cond_jump (rtx_insn *insn)
13447 {
13448   for (; insn; insn = NEXT_INSN (insn))
13449     {
13450       rtx ite, cc;
13451
13452       if (LABEL_P (insn))
13453         break;
13454
13455       if (!JUMP_P (insn))
13456         {
13457           if (reg_mentioned_p (gen_rtx_REG (CCmode, CC_REGNUM), insn))
13458             break;
13459           continue;
13460         }
13461
13462       /* This will be triggered by a return.  */
13463       if (GET_CODE (PATTERN (insn)) != SET)
13464         break;
13465
13466       gcc_assert (SET_DEST (PATTERN (insn)) == pc_rtx);
13467       ite = SET_SRC (PATTERN (insn));
13468
13469       if (GET_CODE (ite) != IF_THEN_ELSE)
13470         break;
13471
13472       cc = XEXP (XEXP (ite, 0), 0);
13473       if (!REG_P (cc) || !CC_REGNO_P (REGNO (cc)))
13474         break;
13475
13476       if (find_reg_note (insn, REG_DEAD, cc))
13477         return insn;
13478       break;
13479     }
13480
13481   return NULL;
13482 }
13483
13484 /* Swap the condition in COND and the operands in OP0 and OP1 so that
13485    the semantics does not change.  If NULL_RTX is passed as COND the
13486    function tries to find the conditional jump starting with INSN.  */
13487 static void
13488 s390_swap_cmp (rtx cond, rtx *op0, rtx *op1, rtx_insn *insn)
13489 {
13490   rtx tmp = *op0;
13491
13492   if (cond == NULL_RTX)
13493     {
13494       rtx_insn *jump = find_cond_jump (NEXT_INSN (insn));
13495       rtx set = jump ? single_set (jump) : NULL_RTX;
13496
13497       if (set == NULL_RTX)
13498         return;
13499
13500       cond = XEXP (SET_SRC (set), 0);
13501     }
13502
13503   *op0 = *op1;
13504   *op1 = tmp;
13505   PUT_CODE (cond, swap_condition (GET_CODE (cond)));
13506 }
13507
13508 /* On z10, instructions of the compare-and-branch family have the
13509    property to access the register occurring as second operand with
13510    its bits complemented.  If such a compare is grouped with a second
13511    instruction that accesses the same register non-complemented, and
13512    if that register's value is delivered via a bypass, then the
13513    pipeline recycles, thereby causing significant performance decline.
13514    This function locates such situations and exchanges the two
13515    operands of the compare.  The function return true whenever it
13516    added an insn.  */
13517 static bool
13518 s390_z10_optimize_cmp (rtx_insn *insn)
13519 {
13520   rtx_insn *prev_insn, *next_insn;
13521   bool insn_added_p = false;
13522   rtx cond, *op0, *op1;
13523
13524   if (GET_CODE (PATTERN (insn)) == PARALLEL)
13525     {
13526       /* Handle compare and branch and branch on count
13527          instructions.  */
13528       rtx pattern = single_set (insn);
13529
13530       if (!pattern
13531           || SET_DEST (pattern) != pc_rtx
13532           || GET_CODE (SET_SRC (pattern)) != IF_THEN_ELSE)
13533         return false;
13534
13535       cond = XEXP (SET_SRC (pattern), 0);
13536       op0 = &XEXP (cond, 0);
13537       op1 = &XEXP (cond, 1);
13538     }
13539   else if (GET_CODE (PATTERN (insn)) == SET)
13540     {
13541       rtx src, dest;
13542
13543       /* Handle normal compare instructions.  */
13544       src = SET_SRC (PATTERN (insn));
13545       dest = SET_DEST (PATTERN (insn));
13546
13547       if (!REG_P (dest)
13548           || !CC_REGNO_P (REGNO (dest))
13549           || GET_CODE (src) != COMPARE)
13550         return false;
13551
13552       /* s390_swap_cmp will try to find the conditional
13553          jump when passing NULL_RTX as condition.  */
13554       cond = NULL_RTX;
13555       op0 = &XEXP (src, 0);
13556       op1 = &XEXP (src, 1);
13557     }
13558   else
13559     return false;
13560
13561   if (!REG_P (*op0) || !REG_P (*op1))
13562     return false;
13563
13564   if (GET_MODE_CLASS (GET_MODE (*op0)) != MODE_INT)
13565     return false;
13566
13567   /* Swap the COMPARE arguments and its mask if there is a
13568      conflicting access in the previous insn.  */
13569   prev_insn = prev_active_insn (insn);
13570   if (prev_insn != NULL_RTX && INSN_P (prev_insn)
13571       && reg_referenced_p (*op1, PATTERN (prev_insn)))
13572     s390_swap_cmp (cond, op0, op1, insn);
13573
13574   /* Check if there is a conflict with the next insn. If there
13575      was no conflict with the previous insn, then swap the
13576      COMPARE arguments and its mask.  If we already swapped
13577      the operands, or if swapping them would cause a conflict
13578      with the previous insn, issue a NOP after the COMPARE in
13579      order to separate the two instuctions.  */
13580   next_insn = next_active_insn (insn);
13581   if (next_insn != NULL_RTX && INSN_P (next_insn)
13582       && s390_non_addr_reg_read_p (*op1, next_insn))
13583     {
13584       if (prev_insn != NULL_RTX && INSN_P (prev_insn)
13585           && s390_non_addr_reg_read_p (*op0, prev_insn))
13586         {
13587           if (REGNO (*op1) == 0)
13588             emit_insn_after (gen_nop1 (), insn);
13589           else
13590             emit_insn_after (gen_nop (), insn);
13591           insn_added_p = true;
13592         }
13593       else
13594         s390_swap_cmp (cond, op0, op1, insn);
13595     }
13596   return insn_added_p;
13597 }
13598
13599 /* Number of INSNs to be scanned backward in the last BB of the loop
13600    and forward in the first BB of the loop.  This usually should be a
13601    bit more than the number of INSNs which could go into one
13602    group.  */
13603 #define S390_OSC_SCAN_INSN_NUM 5
13604
13605 /* Scan LOOP for static OSC collisions and return true if a osc_break
13606    should be issued for this loop.  */
13607 static bool
13608 s390_adjust_loop_scan_osc (struct loop* loop)
13609
13610 {
13611   HARD_REG_SET modregs, newregs;
13612   rtx_insn *insn, *store_insn = NULL;
13613   rtx set;
13614   struct s390_address addr_store, addr_load;
13615   subrtx_iterator::array_type array;
13616   int insn_count;
13617
13618   CLEAR_HARD_REG_SET (modregs);
13619
13620   insn_count = 0;
13621   FOR_BB_INSNS_REVERSE (loop->latch, insn)
13622     {
13623       if (!INSN_P (insn) || INSN_CODE (insn) <= 0)
13624         continue;
13625
13626       insn_count++;
13627       if (insn_count > S390_OSC_SCAN_INSN_NUM)
13628         return false;
13629
13630       find_all_hard_reg_sets (insn, &newregs, true);
13631       IOR_HARD_REG_SET (modregs, newregs);
13632
13633       set = single_set (insn);
13634       if (!set)
13635         continue;
13636
13637       if (MEM_P (SET_DEST (set))
13638           && s390_decompose_address (XEXP (SET_DEST (set), 0), &addr_store))
13639         {
13640           store_insn = insn;
13641           break;
13642         }
13643     }
13644
13645   if (store_insn == NULL_RTX)
13646     return false;
13647
13648   insn_count = 0;
13649   FOR_BB_INSNS (loop->header, insn)
13650     {
13651       if (!INSN_P (insn) || INSN_CODE (insn) <= 0)
13652         continue;
13653
13654       if (insn == store_insn)
13655         return false;
13656
13657       insn_count++;
13658       if (insn_count > S390_OSC_SCAN_INSN_NUM)
13659         return false;
13660
13661       find_all_hard_reg_sets (insn, &newregs, true);
13662       IOR_HARD_REG_SET (modregs, newregs);
13663
13664       set = single_set (insn);
13665       if (!set)
13666         continue;
13667
13668       /* An intermediate store disrupts static OSC checking
13669          anyway.  */
13670       if (MEM_P (SET_DEST (set))
13671           && s390_decompose_address (XEXP (SET_DEST (set), 0), NULL))
13672         return false;
13673
13674       FOR_EACH_SUBRTX (iter, array, SET_SRC (set), NONCONST)
13675         if (MEM_P (*iter)
13676             && s390_decompose_address (XEXP (*iter, 0), &addr_load)
13677             && rtx_equal_p (addr_load.base, addr_store.base)
13678             && rtx_equal_p (addr_load.indx, addr_store.indx)
13679             && rtx_equal_p (addr_load.disp, addr_store.disp))
13680           {
13681             if ((addr_load.base != NULL_RTX
13682                  && TEST_HARD_REG_BIT (modregs, REGNO (addr_load.base)))
13683                 || (addr_load.indx != NULL_RTX
13684                     && TEST_HARD_REG_BIT (modregs, REGNO (addr_load.indx))))
13685               return true;
13686           }
13687     }
13688   return false;
13689 }
13690
13691 /* Look for adjustments which can be done on simple innermost
13692    loops.  */
13693 static void
13694 s390_adjust_loops ()
13695 {
13696   struct loop *loop = NULL;
13697
13698   df_analyze ();
13699   compute_bb_for_insn ();
13700
13701   /* Find the loops.  */
13702   loop_optimizer_init (AVOID_CFG_MODIFICATIONS);
13703
13704   FOR_EACH_LOOP (loop, LI_ONLY_INNERMOST)
13705     {
13706       if (dump_file)
13707         {
13708           flow_loop_dump (loop, dump_file, NULL, 0);
13709           fprintf (dump_file, ";;  OSC loop scan Loop: ");
13710         }
13711       if (loop->latch == NULL
13712           || pc_set (BB_END (loop->latch)) == NULL_RTX
13713           || !s390_adjust_loop_scan_osc (loop))
13714         {
13715           if (dump_file)
13716             {
13717               if (loop->latch == NULL)
13718                 fprintf (dump_file, " muliple backward jumps\n");
13719               else
13720                 {
13721                   fprintf (dump_file, " header insn: %d latch insn: %d ",
13722                            INSN_UID (BB_HEAD (loop->header)),
13723                            INSN_UID (BB_END (loop->latch)));
13724                   if (pc_set (BB_END (loop->latch)) == NULL_RTX)
13725                     fprintf (dump_file, " loop does not end with jump\n");
13726                   else
13727                     fprintf (dump_file, " not instrumented\n");
13728                 }
13729             }
13730         }
13731       else
13732         {
13733           rtx_insn *new_insn;
13734
13735           if (dump_file)
13736             fprintf (dump_file, " adding OSC break insn: ");
13737           new_insn = emit_insn_before (gen_osc_break (),
13738                                        BB_END (loop->latch));
13739           INSN_ADDRESSES_NEW (new_insn, -1);
13740         }
13741     }
13742
13743   loop_optimizer_finalize ();
13744
13745   df_finish_pass (false);
13746 }
13747
13748 /* Perform machine-dependent processing.  */
13749
13750 static void
13751 s390_reorg (void)
13752 {
13753   bool pool_overflow = false;
13754   int hw_before, hw_after;
13755
13756   if (s390_tune == PROCESSOR_2964_Z13)
13757     s390_adjust_loops ();
13758
13759   /* Make sure all splits have been performed; splits after
13760      machine_dependent_reorg might confuse insn length counts.  */
13761   split_all_insns_noflow ();
13762
13763   /* Install the main literal pool and the associated base
13764      register load insns.
13765
13766      In addition, there are two problematic situations we need
13767      to correct:
13768
13769      - the literal pool might be > 4096 bytes in size, so that
13770        some of its elements cannot be directly accessed
13771
13772      - a branch target might be > 64K away from the branch, so that
13773        it is not possible to use a PC-relative instruction.
13774
13775      To fix those, we split the single literal pool into multiple
13776      pool chunks, reloading the pool base register at various
13777      points throughout the function to ensure it always points to
13778      the pool chunk the following code expects, and / or replace
13779      PC-relative branches by absolute branches.
13780
13781      However, the two problems are interdependent: splitting the
13782      literal pool can move a branch further away from its target,
13783      causing the 64K limit to overflow, and on the other hand,
13784      replacing a PC-relative branch by an absolute branch means
13785      we need to put the branch target address into the literal
13786      pool, possibly causing it to overflow.
13787
13788      So, we loop trying to fix up both problems until we manage
13789      to satisfy both conditions at the same time.  Note that the
13790      loop is guaranteed to terminate as every pass of the loop
13791      strictly decreases the total number of PC-relative branches
13792      in the function.  (This is not completely true as there
13793      might be branch-over-pool insns introduced by chunkify_start.
13794      Those never need to be split however.)  */
13795
13796   for (;;)
13797     {
13798       struct constant_pool *pool = NULL;
13799
13800       /* Collect the literal pool.  */
13801       if (!pool_overflow)
13802         {
13803           pool = s390_mainpool_start ();
13804           if (!pool)
13805             pool_overflow = true;
13806         }
13807
13808       /* If literal pool overflowed, start to chunkify it.  */
13809       if (pool_overflow)
13810         pool = s390_chunkify_start ();
13811
13812       /* Split out-of-range branches.  If this has created new
13813          literal pool entries, cancel current chunk list and
13814          recompute it.  zSeries machines have large branch
13815          instructions, so we never need to split a branch.  */
13816       if (!TARGET_CPU_ZARCH && s390_split_branches ())
13817         {
13818           if (pool_overflow)
13819             s390_chunkify_cancel (pool);
13820           else
13821             s390_mainpool_cancel (pool);
13822
13823           continue;
13824         }
13825
13826       /* If we made it up to here, both conditions are satisfied.
13827          Finish up literal pool related changes.  */
13828       if (pool_overflow)
13829         s390_chunkify_finish (pool);
13830       else
13831         s390_mainpool_finish (pool);
13832
13833       /* We're done splitting branches.  */
13834       cfun->machine->split_branches_pending_p = false;
13835       break;
13836     }
13837
13838   /* Generate out-of-pool execute target insns.  */
13839   if (TARGET_CPU_ZARCH)
13840     {
13841       rtx_insn *insn, *target;
13842       rtx label;
13843
13844       for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
13845         {
13846           label = s390_execute_label (insn);
13847           if (!label)
13848             continue;
13849
13850           gcc_assert (label != const0_rtx);
13851
13852           target = emit_label (XEXP (label, 0));
13853           INSN_ADDRESSES_NEW (target, -1);
13854
13855           target = emit_insn (s390_execute_target (insn));
13856           INSN_ADDRESSES_NEW (target, -1);
13857         }
13858     }
13859
13860   /* Try to optimize prologue and epilogue further.  */
13861   s390_optimize_prologue ();
13862
13863   /* Walk over the insns and do some >=z10 specific changes.  */
13864   if (s390_tune >= PROCESSOR_2097_Z10)
13865     {
13866       rtx_insn *insn;
13867       bool insn_added_p = false;
13868
13869       /* The insn lengths and addresses have to be up to date for the
13870          following manipulations.  */
13871       shorten_branches (get_insns ());
13872
13873       for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
13874         {
13875           if (!INSN_P (insn) || INSN_CODE (insn) <= 0)
13876             continue;
13877
13878           if (JUMP_P (insn))
13879             insn_added_p |= s390_fix_long_loop_prediction (insn);
13880
13881           if ((GET_CODE (PATTERN (insn)) == PARALLEL
13882                || GET_CODE (PATTERN (insn)) == SET)
13883               && s390_tune == PROCESSOR_2097_Z10)
13884             insn_added_p |= s390_z10_optimize_cmp (insn);
13885         }
13886
13887       /* Adjust branches if we added new instructions.  */
13888       if (insn_added_p)
13889         shorten_branches (get_insns ());
13890     }
13891
13892   s390_function_num_hotpatch_hw (current_function_decl, &hw_before, &hw_after);
13893   if (hw_after > 0)
13894     {
13895       rtx_insn *insn;
13896
13897       /* Insert NOPs for hotpatching. */
13898       for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
13899         /* Emit NOPs
13900             1. inside the area covered by debug information to allow setting
13901                breakpoints at the NOPs,
13902             2. before any insn which results in an asm instruction,
13903             3. before in-function labels to avoid jumping to the NOPs, for
13904                example as part of a loop,
13905             4. before any barrier in case the function is completely empty
13906                (__builtin_unreachable ()) and has neither internal labels nor
13907                active insns.
13908         */
13909         if (active_insn_p (insn) || BARRIER_P (insn) || LABEL_P (insn))
13910           break;
13911       /* Output a series of NOPs before the first active insn.  */
13912       while (insn && hw_after > 0)
13913         {
13914           if (hw_after >= 3 && TARGET_CPU_ZARCH)
13915             {
13916               emit_insn_before (gen_nop_6_byte (), insn);
13917               hw_after -= 3;
13918             }
13919           else if (hw_after >= 2)
13920             {
13921               emit_insn_before (gen_nop_4_byte (), insn);
13922               hw_after -= 2;
13923             }
13924           else
13925             {
13926               emit_insn_before (gen_nop_2_byte (), insn);
13927               hw_after -= 1;
13928             }
13929         }
13930     }
13931 }
13932
13933 /* Return true if INSN is a fp load insn writing register REGNO.  */
13934 static inline bool
13935 s390_fpload_toreg (rtx_insn *insn, unsigned int regno)
13936 {
13937   rtx set;
13938   enum attr_type flag = s390_safe_attr_type (insn);
13939
13940   if (flag != TYPE_FLOADSF && flag != TYPE_FLOADDF)
13941     return false;
13942
13943   set = single_set (insn);
13944
13945   if (set == NULL_RTX)
13946     return false;
13947
13948   if (!REG_P (SET_DEST (set)) || !MEM_P (SET_SRC (set)))
13949     return false;
13950
13951   if (REGNO (SET_DEST (set)) != regno)
13952     return false;
13953
13954   return true;
13955 }
13956
13957 /* This value describes the distance to be avoided between an
13958    aritmetic fp instruction and an fp load writing the same register.
13959    Z10_EARLYLOAD_DISTANCE - 1 as well as Z10_EARLYLOAD_DISTANCE + 1 is
13960    fine but the exact value has to be avoided. Otherwise the FP
13961    pipeline will throw an exception causing a major penalty.  */
13962 #define Z10_EARLYLOAD_DISTANCE 7
13963
13964 /* Rearrange the ready list in order to avoid the situation described
13965    for Z10_EARLYLOAD_DISTANCE.  A problematic load instruction is
13966    moved to the very end of the ready list.  */
13967 static void
13968 s390_z10_prevent_earlyload_conflicts (rtx_insn **ready, int *nready_p)
13969 {
13970   unsigned int regno;
13971   int nready = *nready_p;
13972   rtx_insn *tmp;
13973   int i;
13974   rtx_insn *insn;
13975   rtx set;
13976   enum attr_type flag;
13977   int distance;
13978
13979   /* Skip DISTANCE - 1 active insns.  */
13980   for (insn = last_scheduled_insn, distance = Z10_EARLYLOAD_DISTANCE - 1;
13981        distance > 0 && insn != NULL_RTX;
13982        distance--, insn = prev_active_insn (insn))
13983     if (CALL_P (insn) || JUMP_P (insn))
13984       return;
13985
13986   if (insn == NULL_RTX)
13987     return;
13988
13989   set = single_set (insn);
13990
13991   if (set == NULL_RTX || !REG_P (SET_DEST (set))
13992       || GET_MODE_CLASS (GET_MODE (SET_DEST (set))) != MODE_FLOAT)
13993     return;
13994
13995   flag = s390_safe_attr_type (insn);
13996
13997   if (flag == TYPE_FLOADSF || flag == TYPE_FLOADDF)
13998     return;
13999
14000   regno = REGNO (SET_DEST (set));
14001   i = nready - 1;
14002
14003   while (!s390_fpload_toreg (ready[i], regno) && i > 0)
14004     i--;
14005
14006   if (!i)
14007     return;
14008
14009   tmp = ready[i];
14010   memmove (&ready[1], &ready[0], sizeof (rtx_insn *) * i);
14011   ready[0] = tmp;
14012 }
14013
14014
14015 /* The s390_sched_state variable tracks the state of the current or
14016    the last instruction group.
14017
14018    0,1,2 number of instructions scheduled in the current group
14019    3     the last group is complete - normal insns
14020    4     the last group was a cracked/expanded insn */
14021
14022 static int s390_sched_state;
14023
14024 #define S390_SCHED_STATE_NORMAL  3
14025 #define S390_SCHED_STATE_CRACKED 4
14026
14027 #define S390_SCHED_ATTR_MASK_CRACKED    0x1
14028 #define S390_SCHED_ATTR_MASK_EXPANDED   0x2
14029 #define S390_SCHED_ATTR_MASK_ENDGROUP   0x4
14030 #define S390_SCHED_ATTR_MASK_GROUPALONE 0x8
14031
14032 static unsigned int
14033 s390_get_sched_attrmask (rtx_insn *insn)
14034 {
14035   unsigned int mask = 0;
14036
14037   switch (s390_tune)
14038     {
14039     case PROCESSOR_2827_ZEC12:
14040       if (get_attr_zEC12_cracked (insn))
14041         mask |= S390_SCHED_ATTR_MASK_CRACKED;
14042       if (get_attr_zEC12_expanded (insn))
14043         mask |= S390_SCHED_ATTR_MASK_EXPANDED;
14044       if (get_attr_zEC12_endgroup (insn))
14045         mask |= S390_SCHED_ATTR_MASK_ENDGROUP;
14046       if (get_attr_zEC12_groupalone (insn))
14047         mask |= S390_SCHED_ATTR_MASK_GROUPALONE;
14048       break;
14049     case PROCESSOR_2964_Z13:
14050     case PROCESSOR_ARCH12:
14051       if (get_attr_z13_cracked (insn))
14052         mask |= S390_SCHED_ATTR_MASK_CRACKED;
14053       if (get_attr_z13_expanded (insn))
14054         mask |= S390_SCHED_ATTR_MASK_EXPANDED;
14055       if (get_attr_z13_endgroup (insn))
14056         mask |= S390_SCHED_ATTR_MASK_ENDGROUP;
14057       if (get_attr_z13_groupalone (insn))
14058         mask |= S390_SCHED_ATTR_MASK_GROUPALONE;
14059       break;
14060     default:
14061       gcc_unreachable ();
14062     }
14063   return mask;
14064 }
14065
14066 static unsigned int
14067 s390_get_unit_mask (rtx_insn *insn, int *units)
14068 {
14069   unsigned int mask = 0;
14070
14071   switch (s390_tune)
14072     {
14073     case PROCESSOR_2964_Z13:
14074     case PROCESSOR_ARCH12:
14075       *units = 3;
14076       if (get_attr_z13_unit_lsu (insn))
14077         mask |= 1 << 0;
14078       if (get_attr_z13_unit_fxu (insn))
14079         mask |= 1 << 1;
14080       if (get_attr_z13_unit_vfu (insn))
14081         mask |= 1 << 2;
14082       break;
14083     default:
14084       gcc_unreachable ();
14085     }
14086   return mask;
14087 }
14088
14089 /* Return the scheduling score for INSN.  The higher the score the
14090    better.  The score is calculated from the OOO scheduling attributes
14091    of INSN and the scheduling state s390_sched_state.  */
14092 static int
14093 s390_sched_score (rtx_insn *insn)
14094 {
14095   unsigned int mask = s390_get_sched_attrmask (insn);
14096   int score = 0;
14097
14098   switch (s390_sched_state)
14099     {
14100     case 0:
14101       /* Try to put insns into the first slot which would otherwise
14102          break a group.  */
14103       if ((mask & S390_SCHED_ATTR_MASK_CRACKED) != 0
14104           || (mask & S390_SCHED_ATTR_MASK_EXPANDED) != 0)
14105         score += 5;
14106       if ((mask & S390_SCHED_ATTR_MASK_GROUPALONE) != 0)
14107         score += 10;
14108       /* fallthrough */
14109     case 1:
14110       /* Prefer not cracked insns while trying to put together a
14111          group.  */
14112       if ((mask & S390_SCHED_ATTR_MASK_CRACKED) == 0
14113           && (mask & S390_SCHED_ATTR_MASK_EXPANDED) == 0
14114           && (mask & S390_SCHED_ATTR_MASK_GROUPALONE) == 0)
14115         score += 10;
14116       if ((mask & S390_SCHED_ATTR_MASK_ENDGROUP) == 0)
14117         score += 5;
14118       break;
14119     case 2:
14120       /* Prefer not cracked insns while trying to put together a
14121          group.  */
14122       if ((mask & S390_SCHED_ATTR_MASK_CRACKED) == 0
14123           && (mask & S390_SCHED_ATTR_MASK_EXPANDED) == 0
14124           && (mask & S390_SCHED_ATTR_MASK_GROUPALONE) == 0)
14125         score += 10;
14126       /* Prefer endgroup insns in the last slot.  */
14127       if ((mask & S390_SCHED_ATTR_MASK_ENDGROUP) != 0)
14128         score += 10;
14129       break;
14130     case S390_SCHED_STATE_NORMAL:
14131       /* Prefer not cracked insns if the last was not cracked.  */
14132       if ((mask & S390_SCHED_ATTR_MASK_CRACKED) == 0
14133           && (mask & S390_SCHED_ATTR_MASK_EXPANDED) == 0)
14134         score += 5;
14135       if ((mask & S390_SCHED_ATTR_MASK_GROUPALONE) != 0)
14136         score += 10;
14137       break;
14138     case S390_SCHED_STATE_CRACKED:
14139       /* Try to keep cracked insns together to prevent them from
14140          interrupting groups.  */
14141       if ((mask & S390_SCHED_ATTR_MASK_CRACKED) != 0
14142           || (mask & S390_SCHED_ATTR_MASK_EXPANDED) != 0)
14143         score += 5;
14144       break;
14145     }
14146
14147   if (s390_tune >= PROCESSOR_2964_Z13)
14148     {
14149       int units, i;
14150       unsigned unit_mask, m = 1;
14151
14152       unit_mask = s390_get_unit_mask (insn, &units);
14153       gcc_assert (units <= MAX_SCHED_UNITS);
14154
14155       /* Add a score in range 0..MAX_SCHED_MIX_SCORE depending on how long
14156          ago the last insn of this unit type got scheduled.  This is
14157          supposed to help providing a proper instruction mix to the
14158          CPU.  */
14159       for (i = 0; i < units; i++, m <<= 1)
14160         if (m & unit_mask)
14161           score += (last_scheduled_unit_distance[i] * MAX_SCHED_MIX_SCORE /
14162                     MAX_SCHED_MIX_DISTANCE);
14163     }
14164   return score;
14165 }
14166
14167 /* This function is called via hook TARGET_SCHED_REORDER before
14168    issuing one insn from list READY which contains *NREADYP entries.
14169    For target z10 it reorders load instructions to avoid early load
14170    conflicts in the floating point pipeline  */
14171 static int
14172 s390_sched_reorder (FILE *file, int verbose,
14173                     rtx_insn **ready, int *nreadyp, int clock ATTRIBUTE_UNUSED)
14174 {
14175   if (s390_tune == PROCESSOR_2097_Z10
14176       && reload_completed
14177       && *nreadyp > 1)
14178     s390_z10_prevent_earlyload_conflicts (ready, nreadyp);
14179
14180   if (s390_tune >= PROCESSOR_2827_ZEC12
14181       && reload_completed
14182       && *nreadyp > 1)
14183     {
14184       int i;
14185       int last_index = *nreadyp - 1;
14186       int max_index = -1;
14187       int max_score = -1;
14188       rtx_insn *tmp;
14189
14190       /* Just move the insn with the highest score to the top (the
14191          end) of the list.  A full sort is not needed since a conflict
14192          in the hazard recognition cannot happen.  So the top insn in
14193          the ready list will always be taken.  */
14194       for (i = last_index; i >= 0; i--)
14195         {
14196           int score;
14197
14198           if (recog_memoized (ready[i]) < 0)
14199             continue;
14200
14201           score = s390_sched_score (ready[i]);
14202           if (score > max_score)
14203             {
14204               max_score = score;
14205               max_index = i;
14206             }
14207         }
14208
14209       if (max_index != -1)
14210         {
14211           if (max_index != last_index)
14212             {
14213               tmp = ready[max_index];
14214               ready[max_index] = ready[last_index];
14215               ready[last_index] = tmp;
14216
14217               if (verbose > 5)
14218                 fprintf (file,
14219                          ";;\t\tBACKEND: move insn %d to the top of list\n",
14220                          INSN_UID (ready[last_index]));
14221             }
14222           else if (verbose > 5)
14223             fprintf (file,
14224                      ";;\t\tBACKEND: best insn %d already on top\n",
14225                      INSN_UID (ready[last_index]));
14226         }
14227
14228       if (verbose > 5)
14229         {
14230           fprintf (file, "ready list ooo attributes - sched state: %d\n",
14231                    s390_sched_state);
14232
14233           for (i = last_index; i >= 0; i--)
14234             {
14235               unsigned int sched_mask;
14236               rtx_insn *insn = ready[i];
14237
14238               if (recog_memoized (insn) < 0)
14239                 continue;
14240
14241               sched_mask = s390_get_sched_attrmask (insn);
14242               fprintf (file, ";;\t\tBACKEND: insn %d score: %d: ",
14243                        INSN_UID (insn),
14244                        s390_sched_score (insn));
14245 #define PRINT_SCHED_ATTR(M, ATTR) fprintf (file, "%s ",\
14246                                            ((M) & sched_mask) ? #ATTR : "");
14247               PRINT_SCHED_ATTR (S390_SCHED_ATTR_MASK_CRACKED, cracked);
14248               PRINT_SCHED_ATTR (S390_SCHED_ATTR_MASK_EXPANDED, expanded);
14249               PRINT_SCHED_ATTR (S390_SCHED_ATTR_MASK_ENDGROUP, endgroup);
14250               PRINT_SCHED_ATTR (S390_SCHED_ATTR_MASK_GROUPALONE, groupalone);
14251 #undef PRINT_SCHED_ATTR
14252               if (s390_tune >= PROCESSOR_2964_Z13)
14253                 {
14254                   unsigned int unit_mask, m = 1;
14255                   int units, j;
14256
14257                   unit_mask  = s390_get_unit_mask (insn, &units);
14258                   fprintf (file, "(units:");
14259                   for (j = 0; j < units; j++, m <<= 1)
14260                     if (m & unit_mask)
14261                       fprintf (file, " u%d", j);
14262                   fprintf (file, ")");
14263                 }
14264               fprintf (file, "\n");
14265             }
14266         }
14267     }
14268
14269   return s390_issue_rate ();
14270 }
14271
14272
14273 /* This function is called via hook TARGET_SCHED_VARIABLE_ISSUE after
14274    the scheduler has issued INSN.  It stores the last issued insn into
14275    last_scheduled_insn in order to make it available for
14276    s390_sched_reorder.  */
14277 static int
14278 s390_sched_variable_issue (FILE *file, int verbose, rtx_insn *insn, int more)
14279 {
14280   last_scheduled_insn = insn;
14281
14282   if (s390_tune >= PROCESSOR_2827_ZEC12
14283       && reload_completed
14284       && recog_memoized (insn) >= 0)
14285     {
14286       unsigned int mask = s390_get_sched_attrmask (insn);
14287
14288       if ((mask & S390_SCHED_ATTR_MASK_CRACKED) != 0
14289           || (mask & S390_SCHED_ATTR_MASK_EXPANDED) != 0)
14290         s390_sched_state = S390_SCHED_STATE_CRACKED;
14291       else if ((mask & S390_SCHED_ATTR_MASK_ENDGROUP) != 0
14292                || (mask & S390_SCHED_ATTR_MASK_GROUPALONE) != 0)
14293         s390_sched_state = S390_SCHED_STATE_NORMAL;
14294       else
14295         {
14296           /* Only normal insns are left (mask == 0).  */
14297           switch (s390_sched_state)
14298             {
14299             case 0:
14300             case 1:
14301             case 2:
14302             case S390_SCHED_STATE_NORMAL:
14303               if (s390_sched_state == S390_SCHED_STATE_NORMAL)
14304                 s390_sched_state = 1;
14305               else
14306                 s390_sched_state++;
14307
14308               break;
14309             case S390_SCHED_STATE_CRACKED:
14310               s390_sched_state = S390_SCHED_STATE_NORMAL;
14311               break;
14312             }
14313         }
14314
14315       if (s390_tune >= PROCESSOR_2964_Z13)
14316         {
14317           int units, i;
14318           unsigned unit_mask, m = 1;
14319
14320           unit_mask = s390_get_unit_mask (insn, &units);
14321           gcc_assert (units <= MAX_SCHED_UNITS);
14322
14323           for (i = 0; i < units; i++, m <<= 1)
14324             if (m & unit_mask)
14325               last_scheduled_unit_distance[i] = 0;
14326             else if (last_scheduled_unit_distance[i] < MAX_SCHED_MIX_DISTANCE)
14327               last_scheduled_unit_distance[i]++;
14328         }
14329
14330       if (verbose > 5)
14331         {
14332           unsigned int sched_mask;
14333
14334           sched_mask = s390_get_sched_attrmask (insn);
14335
14336           fprintf (file, ";;\t\tBACKEND: insn %d: ", INSN_UID (insn));
14337 #define PRINT_SCHED_ATTR(M, ATTR) fprintf (file, "%s ", ((M) & sched_mask) ? #ATTR : "");
14338           PRINT_SCHED_ATTR (S390_SCHED_ATTR_MASK_CRACKED, cracked);
14339           PRINT_SCHED_ATTR (S390_SCHED_ATTR_MASK_EXPANDED, expanded);
14340           PRINT_SCHED_ATTR (S390_SCHED_ATTR_MASK_ENDGROUP, endgroup);
14341           PRINT_SCHED_ATTR (S390_SCHED_ATTR_MASK_GROUPALONE, groupalone);
14342 #undef PRINT_SCHED_ATTR
14343
14344           if (s390_tune >= PROCESSOR_2964_Z13)
14345             {
14346               unsigned int unit_mask, m = 1;
14347               int units, j;
14348
14349               unit_mask  = s390_get_unit_mask (insn, &units);
14350               fprintf (file, "(units:");
14351               for (j = 0; j < units; j++, m <<= 1)
14352                 if (m & unit_mask)
14353                   fprintf (file, " %d", j);
14354               fprintf (file, ")");
14355             }
14356           fprintf (file, " sched state: %d\n", s390_sched_state);
14357
14358           if (s390_tune >= PROCESSOR_2964_Z13)
14359             {
14360               int units, j;
14361
14362               s390_get_unit_mask (insn, &units);
14363
14364               fprintf (file, ";;\t\tBACKEND: units unused for: ");
14365               for (j = 0; j < units; j++)
14366                 fprintf (file, "%d:%d ", j, last_scheduled_unit_distance[j]);
14367               fprintf (file, "\n");
14368             }
14369         }
14370     }
14371
14372   if (GET_CODE (PATTERN (insn)) != USE
14373       && GET_CODE (PATTERN (insn)) != CLOBBER)
14374     return more - 1;
14375   else
14376     return more;
14377 }
14378
14379 static void
14380 s390_sched_init (FILE *file ATTRIBUTE_UNUSED,
14381                  int verbose ATTRIBUTE_UNUSED,
14382                  int max_ready ATTRIBUTE_UNUSED)
14383 {
14384   last_scheduled_insn = NULL;
14385   memset (last_scheduled_unit_distance, 0, MAX_SCHED_UNITS * sizeof (int));
14386   s390_sched_state = 0;
14387 }
14388
14389 /* This target hook implementation for TARGET_LOOP_UNROLL_ADJUST calculates
14390    a new number struct loop *loop should be unrolled if tuned for cpus with
14391    a built-in stride prefetcher.
14392    The loop is analyzed for memory accesses by calling check_dpu for
14393    each rtx of the loop. Depending on the loop_depth and the amount of
14394    memory accesses a new number <=nunroll is returned to improve the
14395    behavior of the hardware prefetch unit.  */
14396 static unsigned
14397 s390_loop_unroll_adjust (unsigned nunroll, struct loop *loop)
14398 {
14399   basic_block *bbs;
14400   rtx_insn *insn;
14401   unsigned i;
14402   unsigned mem_count = 0;
14403
14404   if (s390_tune < PROCESSOR_2097_Z10)
14405     return nunroll;
14406
14407   /* Count the number of memory references within the loop body.  */
14408   bbs = get_loop_body (loop);
14409   subrtx_iterator::array_type array;
14410   for (i = 0; i < loop->num_nodes; i++)
14411     FOR_BB_INSNS (bbs[i], insn)
14412       if (INSN_P (insn) && INSN_CODE (insn) != -1)
14413         FOR_EACH_SUBRTX (iter, array, PATTERN (insn), NONCONST)
14414           if (MEM_P (*iter))
14415             mem_count += 1;
14416   free (bbs);
14417
14418   /* Prevent division by zero, and we do not need to adjust nunroll in this case.  */
14419   if (mem_count == 0)
14420     return nunroll;
14421
14422   switch (loop_depth(loop))
14423     {
14424     case 1:
14425       return MIN (nunroll, 28 / mem_count);
14426     case 2:
14427       return MIN (nunroll, 22 / mem_count);
14428     default:
14429       return MIN (nunroll, 16 / mem_count);
14430     }
14431 }
14432
14433 /* Restore the current options.  This is a hook function and also called
14434    internally.  */
14435
14436 static void
14437 s390_function_specific_restore (struct gcc_options *opts,
14438                                 struct cl_target_option *ptr ATTRIBUTE_UNUSED)
14439 {
14440   opts->x_s390_cost_pointer = (long)processor_table[opts->x_s390_tune].cost;
14441 }
14442
14443 static void
14444 s390_option_override_internal (bool main_args_p,
14445                                struct gcc_options *opts,
14446                                const struct gcc_options *opts_set)
14447 {
14448   const char *prefix;
14449   const char *suffix;
14450
14451   /* Set up prefix/suffix so the error messages refer to either the command
14452      line argument, or the attribute(target).  */
14453   if (main_args_p)
14454     {
14455       prefix = "-m";
14456       suffix = "";
14457     }
14458   else
14459     {
14460       prefix = "option(\"";
14461       suffix = "\")";
14462     }
14463
14464
14465   /* Architecture mode defaults according to ABI.  */
14466   if (!(opts_set->x_target_flags & MASK_ZARCH))
14467     {
14468       if (TARGET_64BIT)
14469         opts->x_target_flags |= MASK_ZARCH;
14470       else
14471         opts->x_target_flags &= ~MASK_ZARCH;
14472     }
14473
14474   /* Set the march default in case it hasn't been specified on cmdline.  */
14475   if (!opts_set->x_s390_arch)
14476     opts->x_s390_arch = PROCESSOR_2064_Z900;
14477   else if (opts->x_s390_arch == PROCESSOR_9672_G5
14478            || opts->x_s390_arch == PROCESSOR_9672_G6)
14479     warning (OPT_Wdeprecated, "%sarch=%s%s is deprecated and will be removed "
14480              "in future releases; use at least %sarch=z900%s",
14481              prefix, opts->x_s390_arch == PROCESSOR_9672_G5 ? "g5" : "g6",
14482              suffix, prefix, suffix);
14483
14484   opts->x_s390_arch_flags = processor_flags_table[(int) opts->x_s390_arch];
14485
14486   /* Determine processor to tune for.  */
14487   if (!opts_set->x_s390_tune)
14488     opts->x_s390_tune = opts->x_s390_arch;
14489   else if (opts->x_s390_tune == PROCESSOR_9672_G5
14490            || opts->x_s390_tune == PROCESSOR_9672_G6)
14491     warning (OPT_Wdeprecated, "%stune=%s%s is deprecated and will be removed "
14492              "in future releases; use at least %stune=z900%s",
14493              prefix, opts->x_s390_tune == PROCESSOR_9672_G5 ? "g5" : "g6",
14494              suffix, prefix, suffix);
14495
14496   opts->x_s390_tune_flags = processor_flags_table[opts->x_s390_tune];
14497
14498   /* Sanity checks.  */
14499   if (opts->x_s390_arch == PROCESSOR_NATIVE
14500       || opts->x_s390_tune == PROCESSOR_NATIVE)
14501     gcc_unreachable ();
14502   if (TARGET_ZARCH_P (opts->x_target_flags) && !TARGET_CPU_ZARCH_P (opts))
14503     error ("z/Architecture mode not supported on %s",
14504            processor_table[(int)opts->x_s390_arch].name);
14505   if (TARGET_64BIT && !TARGET_ZARCH_P (opts->x_target_flags))
14506     error ("64-bit ABI not supported in ESA/390 mode");
14507
14508   /* Enable hardware transactions if available and not explicitly
14509      disabled by user.  E.g. with -m31 -march=zEC12 -mzarch */
14510   if (!TARGET_OPT_HTM_P (opts_set->x_target_flags))
14511     {
14512       if (TARGET_CPU_HTM_P (opts) && TARGET_ZARCH_P (opts->x_target_flags))
14513         opts->x_target_flags |= MASK_OPT_HTM;
14514       else
14515         opts->x_target_flags &= ~MASK_OPT_HTM;
14516     }
14517
14518   if (TARGET_OPT_VX_P (opts_set->x_target_flags))
14519     {
14520       if (TARGET_OPT_VX_P (opts->x_target_flags))
14521         {
14522           if (!TARGET_CPU_VX_P (opts))
14523             error ("hardware vector support not available on %s",
14524                    processor_table[(int)opts->x_s390_arch].name);
14525           if (TARGET_SOFT_FLOAT_P (opts->x_target_flags))
14526             error ("hardware vector support not available with -msoft-float");
14527         }
14528     }
14529   else
14530     {
14531       if (TARGET_CPU_VX_P (opts))
14532         /* Enable vector support if available and not explicitly disabled
14533            by user.  E.g. with -m31 -march=z13 -mzarch */
14534         opts->x_target_flags |= MASK_OPT_VX;
14535       else
14536         opts->x_target_flags &= ~MASK_OPT_VX;
14537     }
14538
14539   /* Use hardware DFP if available and not explicitly disabled by
14540      user. E.g. with -m31 -march=z10 -mzarch   */
14541   if (!TARGET_HARD_DFP_P (opts_set->x_target_flags))
14542     {
14543       if (TARGET_DFP_P (opts))
14544         opts->x_target_flags |= MASK_HARD_DFP;
14545       else
14546         opts->x_target_flags &= ~MASK_HARD_DFP;
14547     }
14548
14549   if (TARGET_HARD_DFP_P (opts->x_target_flags) && !TARGET_DFP_P (opts))
14550     {
14551       if (TARGET_HARD_DFP_P (opts_set->x_target_flags))
14552         {
14553           if (!TARGET_CPU_DFP_P (opts))
14554             error ("hardware decimal floating point instructions"
14555                    " not available on %s",
14556                    processor_table[(int)opts->x_s390_arch].name);
14557           if (!TARGET_ZARCH_P (opts->x_target_flags))
14558             error ("hardware decimal floating point instructions"
14559                    " not available in ESA/390 mode");
14560         }
14561       else
14562         opts->x_target_flags &= ~MASK_HARD_DFP;
14563     }
14564
14565   if (TARGET_SOFT_FLOAT_P (opts_set->x_target_flags)
14566       && TARGET_SOFT_FLOAT_P (opts->x_target_flags))
14567     {
14568       if (TARGET_HARD_DFP_P (opts_set->x_target_flags)
14569           && TARGET_HARD_DFP_P (opts->x_target_flags))
14570         error ("-mhard-dfp can%'t be used in conjunction with -msoft-float");
14571
14572       opts->x_target_flags &= ~MASK_HARD_DFP;
14573     }
14574
14575   if (TARGET_BACKCHAIN_P (opts->x_target_flags)
14576       && TARGET_PACKED_STACK_P (opts->x_target_flags)
14577       && TARGET_HARD_FLOAT_P (opts->x_target_flags))
14578     error ("-mbackchain -mpacked-stack -mhard-float are not supported "
14579            "in combination");
14580
14581   if (opts->x_s390_stack_size)
14582     {
14583       if (opts->x_s390_stack_guard >= opts->x_s390_stack_size)
14584         error ("stack size must be greater than the stack guard value");
14585       else if (opts->x_s390_stack_size > 1 << 16)
14586         error ("stack size must not be greater than 64k");
14587     }
14588   else if (opts->x_s390_stack_guard)
14589     error ("-mstack-guard implies use of -mstack-size");
14590
14591 #ifdef TARGET_DEFAULT_LONG_DOUBLE_128
14592   if (!TARGET_LONG_DOUBLE_128_P (opts_set->x_target_flags))
14593     opts->x_target_flags |= MASK_LONG_DOUBLE_128;
14594 #endif
14595
14596   if (opts->x_s390_tune >= PROCESSOR_2097_Z10)
14597     {
14598       maybe_set_param_value (PARAM_MAX_UNROLLED_INSNS, 100,
14599                              opts->x_param_values,
14600                              opts_set->x_param_values);
14601       maybe_set_param_value (PARAM_MAX_UNROLL_TIMES, 32,
14602                              opts->x_param_values,
14603                              opts_set->x_param_values);
14604       maybe_set_param_value (PARAM_MAX_COMPLETELY_PEELED_INSNS, 2000,
14605                              opts->x_param_values,
14606                              opts_set->x_param_values);
14607       maybe_set_param_value (PARAM_MAX_COMPLETELY_PEEL_TIMES, 64,
14608                              opts->x_param_values,
14609                              opts_set->x_param_values);
14610     }
14611
14612   maybe_set_param_value (PARAM_MAX_PENDING_LIST_LENGTH, 256,
14613                          opts->x_param_values,
14614                          opts_set->x_param_values);
14615   /* values for loop prefetching */
14616   maybe_set_param_value (PARAM_L1_CACHE_LINE_SIZE, 256,
14617                          opts->x_param_values,
14618                          opts_set->x_param_values);
14619   maybe_set_param_value (PARAM_L1_CACHE_SIZE, 128,
14620                          opts->x_param_values,
14621                          opts_set->x_param_values);
14622   /* s390 has more than 2 levels and the size is much larger.  Since
14623      we are always running virtualized assume that we only get a small
14624      part of the caches above l1.  */
14625   maybe_set_param_value (PARAM_L2_CACHE_SIZE, 1500,
14626                          opts->x_param_values,
14627                          opts_set->x_param_values);
14628   maybe_set_param_value (PARAM_PREFETCH_MIN_INSN_TO_MEM_RATIO, 2,
14629                          opts->x_param_values,
14630                          opts_set->x_param_values);
14631   maybe_set_param_value (PARAM_SIMULTANEOUS_PREFETCHES, 6,
14632                          opts->x_param_values,
14633                          opts_set->x_param_values);
14634
14635   /* Use the alternative scheduling-pressure algorithm by default.  */
14636   maybe_set_param_value (PARAM_SCHED_PRESSURE_ALGORITHM, 2,
14637                          opts->x_param_values,
14638                          opts_set->x_param_values);
14639
14640   maybe_set_param_value (PARAM_MIN_VECT_LOOP_BOUND, 2,
14641                          opts->x_param_values,
14642                          opts_set->x_param_values);
14643
14644   /* Call target specific restore function to do post-init work.  At the moment,
14645      this just sets opts->x_s390_cost_pointer.  */
14646   s390_function_specific_restore (opts, NULL);
14647 }
14648
14649 static void
14650 s390_option_override (void)
14651 {
14652   unsigned int i;
14653   cl_deferred_option *opt;
14654   vec<cl_deferred_option> *v =
14655     (vec<cl_deferred_option> *) s390_deferred_options;
14656
14657   if (v)
14658     FOR_EACH_VEC_ELT (*v, i, opt)
14659       {
14660         switch (opt->opt_index)
14661           {
14662           case OPT_mhotpatch_:
14663             {
14664               int val1;
14665               int val2;
14666               char s[256];
14667               char *t;
14668
14669               strncpy (s, opt->arg, 256);
14670               s[255] = 0;
14671               t = strchr (s, ',');
14672               if (t != NULL)
14673                 {
14674                   *t = 0;
14675                   t++;
14676                   val1 = integral_argument (s);
14677                   val2 = integral_argument (t);
14678                 }
14679               else
14680                 {
14681                   val1 = -1;
14682                   val2 = -1;
14683                 }
14684               if (val1 == -1 || val2 == -1)
14685                 {
14686                   /* argument is not a plain number */
14687                   error ("arguments to %qs should be non-negative integers",
14688                          "-mhotpatch=n,m");
14689                   break;
14690                 }
14691               else if (val1 > s390_hotpatch_hw_max
14692                        || val2 > s390_hotpatch_hw_max)
14693                 {
14694                   error ("argument to %qs is too large (max. %d)",
14695                          "-mhotpatch=n,m", s390_hotpatch_hw_max);
14696                   break;
14697                 }
14698               s390_hotpatch_hw_before_label = val1;
14699               s390_hotpatch_hw_after_label = val2;
14700               break;
14701             }
14702           default:
14703             gcc_unreachable ();
14704           }
14705       }
14706
14707   /* Set up function hooks.  */
14708   init_machine_status = s390_init_machine_status;
14709
14710   s390_option_override_internal (true, &global_options, &global_options_set);
14711
14712   /* Save the initial options in case the user does function specific
14713      options.  */
14714   target_option_default_node = build_target_option_node (&global_options);
14715   target_option_current_node = target_option_default_node;
14716
14717   /* This cannot reside in s390_option_optimization_table since HAVE_prefetch
14718      requires the arch flags to be evaluated already.  Since prefetching
14719      is beneficial on s390, we enable it if available.  */
14720   if (flag_prefetch_loop_arrays < 0 && HAVE_prefetch && optimize >= 3)
14721     flag_prefetch_loop_arrays = 1;
14722
14723   if (TARGET_TPF)
14724     {
14725       /* Don't emit DWARF3/4 unless specifically selected.  The TPF
14726          debuggers do not yet support DWARF 3/4.  */
14727       if (!global_options_set.x_dwarf_strict) 
14728         dwarf_strict = 1;
14729       if (!global_options_set.x_dwarf_version)
14730         dwarf_version = 2;
14731     }
14732
14733   /* Register a target-specific optimization-and-lowering pass
14734      to run immediately before prologue and epilogue generation.
14735
14736      Registering the pass must be done at start up.  It's
14737      convenient to do it here.  */
14738   opt_pass *new_pass = new pass_s390_early_mach (g);
14739   struct register_pass_info insert_pass_s390_early_mach =
14740     {
14741       new_pass,                 /* pass */
14742       "pro_and_epilogue",       /* reference_pass_name */
14743       1,                        /* ref_pass_instance_number */
14744       PASS_POS_INSERT_BEFORE    /* po_op */
14745     };
14746   register_pass (&insert_pass_s390_early_mach);
14747 }
14748
14749 #if S390_USE_TARGET_ATTRIBUTE
14750 /* Inner function to process the attribute((target(...))), take an argument and
14751    set the current options from the argument. If we have a list, recursively go
14752    over the list.  */
14753
14754 static bool
14755 s390_valid_target_attribute_inner_p (tree args,
14756                                      struct gcc_options *opts,
14757                                      struct gcc_options *new_opts_set,
14758                                      bool force_pragma)
14759 {
14760   char *next_optstr;
14761   bool ret = true;
14762
14763 #define S390_ATTRIB(S,O,A)  { S, sizeof (S)-1, O, A, 0 }
14764 #define S390_PRAGMA(S,O,A)  { S, sizeof (S)-1, O, A, 1 }
14765   static const struct
14766   {
14767     const char *string;
14768     size_t len;
14769     int opt;
14770     int has_arg;
14771     int only_as_pragma;
14772   } attrs[] = {
14773     /* enum options */
14774     S390_ATTRIB ("arch=", OPT_march_, 1),
14775     S390_ATTRIB ("tune=", OPT_mtune_, 1),
14776     /* uinteger options */
14777     S390_ATTRIB ("stack-guard=", OPT_mstack_guard_, 1),
14778     S390_ATTRIB ("stack-size=", OPT_mstack_size_, 1),
14779     S390_ATTRIB ("branch-cost=", OPT_mbranch_cost_, 1),
14780     S390_ATTRIB ("warn-framesize=", OPT_mwarn_framesize_, 1),
14781     /* flag options */
14782     S390_ATTRIB ("backchain", OPT_mbackchain, 0),
14783     S390_ATTRIB ("hard-dfp", OPT_mhard_dfp, 0),
14784     S390_ATTRIB ("hard-float", OPT_mhard_float, 0),
14785     S390_ATTRIB ("htm", OPT_mhtm, 0),
14786     S390_ATTRIB ("vx", OPT_mvx, 0),
14787     S390_ATTRIB ("packed-stack", OPT_mpacked_stack, 0),
14788     S390_ATTRIB ("small-exec", OPT_msmall_exec, 0),
14789     S390_ATTRIB ("soft-float", OPT_msoft_float, 0),
14790     S390_ATTRIB ("mvcle", OPT_mmvcle, 0),
14791     S390_PRAGMA ("zvector", OPT_mzvector, 0),
14792     /* boolean options */
14793     S390_ATTRIB ("warn-dynamicstack", OPT_mwarn_dynamicstack, 0),
14794   };
14795 #undef S390_ATTRIB
14796 #undef S390_PRAGMA
14797
14798   /* If this is a list, recurse to get the options.  */
14799   if (TREE_CODE (args) == TREE_LIST)
14800     {
14801       bool ret = true;
14802       int num_pragma_values;
14803       int i;
14804
14805       /* Note: attribs.c:decl_attributes prepends the values from
14806          current_target_pragma to the list of target attributes.  To determine
14807          whether we're looking at a value of the attribute or the pragma we
14808          assume that the first [list_length (current_target_pragma)] values in
14809          the list are the values from the pragma.  */
14810       num_pragma_values = (!force_pragma && current_target_pragma != NULL)
14811         ? list_length (current_target_pragma) : 0;
14812       for (i = 0; args; args = TREE_CHAIN (args), i++)
14813         {
14814           bool is_pragma;
14815
14816           is_pragma = (force_pragma || i < num_pragma_values);
14817           if (TREE_VALUE (args)
14818               && !s390_valid_target_attribute_inner_p (TREE_VALUE (args),
14819                                                        opts, new_opts_set,
14820                                                        is_pragma))
14821             {
14822               ret = false;
14823             }
14824         }
14825       return ret;
14826     }
14827
14828   else if (TREE_CODE (args) != STRING_CST)
14829     {
14830       error ("attribute %<target%> argument not a string");
14831       return false;
14832     }
14833
14834   /* Handle multiple arguments separated by commas.  */
14835   next_optstr = ASTRDUP (TREE_STRING_POINTER (args));
14836
14837   while (next_optstr && *next_optstr != '\0')
14838     {
14839       char *p = next_optstr;
14840       char *orig_p = p;
14841       char *comma = strchr (next_optstr, ',');
14842       size_t len, opt_len;
14843       int opt;
14844       bool opt_set_p;
14845       char ch;
14846       unsigned i;
14847       int mask = 0;
14848       enum cl_var_type var_type;
14849       bool found;
14850
14851       if (comma)
14852         {
14853           *comma = '\0';
14854           len = comma - next_optstr;
14855           next_optstr = comma + 1;
14856         }
14857       else
14858         {
14859           len = strlen (p);
14860           next_optstr = NULL;
14861         }
14862
14863       /* Recognize no-xxx.  */
14864       if (len > 3 && p[0] == 'n' && p[1] == 'o' && p[2] == '-')
14865         {
14866           opt_set_p = false;
14867           p += 3;
14868           len -= 3;
14869         }
14870       else
14871         opt_set_p = true;
14872
14873       /* Find the option.  */
14874       ch = *p;
14875       found = false;
14876       for (i = 0; i < ARRAY_SIZE (attrs); i++)
14877         {
14878           opt_len = attrs[i].len;
14879           if (ch == attrs[i].string[0]
14880               && ((attrs[i].has_arg) ? len > opt_len : len == opt_len)
14881               && memcmp (p, attrs[i].string, opt_len) == 0)
14882             {
14883               opt = attrs[i].opt;
14884               if (!opt_set_p && cl_options[opt].cl_reject_negative)
14885                 continue;
14886               mask = cl_options[opt].var_value;
14887               var_type = cl_options[opt].var_type;
14888               found = true;
14889               break;
14890             }
14891         }
14892
14893       /* Process the option.  */
14894       if (!found)
14895         {
14896           error ("attribute(target(\"%s\")) is unknown", orig_p);
14897           return false;
14898         }
14899       else if (attrs[i].only_as_pragma && !force_pragma)
14900         {
14901           /* Value is not allowed for the target attribute.  */
14902           error ("value %qs is not supported by attribute %<target%>",
14903                  attrs[i].string);
14904           return false;
14905         }
14906
14907       else if (var_type == CLVC_BIT_SET || var_type == CLVC_BIT_CLEAR)
14908         {
14909           if (var_type == CLVC_BIT_CLEAR)
14910             opt_set_p = !opt_set_p;
14911
14912           if (opt_set_p)
14913             opts->x_target_flags |= mask;
14914           else
14915             opts->x_target_flags &= ~mask;
14916           new_opts_set->x_target_flags |= mask;
14917         }
14918
14919       else if (cl_options[opt].var_type == CLVC_BOOLEAN)
14920         {
14921           int value;
14922
14923           if (cl_options[opt].cl_uinteger)
14924             {
14925               /* Unsigned integer argument.  Code based on the function
14926                  decode_cmdline_option () in opts-common.c.  */
14927               value = integral_argument (p + opt_len);
14928             }
14929           else
14930             value = (opt_set_p) ? 1 : 0;
14931
14932           if (value != -1)
14933             {
14934               struct cl_decoded_option decoded;
14935
14936               /* Value range check; only implemented for numeric and boolean
14937                  options at the moment.  */
14938               generate_option (opt, NULL, value, CL_TARGET, &decoded);
14939               s390_handle_option (opts, new_opts_set, &decoded, input_location);
14940               set_option (opts, new_opts_set, opt, value,
14941                           p + opt_len, DK_UNSPECIFIED, input_location,
14942                           global_dc);
14943             }
14944           else
14945             {
14946               error ("attribute(target(\"%s\")) is unknown", orig_p);
14947               ret = false;
14948             }
14949         }
14950
14951       else if (cl_options[opt].var_type == CLVC_ENUM)
14952         {
14953           bool arg_ok;
14954           int value;
14955
14956           arg_ok = opt_enum_arg_to_value (opt, p + opt_len, &value, CL_TARGET);
14957           if (arg_ok)
14958             set_option (opts, new_opts_set, opt, value,
14959                         p + opt_len, DK_UNSPECIFIED, input_location,
14960                         global_dc);
14961           else
14962             {
14963               error ("attribute(target(\"%s\")) is unknown", orig_p);
14964               ret = false;
14965             }
14966         }
14967
14968       else
14969         gcc_unreachable ();
14970     }
14971   return ret;
14972 }
14973
14974 /* Return a TARGET_OPTION_NODE tree of the target options listed or NULL.  */
14975
14976 tree
14977 s390_valid_target_attribute_tree (tree args,
14978                                   struct gcc_options *opts,
14979                                   const struct gcc_options *opts_set,
14980                                   bool force_pragma)
14981 {
14982   tree t = NULL_TREE;
14983   struct gcc_options new_opts_set;
14984
14985   memset (&new_opts_set, 0, sizeof (new_opts_set));
14986
14987   /* Process each of the options on the chain.  */
14988   if (! s390_valid_target_attribute_inner_p (args, opts, &new_opts_set,
14989                                              force_pragma))
14990     return error_mark_node;
14991
14992   /* If some option was set (even if it has not changed), rerun
14993      s390_option_override_internal, and then save the options away.  */
14994   if (new_opts_set.x_target_flags
14995       || new_opts_set.x_s390_arch
14996       || new_opts_set.x_s390_tune
14997       || new_opts_set.x_s390_stack_guard
14998       || new_opts_set.x_s390_stack_size
14999       || new_opts_set.x_s390_branch_cost
15000       || new_opts_set.x_s390_warn_framesize
15001       || new_opts_set.x_s390_warn_dynamicstack_p)
15002     {
15003       const unsigned char *src = (const unsigned char *)opts_set;
15004       unsigned char *dest = (unsigned char *)&new_opts_set;
15005       unsigned int i;
15006
15007       /* Merge the original option flags into the new ones.  */
15008       for (i = 0; i < sizeof(*opts_set); i++)
15009         dest[i] |= src[i];
15010
15011       /* Do any overrides, such as arch=xxx, or tune=xxx support.  */
15012       s390_option_override_internal (false, opts, &new_opts_set);
15013       /* Save the current options unless we are validating options for
15014          #pragma.  */
15015       t = build_target_option_node (opts);
15016     }
15017   return t;
15018 }
15019
15020 /* Hook to validate attribute((target("string"))).  */
15021
15022 static bool
15023 s390_valid_target_attribute_p (tree fndecl,
15024                                tree ARG_UNUSED (name),
15025                                tree args,
15026                                int ARG_UNUSED (flags))
15027 {
15028   struct gcc_options func_options;
15029   tree new_target, new_optimize;
15030   bool ret = true;
15031
15032   /* attribute((target("default"))) does nothing, beyond
15033      affecting multi-versioning.  */
15034   if (TREE_VALUE (args)
15035       && TREE_CODE (TREE_VALUE (args)) == STRING_CST
15036       && TREE_CHAIN (args) == NULL_TREE
15037       && strcmp (TREE_STRING_POINTER (TREE_VALUE (args)), "default") == 0)
15038     return true;
15039
15040   tree old_optimize = build_optimization_node (&global_options);
15041
15042   /* Get the optimization options of the current function.  */
15043   tree func_optimize = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (fndecl);
15044
15045   if (!func_optimize)
15046     func_optimize = old_optimize;
15047
15048   /* Init func_options.  */
15049   memset (&func_options, 0, sizeof (func_options));
15050   init_options_struct (&func_options, NULL);
15051   lang_hooks.init_options_struct (&func_options);
15052
15053   cl_optimization_restore (&func_options, TREE_OPTIMIZATION (func_optimize));
15054
15055   /* Initialize func_options to the default before its target options can
15056      be set.  */
15057   cl_target_option_restore (&func_options,
15058                             TREE_TARGET_OPTION (target_option_default_node));
15059
15060   new_target = s390_valid_target_attribute_tree (args, &func_options,
15061                                                  &global_options_set,
15062                                                  (args ==
15063                                                   current_target_pragma));
15064   new_optimize = build_optimization_node (&func_options);
15065   if (new_target == error_mark_node)
15066     ret = false;
15067   else if (fndecl && new_target)
15068     {
15069       DECL_FUNCTION_SPECIFIC_TARGET (fndecl) = new_target;
15070       if (old_optimize != new_optimize)
15071         DECL_FUNCTION_SPECIFIC_OPTIMIZATION (fndecl) = new_optimize;
15072     }
15073   return ret;
15074 }
15075
15076 /* Restore targets globals from NEW_TREE and invalidate s390_previous_fndecl
15077    cache.  */
15078
15079 void
15080 s390_activate_target_options (tree new_tree)
15081 {
15082   cl_target_option_restore (&global_options, TREE_TARGET_OPTION (new_tree));
15083   if (TREE_TARGET_GLOBALS (new_tree))
15084     restore_target_globals (TREE_TARGET_GLOBALS (new_tree));
15085   else if (new_tree == target_option_default_node)
15086     restore_target_globals (&default_target_globals);
15087   else
15088     TREE_TARGET_GLOBALS (new_tree) = save_target_globals_default_opts ();
15089   s390_previous_fndecl = NULL_TREE;
15090 }
15091
15092 /* Establish appropriate back-end context for processing the function
15093    FNDECL.  The argument might be NULL to indicate processing at top
15094    level, outside of any function scope.  */
15095 static void
15096 s390_set_current_function (tree fndecl)
15097 {
15098   /* Only change the context if the function changes.  This hook is called
15099      several times in the course of compiling a function, and we don't want to
15100      slow things down too much or call target_reinit when it isn't safe.  */
15101   if (fndecl == s390_previous_fndecl)
15102     return;
15103
15104   tree old_tree;
15105   if (s390_previous_fndecl == NULL_TREE)
15106     old_tree = target_option_current_node;
15107   else if (DECL_FUNCTION_SPECIFIC_TARGET (s390_previous_fndecl))
15108     old_tree = DECL_FUNCTION_SPECIFIC_TARGET (s390_previous_fndecl);
15109   else
15110     old_tree = target_option_default_node;
15111
15112   if (fndecl == NULL_TREE)
15113     {
15114       if (old_tree != target_option_current_node)
15115         s390_activate_target_options (target_option_current_node);
15116       return;
15117     }
15118
15119   tree new_tree = DECL_FUNCTION_SPECIFIC_TARGET (fndecl);
15120   if (new_tree == NULL_TREE)
15121     new_tree = target_option_default_node;
15122
15123   if (old_tree != new_tree)
15124     s390_activate_target_options (new_tree);
15125   s390_previous_fndecl = fndecl;
15126 }
15127 #endif
15128
15129 /* Implement TARGET_USE_BY_PIECES_INFRASTRUCTURE_P.  */
15130
15131 static bool
15132 s390_use_by_pieces_infrastructure_p (unsigned HOST_WIDE_INT size,
15133                                      unsigned int align ATTRIBUTE_UNUSED,
15134                                      enum by_pieces_operation op ATTRIBUTE_UNUSED,
15135                                      bool speed_p ATTRIBUTE_UNUSED)
15136 {
15137   return (size == 1 || size == 2
15138           || size == 4 || (TARGET_ZARCH && size == 8));
15139 }
15140
15141 /* Implement TARGET_ATOMIC_ASSIGN_EXPAND_FENV hook.  */
15142
15143 static void
15144 s390_atomic_assign_expand_fenv (tree *hold, tree *clear, tree *update)
15145 {
15146   tree sfpc = s390_builtin_decls[S390_BUILTIN_s390_sfpc];
15147   tree efpc = s390_builtin_decls[S390_BUILTIN_s390_efpc];
15148   tree call_efpc = build_call_expr (efpc, 0);
15149   tree fenv_var = create_tmp_var_raw (unsigned_type_node);
15150
15151 #define FPC_EXCEPTION_MASK       HOST_WIDE_INT_UC (0xf8000000)
15152 #define FPC_FLAGS_MASK           HOST_WIDE_INT_UC (0x00f80000)
15153 #define FPC_DXC_MASK             HOST_WIDE_INT_UC (0x0000ff00)
15154 #define FPC_EXCEPTION_MASK_SHIFT HOST_WIDE_INT_UC (24)
15155 #define FPC_FLAGS_SHIFT          HOST_WIDE_INT_UC (16)
15156 #define FPC_DXC_SHIFT            HOST_WIDE_INT_UC (8)
15157
15158   /* Generates the equivalent of feholdexcept (&fenv_var)
15159
15160      fenv_var = __builtin_s390_efpc ();
15161      __builtin_s390_sfpc (fenv_var & mask) */
15162   tree old_fpc = build2 (MODIFY_EXPR, unsigned_type_node, fenv_var, call_efpc);
15163   tree new_fpc =
15164     build2 (BIT_AND_EXPR, unsigned_type_node, fenv_var,
15165             build_int_cst (unsigned_type_node,
15166                            ~(FPC_DXC_MASK | FPC_FLAGS_MASK |
15167                              FPC_EXCEPTION_MASK)));
15168   tree set_new_fpc = build_call_expr (sfpc, 1, new_fpc);
15169   *hold = build2 (COMPOUND_EXPR, void_type_node, old_fpc, set_new_fpc);
15170
15171   /* Generates the equivalent of feclearexcept (FE_ALL_EXCEPT)
15172
15173      __builtin_s390_sfpc (__builtin_s390_efpc () & mask) */
15174   new_fpc = build2 (BIT_AND_EXPR, unsigned_type_node, call_efpc,
15175                     build_int_cst (unsigned_type_node,
15176                                    ~(FPC_DXC_MASK | FPC_FLAGS_MASK)));
15177   *clear = build_call_expr (sfpc, 1, new_fpc);
15178
15179   /* Generates the equivalent of feupdateenv (fenv_var)
15180
15181   old_fpc = __builtin_s390_efpc ();
15182   __builtin_s390_sfpc (fenv_var);
15183   __atomic_feraiseexcept ((old_fpc & FPC_FLAGS_MASK) >> FPC_FLAGS_SHIFT);  */
15184
15185   old_fpc = create_tmp_var_raw (unsigned_type_node);
15186   tree store_old_fpc = build2 (MODIFY_EXPR, void_type_node,
15187                                old_fpc, call_efpc);
15188
15189   set_new_fpc = build_call_expr (sfpc, 1, fenv_var);
15190
15191   tree raise_old_except = build2 (BIT_AND_EXPR, unsigned_type_node, old_fpc,
15192                                   build_int_cst (unsigned_type_node,
15193                                                  FPC_FLAGS_MASK));
15194   raise_old_except = build2 (RSHIFT_EXPR, unsigned_type_node, raise_old_except,
15195                              build_int_cst (unsigned_type_node,
15196                                             FPC_FLAGS_SHIFT));
15197   tree atomic_feraiseexcept
15198     = builtin_decl_implicit (BUILT_IN_ATOMIC_FERAISEEXCEPT);
15199   raise_old_except = build_call_expr (atomic_feraiseexcept,
15200                                       1, raise_old_except);
15201
15202   *update = build2 (COMPOUND_EXPR, void_type_node,
15203                     build2 (COMPOUND_EXPR, void_type_node,
15204                             store_old_fpc, set_new_fpc),
15205                     raise_old_except);
15206
15207 #undef FPC_EXCEPTION_MASK
15208 #undef FPC_FLAGS_MASK
15209 #undef FPC_DXC_MASK
15210 #undef FPC_EXCEPTION_MASK_SHIFT
15211 #undef FPC_FLAGS_SHIFT
15212 #undef FPC_DXC_SHIFT
15213 }
15214
15215 /* Return the vector mode to be used for inner mode MODE when doing
15216    vectorization.  */
15217 static machine_mode
15218 s390_preferred_simd_mode (machine_mode mode)
15219 {
15220   if (TARGET_VX)
15221     switch (mode)
15222       {
15223       case DFmode:
15224         return V2DFmode;
15225       case DImode:
15226         return V2DImode;
15227       case SImode:
15228         return V4SImode;
15229       case HImode:
15230         return V8HImode;
15231       case QImode:
15232         return V16QImode;
15233       default:;
15234       }
15235   return word_mode;
15236 }
15237
15238 /* Our hardware does not require vectors to be strictly aligned.  */
15239 static bool
15240 s390_support_vector_misalignment (machine_mode mode ATTRIBUTE_UNUSED,
15241                                   const_tree type ATTRIBUTE_UNUSED,
15242                                   int misalignment ATTRIBUTE_UNUSED,
15243                                   bool is_packed ATTRIBUTE_UNUSED)
15244 {
15245   if (TARGET_VX)
15246     return true;
15247
15248   return default_builtin_support_vector_misalignment (mode, type, misalignment,
15249                                                       is_packed);
15250 }
15251
15252 /* The vector ABI requires vector types to be aligned on an 8 byte
15253    boundary (our stack alignment).  However, we allow this to be
15254    overriden by the user, while this definitely breaks the ABI.  */
15255 static HOST_WIDE_INT
15256 s390_vector_alignment (const_tree type)
15257 {
15258   if (!TARGET_VX_ABI)
15259     return default_vector_alignment (type);
15260
15261   if (TYPE_USER_ALIGN (type))
15262     return TYPE_ALIGN (type);
15263
15264   return MIN (64, tree_to_shwi (TYPE_SIZE (type)));
15265 }
15266
15267 #ifdef HAVE_AS_MACHINE_MACHINEMODE
15268 /* Implement TARGET_ASM_FILE_START.  */
15269 static void
15270 s390_asm_file_start (void)
15271 {
15272   default_file_start ();
15273   s390_asm_output_machine_for_arch (asm_out_file);
15274 }
15275 #endif
15276
15277 /* Implement TARGET_ASM_FILE_END.  */
15278 static void
15279 s390_asm_file_end (void)
15280 {
15281 #ifdef HAVE_AS_GNU_ATTRIBUTE
15282   varpool_node *vnode;
15283   cgraph_node *cnode;
15284
15285   FOR_EACH_VARIABLE (vnode)
15286     if (TREE_PUBLIC (vnode->decl))
15287       s390_check_type_for_vector_abi (TREE_TYPE (vnode->decl), false, false);
15288
15289   FOR_EACH_FUNCTION (cnode)
15290     if (TREE_PUBLIC (cnode->decl))
15291       s390_check_type_for_vector_abi (TREE_TYPE (cnode->decl), false, false);
15292
15293
15294   if (s390_vector_abi != 0)
15295     fprintf (asm_out_file, "\t.gnu_attribute 8, %d\n",
15296              s390_vector_abi);
15297 #endif
15298   file_end_indicate_exec_stack ();
15299
15300   if (flag_split_stack)
15301     file_end_indicate_split_stack ();
15302 }
15303
15304 /* Return true if TYPE is a vector bool type.  */
15305 static inline bool
15306 s390_vector_bool_type_p (const_tree type)
15307 {
15308   return TYPE_VECTOR_OPAQUE (type);
15309 }
15310
15311 /* Return the diagnostic message string if the binary operation OP is
15312    not permitted on TYPE1 and TYPE2, NULL otherwise.  */
15313 static const char*
15314 s390_invalid_binary_op (int op ATTRIBUTE_UNUSED, const_tree type1, const_tree type2)
15315 {
15316   bool bool1_p, bool2_p;
15317   bool plusminus_p;
15318   bool muldiv_p;
15319   bool compare_p;
15320   machine_mode mode1, mode2;
15321
15322   if (!TARGET_ZVECTOR)
15323     return NULL;
15324
15325   if (!VECTOR_TYPE_P (type1) || !VECTOR_TYPE_P (type2))
15326     return NULL;
15327
15328   bool1_p = s390_vector_bool_type_p (type1);
15329   bool2_p = s390_vector_bool_type_p (type2);
15330
15331   /* Mixing signed and unsigned types is forbidden for all
15332      operators.  */
15333   if (!bool1_p && !bool2_p
15334       && TYPE_UNSIGNED (type1) != TYPE_UNSIGNED (type2))
15335     return N_("types differ in signedness");
15336
15337   plusminus_p = (op == PLUS_EXPR || op == MINUS_EXPR);
15338   muldiv_p = (op == MULT_EXPR || op == RDIV_EXPR || op == TRUNC_DIV_EXPR
15339               || op == CEIL_DIV_EXPR || op == FLOOR_DIV_EXPR
15340               || op == ROUND_DIV_EXPR);
15341   compare_p = (op == LT_EXPR || op == LE_EXPR || op == GT_EXPR || op == GE_EXPR
15342                || op == EQ_EXPR || op == NE_EXPR);
15343
15344   if (bool1_p && bool2_p && (plusminus_p || muldiv_p))
15345     return N_("binary operator does not support two vector bool operands");
15346
15347   if (bool1_p != bool2_p && (muldiv_p || compare_p))
15348     return N_("binary operator does not support vector bool operand");
15349
15350   mode1 = TYPE_MODE (type1);
15351   mode2 = TYPE_MODE (type2);
15352
15353   if (bool1_p != bool2_p && plusminus_p
15354       && (GET_MODE_CLASS (mode1) == MODE_VECTOR_FLOAT
15355           || GET_MODE_CLASS (mode2) == MODE_VECTOR_FLOAT))
15356     return N_("binary operator does not support mixing vector "
15357               "bool with floating point vector operands");
15358
15359   return NULL;
15360 }
15361
15362 /* Implement TARGET_C_EXCESS_PRECISION.
15363
15364    FIXME: For historical reasons, float_t and double_t are typedef'ed to
15365    double on s390, causing operations on float_t to operate in a higher
15366    precision than is necessary.  However, it is not the case that SFmode
15367    operations have implicit excess precision, and we generate more optimal
15368    code if we let the compiler know no implicit extra precision is added.
15369
15370    That means when we are compiling with -fexcess-precision=fast, the value
15371    we set for FLT_EVAL_METHOD will be out of line with the actual precision of
15372    float_t (though they would be correct for -fexcess-precision=standard).
15373
15374    A complete fix would modify glibc to remove the unnecessary typedef
15375    of float_t to double.  */
15376
15377 static enum flt_eval_method
15378 s390_excess_precision (enum excess_precision_type type)
15379 {
15380   switch (type)
15381     {
15382       case EXCESS_PRECISION_TYPE_IMPLICIT:
15383       case EXCESS_PRECISION_TYPE_FAST:
15384         /* The fastest type to promote to will always be the native type,
15385            whether that occurs with implicit excess precision or
15386            otherwise.  */
15387         return FLT_EVAL_METHOD_PROMOTE_TO_FLOAT;
15388       case EXCESS_PRECISION_TYPE_STANDARD:
15389         /* Otherwise, when we are in a standards compliant mode, to
15390            ensure consistency with the implementation in glibc, report that
15391            float is evaluated to the range and precision of double.  */
15392         return FLT_EVAL_METHOD_PROMOTE_TO_DOUBLE;
15393       default:
15394         gcc_unreachable ();
15395     }
15396   return FLT_EVAL_METHOD_UNPREDICTABLE;
15397 }
15398
15399 /* Implement the TARGET_ASAN_SHADOW_OFFSET hook.  */
15400
15401 static unsigned HOST_WIDE_INT
15402 s390_asan_shadow_offset (void)
15403 {
15404   return TARGET_64BIT ? HOST_WIDE_INT_1U << 52 : HOST_WIDE_INT_UC (0x20000000);
15405 }
15406
15407 /* Initialize GCC target structure.  */
15408
15409 #undef  TARGET_ASM_ALIGNED_HI_OP
15410 #define TARGET_ASM_ALIGNED_HI_OP "\t.word\t"
15411 #undef  TARGET_ASM_ALIGNED_DI_OP
15412 #define TARGET_ASM_ALIGNED_DI_OP "\t.quad\t"
15413 #undef  TARGET_ASM_INTEGER
15414 #define TARGET_ASM_INTEGER s390_assemble_integer
15415
15416 #undef  TARGET_ASM_OPEN_PAREN
15417 #define TARGET_ASM_OPEN_PAREN ""
15418
15419 #undef  TARGET_ASM_CLOSE_PAREN
15420 #define TARGET_ASM_CLOSE_PAREN ""
15421
15422 #undef TARGET_OPTION_OVERRIDE
15423 #define TARGET_OPTION_OVERRIDE s390_option_override
15424
15425 #ifdef TARGET_THREAD_SSP_OFFSET
15426 #undef TARGET_STACK_PROTECT_GUARD
15427 #define TARGET_STACK_PROTECT_GUARD hook_tree_void_null
15428 #endif
15429
15430 #undef  TARGET_ENCODE_SECTION_INFO
15431 #define TARGET_ENCODE_SECTION_INFO s390_encode_section_info
15432
15433 #undef TARGET_SCALAR_MODE_SUPPORTED_P
15434 #define TARGET_SCALAR_MODE_SUPPORTED_P s390_scalar_mode_supported_p
15435
15436 #ifdef HAVE_AS_TLS
15437 #undef TARGET_HAVE_TLS
15438 #define TARGET_HAVE_TLS true
15439 #endif
15440 #undef TARGET_CANNOT_FORCE_CONST_MEM
15441 #define TARGET_CANNOT_FORCE_CONST_MEM s390_cannot_force_const_mem
15442
15443 #undef TARGET_DELEGITIMIZE_ADDRESS
15444 #define TARGET_DELEGITIMIZE_ADDRESS s390_delegitimize_address
15445
15446 #undef TARGET_LEGITIMIZE_ADDRESS
15447 #define TARGET_LEGITIMIZE_ADDRESS s390_legitimize_address
15448
15449 #undef TARGET_RETURN_IN_MEMORY
15450 #define TARGET_RETURN_IN_MEMORY s390_return_in_memory
15451
15452 #undef  TARGET_INIT_BUILTINS
15453 #define TARGET_INIT_BUILTINS s390_init_builtins
15454 #undef  TARGET_EXPAND_BUILTIN
15455 #define TARGET_EXPAND_BUILTIN s390_expand_builtin
15456 #undef  TARGET_BUILTIN_DECL
15457 #define TARGET_BUILTIN_DECL s390_builtin_decl
15458
15459 #undef TARGET_ASM_OUTPUT_ADDR_CONST_EXTRA
15460 #define TARGET_ASM_OUTPUT_ADDR_CONST_EXTRA s390_output_addr_const_extra
15461
15462 #undef TARGET_ASM_OUTPUT_MI_THUNK
15463 #define TARGET_ASM_OUTPUT_MI_THUNK s390_output_mi_thunk
15464 #undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
15465 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK hook_bool_const_tree_hwi_hwi_const_tree_true
15466
15467 #undef TARGET_C_EXCESS_PRECISION
15468 #define TARGET_C_EXCESS_PRECISION s390_excess_precision
15469
15470 #undef  TARGET_SCHED_ADJUST_PRIORITY
15471 #define TARGET_SCHED_ADJUST_PRIORITY s390_adjust_priority
15472 #undef TARGET_SCHED_ISSUE_RATE
15473 #define TARGET_SCHED_ISSUE_RATE s390_issue_rate
15474 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD
15475 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD s390_first_cycle_multipass_dfa_lookahead
15476
15477 #undef TARGET_SCHED_VARIABLE_ISSUE
15478 #define TARGET_SCHED_VARIABLE_ISSUE s390_sched_variable_issue
15479 #undef TARGET_SCHED_REORDER
15480 #define TARGET_SCHED_REORDER s390_sched_reorder
15481 #undef TARGET_SCHED_INIT
15482 #define TARGET_SCHED_INIT s390_sched_init
15483
15484 #undef TARGET_CANNOT_COPY_INSN_P
15485 #define TARGET_CANNOT_COPY_INSN_P s390_cannot_copy_insn_p
15486 #undef TARGET_RTX_COSTS
15487 #define TARGET_RTX_COSTS s390_rtx_costs
15488 #undef TARGET_ADDRESS_COST
15489 #define TARGET_ADDRESS_COST s390_address_cost
15490 #undef TARGET_REGISTER_MOVE_COST
15491 #define TARGET_REGISTER_MOVE_COST s390_register_move_cost
15492 #undef TARGET_MEMORY_MOVE_COST
15493 #define TARGET_MEMORY_MOVE_COST s390_memory_move_cost
15494 #undef TARGET_VECTORIZE_BUILTIN_VECTORIZATION_COST
15495 #define TARGET_VECTORIZE_BUILTIN_VECTORIZATION_COST \
15496   s390_builtin_vectorization_cost
15497
15498 #undef TARGET_MACHINE_DEPENDENT_REORG
15499 #define TARGET_MACHINE_DEPENDENT_REORG s390_reorg
15500
15501 #undef TARGET_VALID_POINTER_MODE
15502 #define TARGET_VALID_POINTER_MODE s390_valid_pointer_mode
15503
15504 #undef TARGET_BUILD_BUILTIN_VA_LIST
15505 #define TARGET_BUILD_BUILTIN_VA_LIST s390_build_builtin_va_list
15506 #undef TARGET_EXPAND_BUILTIN_VA_START
15507 #define TARGET_EXPAND_BUILTIN_VA_START s390_va_start
15508 #undef TARGET_ASAN_SHADOW_OFFSET
15509 #define TARGET_ASAN_SHADOW_OFFSET s390_asan_shadow_offset
15510 #undef TARGET_GIMPLIFY_VA_ARG_EXPR
15511 #define TARGET_GIMPLIFY_VA_ARG_EXPR s390_gimplify_va_arg
15512
15513 #undef TARGET_PROMOTE_FUNCTION_MODE
15514 #define TARGET_PROMOTE_FUNCTION_MODE s390_promote_function_mode
15515 #undef TARGET_PASS_BY_REFERENCE
15516 #define TARGET_PASS_BY_REFERENCE s390_pass_by_reference
15517
15518 #undef TARGET_FUNCTION_OK_FOR_SIBCALL
15519 #define TARGET_FUNCTION_OK_FOR_SIBCALL s390_function_ok_for_sibcall
15520 #undef TARGET_FUNCTION_ARG
15521 #define TARGET_FUNCTION_ARG s390_function_arg
15522 #undef TARGET_FUNCTION_ARG_ADVANCE
15523 #define TARGET_FUNCTION_ARG_ADVANCE s390_function_arg_advance
15524 #undef TARGET_FUNCTION_VALUE
15525 #define TARGET_FUNCTION_VALUE s390_function_value
15526 #undef TARGET_LIBCALL_VALUE
15527 #define TARGET_LIBCALL_VALUE s390_libcall_value
15528 #undef TARGET_STRICT_ARGUMENT_NAMING
15529 #define TARGET_STRICT_ARGUMENT_NAMING hook_bool_CUMULATIVE_ARGS_true
15530
15531 #undef TARGET_KEEP_LEAF_WHEN_PROFILED
15532 #define TARGET_KEEP_LEAF_WHEN_PROFILED s390_keep_leaf_when_profiled
15533
15534 #undef TARGET_FIXED_CONDITION_CODE_REGS
15535 #define TARGET_FIXED_CONDITION_CODE_REGS s390_fixed_condition_code_regs
15536
15537 #undef TARGET_CC_MODES_COMPATIBLE
15538 #define TARGET_CC_MODES_COMPATIBLE s390_cc_modes_compatible
15539
15540 #undef TARGET_INVALID_WITHIN_DOLOOP
15541 #define TARGET_INVALID_WITHIN_DOLOOP hook_constcharptr_const_rtx_insn_null
15542
15543 #ifdef HAVE_AS_TLS
15544 #undef TARGET_ASM_OUTPUT_DWARF_DTPREL
15545 #define TARGET_ASM_OUTPUT_DWARF_DTPREL s390_output_dwarf_dtprel
15546 #endif
15547
15548 #undef TARGET_DWARF_FRAME_REG_MODE
15549 #define TARGET_DWARF_FRAME_REG_MODE s390_dwarf_frame_reg_mode
15550
15551 #ifdef TARGET_ALTERNATE_LONG_DOUBLE_MANGLING
15552 #undef TARGET_MANGLE_TYPE
15553 #define TARGET_MANGLE_TYPE s390_mangle_type
15554 #endif
15555
15556 #undef TARGET_SCALAR_MODE_SUPPORTED_P
15557 #define TARGET_SCALAR_MODE_SUPPORTED_P s390_scalar_mode_supported_p
15558
15559 #undef TARGET_VECTOR_MODE_SUPPORTED_P
15560 #define TARGET_VECTOR_MODE_SUPPORTED_P s390_vector_mode_supported_p
15561
15562 #undef  TARGET_PREFERRED_RELOAD_CLASS
15563 #define TARGET_PREFERRED_RELOAD_CLASS s390_preferred_reload_class
15564
15565 #undef TARGET_SECONDARY_RELOAD
15566 #define TARGET_SECONDARY_RELOAD s390_secondary_reload
15567
15568 #undef TARGET_LIBGCC_CMP_RETURN_MODE
15569 #define TARGET_LIBGCC_CMP_RETURN_MODE s390_libgcc_cmp_return_mode
15570
15571 #undef TARGET_LIBGCC_SHIFT_COUNT_MODE
15572 #define TARGET_LIBGCC_SHIFT_COUNT_MODE s390_libgcc_shift_count_mode
15573
15574 #undef TARGET_LEGITIMATE_ADDRESS_P
15575 #define TARGET_LEGITIMATE_ADDRESS_P s390_legitimate_address_p
15576
15577 #undef TARGET_LEGITIMATE_CONSTANT_P
15578 #define TARGET_LEGITIMATE_CONSTANT_P s390_legitimate_constant_p
15579
15580 #undef TARGET_LRA_P
15581 #define TARGET_LRA_P s390_lra_p
15582
15583 #undef TARGET_CAN_ELIMINATE
15584 #define TARGET_CAN_ELIMINATE s390_can_eliminate
15585
15586 #undef TARGET_CONDITIONAL_REGISTER_USAGE
15587 #define TARGET_CONDITIONAL_REGISTER_USAGE s390_conditional_register_usage
15588
15589 #undef TARGET_LOOP_UNROLL_ADJUST
15590 #define TARGET_LOOP_UNROLL_ADJUST s390_loop_unroll_adjust
15591
15592 #undef TARGET_ASM_TRAMPOLINE_TEMPLATE
15593 #define TARGET_ASM_TRAMPOLINE_TEMPLATE s390_asm_trampoline_template
15594 #undef TARGET_TRAMPOLINE_INIT
15595 #define TARGET_TRAMPOLINE_INIT s390_trampoline_init
15596
15597 /* PR 79421 */
15598 #undef TARGET_CUSTOM_FUNCTION_DESCRIPTORS
15599 #define TARGET_CUSTOM_FUNCTION_DESCRIPTORS 1
15600
15601 #undef TARGET_UNWIND_WORD_MODE
15602 #define TARGET_UNWIND_WORD_MODE s390_unwind_word_mode
15603
15604 #undef TARGET_CANONICALIZE_COMPARISON
15605 #define TARGET_CANONICALIZE_COMPARISON s390_canonicalize_comparison
15606
15607 #undef TARGET_HARD_REGNO_SCRATCH_OK
15608 #define TARGET_HARD_REGNO_SCRATCH_OK s390_hard_regno_scratch_ok
15609
15610 #undef TARGET_ATTRIBUTE_TABLE
15611 #define TARGET_ATTRIBUTE_TABLE s390_attribute_table
15612
15613 #undef TARGET_FUNCTION_ATTRIBUTE_INLINABLE_P
15614 #define TARGET_FUNCTION_ATTRIBUTE_INLINABLE_P hook_bool_const_tree_true
15615
15616 #undef TARGET_SET_UP_BY_PROLOGUE
15617 #define TARGET_SET_UP_BY_PROLOGUE s300_set_up_by_prologue
15618
15619 #undef TARGET_EXTRA_LIVE_ON_ENTRY
15620 #define TARGET_EXTRA_LIVE_ON_ENTRY s390_live_on_entry
15621
15622 #undef TARGET_USE_BY_PIECES_INFRASTRUCTURE_P
15623 #define TARGET_USE_BY_PIECES_INFRASTRUCTURE_P \
15624   s390_use_by_pieces_infrastructure_p
15625
15626 #undef TARGET_ATOMIC_ASSIGN_EXPAND_FENV
15627 #define TARGET_ATOMIC_ASSIGN_EXPAND_FENV s390_atomic_assign_expand_fenv
15628
15629 #undef TARGET_INVALID_ARG_FOR_UNPROTOTYPED_FN
15630 #define TARGET_INVALID_ARG_FOR_UNPROTOTYPED_FN s390_invalid_arg_for_unprototyped_fn
15631
15632 #undef TARGET_VECTORIZE_PREFERRED_SIMD_MODE
15633 #define TARGET_VECTORIZE_PREFERRED_SIMD_MODE s390_preferred_simd_mode
15634
15635 #undef TARGET_VECTORIZE_SUPPORT_VECTOR_MISALIGNMENT
15636 #define TARGET_VECTORIZE_SUPPORT_VECTOR_MISALIGNMENT s390_support_vector_misalignment
15637
15638 #undef TARGET_VECTOR_ALIGNMENT
15639 #define TARGET_VECTOR_ALIGNMENT s390_vector_alignment
15640
15641 #undef TARGET_INVALID_BINARY_OP
15642 #define TARGET_INVALID_BINARY_OP s390_invalid_binary_op
15643
15644 #ifdef HAVE_AS_MACHINE_MACHINEMODE
15645 #undef TARGET_ASM_FILE_START
15646 #define TARGET_ASM_FILE_START s390_asm_file_start
15647 #endif
15648
15649 #undef TARGET_ASM_FILE_END
15650 #define TARGET_ASM_FILE_END s390_asm_file_end
15651
15652 #if S390_USE_TARGET_ATTRIBUTE
15653 #undef TARGET_SET_CURRENT_FUNCTION
15654 #define TARGET_SET_CURRENT_FUNCTION s390_set_current_function
15655
15656 #undef TARGET_OPTION_VALID_ATTRIBUTE_P
15657 #define TARGET_OPTION_VALID_ATTRIBUTE_P s390_valid_target_attribute_p
15658 #endif
15659
15660 #undef TARGET_OPTION_RESTORE
15661 #define TARGET_OPTION_RESTORE s390_function_specific_restore
15662
15663 struct gcc_target targetm = TARGET_INITIALIZER;
15664
15665 #include "gt-s390.h"