Merge branch 'vendor/MDOCML'
[dragonfly.git] / contrib / gcc-4.4 / gcc / expmed.c
1 /* Medium-level subroutines: convert bit-field store and extract
2    and shifts, multiplies and divides to rtl instructions.
3    Copyright (C) 1987, 1988, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
4    1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
5    Free Software Foundation, Inc.
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
24 #include "config.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "tm.h"
28 #include "toplev.h"
29 #include "rtl.h"
30 #include "tree.h"
31 #include "tm_p.h"
32 #include "flags.h"
33 #include "insn-config.h"
34 #include "expr.h"
35 #include "optabs.h"
36 #include "real.h"
37 #include "recog.h"
38 #include "langhooks.h"
39 #include "df.h"
40 #include "target.h"
41
42 static void store_fixed_bit_field (rtx, unsigned HOST_WIDE_INT,
43                                    unsigned HOST_WIDE_INT,
44                                    unsigned HOST_WIDE_INT, rtx);
45 static void store_split_bit_field (rtx, unsigned HOST_WIDE_INT,
46                                    unsigned HOST_WIDE_INT, rtx);
47 static rtx extract_fixed_bit_field (enum machine_mode, rtx,
48                                     unsigned HOST_WIDE_INT,
49                                     unsigned HOST_WIDE_INT,
50                                     unsigned HOST_WIDE_INT, rtx, int);
51 static rtx mask_rtx (enum machine_mode, int, int, int);
52 static rtx lshift_value (enum machine_mode, rtx, int, int);
53 static rtx extract_split_bit_field (rtx, unsigned HOST_WIDE_INT,
54                                     unsigned HOST_WIDE_INT, int);
55 static void do_cmp_and_jump (rtx, rtx, enum rtx_code, enum machine_mode, rtx);
56 static rtx expand_smod_pow2 (enum machine_mode, rtx, HOST_WIDE_INT);
57 static rtx expand_sdiv_pow2 (enum machine_mode, rtx, HOST_WIDE_INT);
58
59 /* Test whether a value is zero of a power of two.  */
60 #define EXACT_POWER_OF_2_OR_ZERO_P(x) (((x) & ((x) - 1)) == 0)
61
62 /* Nonzero means divides or modulus operations are relatively cheap for
63    powers of two, so don't use branches; emit the operation instead.
64    Usually, this will mean that the MD file will emit non-branch
65    sequences.  */
66
67 static bool sdiv_pow2_cheap[2][NUM_MACHINE_MODES];
68 static bool smod_pow2_cheap[2][NUM_MACHINE_MODES];
69
70 #ifndef SLOW_UNALIGNED_ACCESS
71 #define SLOW_UNALIGNED_ACCESS(MODE, ALIGN) STRICT_ALIGNMENT
72 #endif
73
74 /* For compilers that support multiple targets with different word sizes,
75    MAX_BITS_PER_WORD contains the biggest value of BITS_PER_WORD.  An example
76    is the H8/300(H) compiler.  */
77
78 #ifndef MAX_BITS_PER_WORD
79 #define MAX_BITS_PER_WORD BITS_PER_WORD
80 #endif
81
82 /* Reduce conditional compilation elsewhere.  */
83 #ifndef HAVE_insv
84 #define HAVE_insv       0
85 #define CODE_FOR_insv   CODE_FOR_nothing
86 #define gen_insv(a,b,c,d) NULL_RTX
87 #endif
88 #ifndef HAVE_extv
89 #define HAVE_extv       0
90 #define CODE_FOR_extv   CODE_FOR_nothing
91 #define gen_extv(a,b,c,d) NULL_RTX
92 #endif
93 #ifndef HAVE_extzv
94 #define HAVE_extzv      0
95 #define CODE_FOR_extzv  CODE_FOR_nothing
96 #define gen_extzv(a,b,c,d) NULL_RTX
97 #endif
98
99 /* Cost of various pieces of RTL.  Note that some of these are indexed by
100    shift count and some by mode.  */
101 static int zero_cost[2];
102 static int add_cost[2][NUM_MACHINE_MODES];
103 static int neg_cost[2][NUM_MACHINE_MODES];
104 static int shift_cost[2][NUM_MACHINE_MODES][MAX_BITS_PER_WORD];
105 static int shiftadd_cost[2][NUM_MACHINE_MODES][MAX_BITS_PER_WORD];
106 static int shiftsub_cost[2][NUM_MACHINE_MODES][MAX_BITS_PER_WORD];
107 static int mul_cost[2][NUM_MACHINE_MODES];
108 static int sdiv_cost[2][NUM_MACHINE_MODES];
109 static int udiv_cost[2][NUM_MACHINE_MODES];
110 static int mul_widen_cost[2][NUM_MACHINE_MODES];
111 static int mul_highpart_cost[2][NUM_MACHINE_MODES];
112
113 void
114 init_expmed (void)
115 {
116   struct
117   {
118     struct rtx_def reg;         rtunion reg_fld[2];
119     struct rtx_def plus;        rtunion plus_fld1;
120     struct rtx_def neg;
121     struct rtx_def mult;        rtunion mult_fld1;
122     struct rtx_def sdiv;        rtunion sdiv_fld1;
123     struct rtx_def udiv;        rtunion udiv_fld1;
124     struct rtx_def zext;
125     struct rtx_def sdiv_32;     rtunion sdiv_32_fld1;
126     struct rtx_def smod_32;     rtunion smod_32_fld1;
127     struct rtx_def wide_mult;   rtunion wide_mult_fld1;
128     struct rtx_def wide_lshr;   rtunion wide_lshr_fld1;
129     struct rtx_def wide_trunc;
130     struct rtx_def shift;       rtunion shift_fld1;
131     struct rtx_def shift_mult;  rtunion shift_mult_fld1;
132     struct rtx_def shift_add;   rtunion shift_add_fld1;
133     struct rtx_def shift_sub;   rtunion shift_sub_fld1;
134   } all;
135
136   rtx pow2[MAX_BITS_PER_WORD];
137   rtx cint[MAX_BITS_PER_WORD];
138   int m, n;
139   enum machine_mode mode, wider_mode;
140   int speed;
141
142
143   for (m = 1; m < MAX_BITS_PER_WORD; m++)
144     {
145       pow2[m] = GEN_INT ((HOST_WIDE_INT) 1 << m);
146       cint[m] = GEN_INT (m);
147     }
148   memset (&all, 0, sizeof all);
149
150   PUT_CODE (&all.reg, REG);
151   /* Avoid using hard regs in ways which may be unsupported.  */
152   SET_REGNO (&all.reg, LAST_VIRTUAL_REGISTER + 1);
153
154   PUT_CODE (&all.plus, PLUS);
155   XEXP (&all.plus, 0) = &all.reg;
156   XEXP (&all.plus, 1) = &all.reg;
157
158   PUT_CODE (&all.neg, NEG);
159   XEXP (&all.neg, 0) = &all.reg;
160
161   PUT_CODE (&all.mult, MULT);
162   XEXP (&all.mult, 0) = &all.reg;
163   XEXP (&all.mult, 1) = &all.reg;
164
165   PUT_CODE (&all.sdiv, DIV);
166   XEXP (&all.sdiv, 0) = &all.reg;
167   XEXP (&all.sdiv, 1) = &all.reg;
168
169   PUT_CODE (&all.udiv, UDIV);
170   XEXP (&all.udiv, 0) = &all.reg;
171   XEXP (&all.udiv, 1) = &all.reg;
172
173   PUT_CODE (&all.sdiv_32, DIV);
174   XEXP (&all.sdiv_32, 0) = &all.reg;
175   XEXP (&all.sdiv_32, 1) = 32 < MAX_BITS_PER_WORD ? cint[32] : GEN_INT (32);
176
177   PUT_CODE (&all.smod_32, MOD);
178   XEXP (&all.smod_32, 0) = &all.reg;
179   XEXP (&all.smod_32, 1) = XEXP (&all.sdiv_32, 1);
180
181   PUT_CODE (&all.zext, ZERO_EXTEND);
182   XEXP (&all.zext, 0) = &all.reg;
183
184   PUT_CODE (&all.wide_mult, MULT);
185   XEXP (&all.wide_mult, 0) = &all.zext;
186   XEXP (&all.wide_mult, 1) = &all.zext;
187
188   PUT_CODE (&all.wide_lshr, LSHIFTRT);
189   XEXP (&all.wide_lshr, 0) = &all.wide_mult;
190
191   PUT_CODE (&all.wide_trunc, TRUNCATE);
192   XEXP (&all.wide_trunc, 0) = &all.wide_lshr;
193
194   PUT_CODE (&all.shift, ASHIFT);
195   XEXP (&all.shift, 0) = &all.reg;
196
197   PUT_CODE (&all.shift_mult, MULT);
198   XEXP (&all.shift_mult, 0) = &all.reg;
199
200   PUT_CODE (&all.shift_add, PLUS);
201   XEXP (&all.shift_add, 0) = &all.shift_mult;
202   XEXP (&all.shift_add, 1) = &all.reg;
203
204   PUT_CODE (&all.shift_sub, MINUS);
205   XEXP (&all.shift_sub, 0) = &all.shift_mult;
206   XEXP (&all.shift_sub, 1) = &all.reg;
207
208   for (speed = 0; speed < 2; speed++)
209     {
210       crtl->maybe_hot_insn_p = speed;
211       zero_cost[speed] = rtx_cost (const0_rtx, 0, speed);
212
213       for (mode = GET_CLASS_NARROWEST_MODE (MODE_INT);
214            mode != VOIDmode;
215            mode = GET_MODE_WIDER_MODE (mode))
216         {
217           PUT_MODE (&all.reg, mode);
218           PUT_MODE (&all.plus, mode);
219           PUT_MODE (&all.neg, mode);
220           PUT_MODE (&all.mult, mode);
221           PUT_MODE (&all.sdiv, mode);
222           PUT_MODE (&all.udiv, mode);
223           PUT_MODE (&all.sdiv_32, mode);
224           PUT_MODE (&all.smod_32, mode);
225           PUT_MODE (&all.wide_trunc, mode);
226           PUT_MODE (&all.shift, mode);
227           PUT_MODE (&all.shift_mult, mode);
228           PUT_MODE (&all.shift_add, mode);
229           PUT_MODE (&all.shift_sub, mode);
230
231           add_cost[speed][mode] = rtx_cost (&all.plus, SET, speed);
232           neg_cost[speed][mode] = rtx_cost (&all.neg, SET, speed);
233           mul_cost[speed][mode] = rtx_cost (&all.mult, SET, speed);
234           sdiv_cost[speed][mode] = rtx_cost (&all.sdiv, SET, speed);
235           udiv_cost[speed][mode] = rtx_cost (&all.udiv, SET, speed);
236
237           sdiv_pow2_cheap[speed][mode] = (rtx_cost (&all.sdiv_32, SET, speed)
238                                           <= 2 * add_cost[speed][mode]);
239           smod_pow2_cheap[speed][mode] = (rtx_cost (&all.smod_32, SET, speed)
240                                           <= 4 * add_cost[speed][mode]);
241
242           wider_mode = GET_MODE_WIDER_MODE (mode);
243           if (wider_mode != VOIDmode)
244             {
245               PUT_MODE (&all.zext, wider_mode);
246               PUT_MODE (&all.wide_mult, wider_mode);
247               PUT_MODE (&all.wide_lshr, wider_mode);
248               XEXP (&all.wide_lshr, 1) = GEN_INT (GET_MODE_BITSIZE (mode));
249
250               mul_widen_cost[speed][wider_mode]
251                 = rtx_cost (&all.wide_mult, SET, speed);
252               mul_highpart_cost[speed][mode]
253                 = rtx_cost (&all.wide_trunc, SET, speed);
254             }
255
256           shift_cost[speed][mode][0] = 0;
257           shiftadd_cost[speed][mode][0] = shiftsub_cost[speed][mode][0]
258             = add_cost[speed][mode];
259
260           n = MIN (MAX_BITS_PER_WORD, GET_MODE_BITSIZE (mode));
261           for (m = 1; m < n; m++)
262             {
263               XEXP (&all.shift, 1) = cint[m];
264               XEXP (&all.shift_mult, 1) = pow2[m];
265
266               shift_cost[speed][mode][m] = rtx_cost (&all.shift, SET, speed);
267               shiftadd_cost[speed][mode][m] = rtx_cost (&all.shift_add, SET, speed);
268               shiftsub_cost[speed][mode][m] = rtx_cost (&all.shift_sub, SET, speed);
269             }
270         }
271     }
272   default_rtl_profile ();
273 }
274
275 /* Return an rtx representing minus the value of X.
276    MODE is the intended mode of the result,
277    useful if X is a CONST_INT.  */
278
279 rtx
280 negate_rtx (enum machine_mode mode, rtx x)
281 {
282   rtx result = simplify_unary_operation (NEG, mode, x, mode);
283
284   if (result == 0)
285     result = expand_unop (mode, neg_optab, x, NULL_RTX, 0);
286
287   return result;
288 }
289
290 /* Report on the availability of insv/extv/extzv and the desired mode
291    of each of their operands.  Returns MAX_MACHINE_MODE if HAVE_foo
292    is false; else the mode of the specified operand.  If OPNO is -1,
293    all the caller cares about is whether the insn is available.  */
294 enum machine_mode
295 mode_for_extraction (enum extraction_pattern pattern, int opno)
296 {
297   const struct insn_data *data;
298
299   switch (pattern)
300     {
301     case EP_insv:
302       if (HAVE_insv)
303         {
304           data = &insn_data[CODE_FOR_insv];
305           break;
306         }
307       return MAX_MACHINE_MODE;
308
309     case EP_extv:
310       if (HAVE_extv)
311         {
312           data = &insn_data[CODE_FOR_extv];
313           break;
314         }
315       return MAX_MACHINE_MODE;
316
317     case EP_extzv:
318       if (HAVE_extzv)
319         {
320           data = &insn_data[CODE_FOR_extzv];
321           break;
322         }
323       return MAX_MACHINE_MODE;
324
325     default:
326       gcc_unreachable ();
327     }
328
329   if (opno == -1)
330     return VOIDmode;
331
332   /* Everyone who uses this function used to follow it with
333      if (result == VOIDmode) result = word_mode; */
334   if (data->operand[opno].mode == VOIDmode)
335     return word_mode;
336   return data->operand[opno].mode;
337 }
338
339 /* Return true if X, of mode MODE, matches the predicate for operand
340    OPNO of instruction ICODE.  Allow volatile memories, regardless of
341    the ambient volatile_ok setting.  */
342
343 static bool
344 check_predicate_volatile_ok (enum insn_code icode, int opno,
345                              rtx x, enum machine_mode mode)
346 {
347   bool save_volatile_ok, result;
348
349   save_volatile_ok = volatile_ok;
350   result = insn_data[(int) icode].operand[opno].predicate (x, mode);
351   volatile_ok = save_volatile_ok;
352   return result;
353 }
354 \f
355 /* A subroutine of store_bit_field, with the same arguments.  Return true
356    if the operation could be implemented.
357
358    If FALLBACK_P is true, fall back to store_fixed_bit_field if we have
359    no other way of implementing the operation.  If FALLBACK_P is false,
360    return false instead.  */
361
362 static bool
363 store_bit_field_1 (rtx str_rtx, unsigned HOST_WIDE_INT bitsize,
364                    unsigned HOST_WIDE_INT bitnum, enum machine_mode fieldmode,
365                    rtx value, bool fallback_p)
366 {
367   unsigned int unit
368     = (MEM_P (str_rtx)) ? BITS_PER_UNIT : BITS_PER_WORD;
369   unsigned HOST_WIDE_INT offset, bitpos;
370   rtx op0 = str_rtx;
371   int byte_offset;
372   rtx orig_value;
373
374   enum machine_mode op_mode = mode_for_extraction (EP_insv, 3);
375
376   while (GET_CODE (op0) == SUBREG)
377     {
378       /* The following line once was done only if WORDS_BIG_ENDIAN,
379          but I think that is a mistake.  WORDS_BIG_ENDIAN is
380          meaningful at a much higher level; when structures are copied
381          between memory and regs, the higher-numbered regs
382          always get higher addresses.  */
383       int inner_mode_size = GET_MODE_SIZE (GET_MODE (SUBREG_REG (op0)));
384       int outer_mode_size = GET_MODE_SIZE (GET_MODE (op0));
385       
386       byte_offset = 0;
387
388       /* Paradoxical subregs need special handling on big endian machines.  */
389       if (SUBREG_BYTE (op0) == 0 && inner_mode_size < outer_mode_size)
390         {
391           int difference = inner_mode_size - outer_mode_size;
392
393           if (WORDS_BIG_ENDIAN)
394             byte_offset += (difference / UNITS_PER_WORD) * UNITS_PER_WORD;
395           if (BYTES_BIG_ENDIAN)
396             byte_offset += difference % UNITS_PER_WORD;
397         }
398       else
399         byte_offset = SUBREG_BYTE (op0);
400
401       bitnum += byte_offset * BITS_PER_UNIT;
402       op0 = SUBREG_REG (op0);
403     }
404
405   /* No action is needed if the target is a register and if the field
406      lies completely outside that register.  This can occur if the source
407      code contains an out-of-bounds access to a small array.  */
408   if (REG_P (op0) && bitnum >= GET_MODE_BITSIZE (GET_MODE (op0)))
409     return true;
410
411   /* Use vec_set patterns for inserting parts of vectors whenever
412      available.  */
413   if (VECTOR_MODE_P (GET_MODE (op0))
414       && !MEM_P (op0)
415       && (optab_handler (vec_set_optab, GET_MODE (op0))->insn_code
416           != CODE_FOR_nothing)
417       && fieldmode == GET_MODE_INNER (GET_MODE (op0))
418       && bitsize == GET_MODE_BITSIZE (GET_MODE_INNER (GET_MODE (op0)))
419       && !(bitnum % GET_MODE_BITSIZE (GET_MODE_INNER (GET_MODE (op0)))))
420     {
421       enum machine_mode outermode = GET_MODE (op0);
422       enum machine_mode innermode = GET_MODE_INNER (outermode);
423       int icode = (int) optab_handler (vec_set_optab, outermode)->insn_code;
424       int pos = bitnum / GET_MODE_BITSIZE (innermode);
425       rtx rtxpos = GEN_INT (pos);
426       rtx src = value;
427       rtx dest = op0;
428       rtx pat, seq;
429       enum machine_mode mode0 = insn_data[icode].operand[0].mode;
430       enum machine_mode mode1 = insn_data[icode].operand[1].mode;
431       enum machine_mode mode2 = insn_data[icode].operand[2].mode;
432
433       start_sequence ();
434
435       if (! (*insn_data[icode].operand[1].predicate) (src, mode1))
436         src = copy_to_mode_reg (mode1, src);
437
438       if (! (*insn_data[icode].operand[2].predicate) (rtxpos, mode2))
439         rtxpos = copy_to_mode_reg (mode1, rtxpos);
440
441       /* We could handle this, but we should always be called with a pseudo
442          for our targets and all insns should take them as outputs.  */
443       gcc_assert ((*insn_data[icode].operand[0].predicate) (dest, mode0)
444                   && (*insn_data[icode].operand[1].predicate) (src, mode1)
445                   && (*insn_data[icode].operand[2].predicate) (rtxpos, mode2));
446       pat = GEN_FCN (icode) (dest, src, rtxpos);
447       seq = get_insns ();
448       end_sequence ();
449       if (pat)
450         {
451           emit_insn (seq);
452           emit_insn (pat);
453           return true;
454         }
455     }
456
457   /* If the target is a register, overwriting the entire object, or storing
458      a full-word or multi-word field can be done with just a SUBREG.
459
460      If the target is memory, storing any naturally aligned field can be
461      done with a simple store.  For targets that support fast unaligned
462      memory, any naturally sized, unit aligned field can be done directly.  */
463
464   offset = bitnum / unit;
465   bitpos = bitnum % unit;
466   byte_offset = (bitnum % BITS_PER_WORD) / BITS_PER_UNIT
467                 + (offset * UNITS_PER_WORD);
468
469   if (bitpos == 0
470       && bitsize == GET_MODE_BITSIZE (fieldmode)
471       && (!MEM_P (op0)
472           ? ((GET_MODE_SIZE (fieldmode) >= UNITS_PER_WORD
473              || GET_MODE_SIZE (GET_MODE (op0)) == GET_MODE_SIZE (fieldmode))
474              && byte_offset % GET_MODE_SIZE (fieldmode) == 0)
475           : (! SLOW_UNALIGNED_ACCESS (fieldmode, MEM_ALIGN (op0))
476              || (offset * BITS_PER_UNIT % bitsize == 0
477                  && MEM_ALIGN (op0) % GET_MODE_BITSIZE (fieldmode) == 0))))
478     {
479       if (MEM_P (op0))
480         op0 = adjust_address (op0, fieldmode, offset);
481       else if (GET_MODE (op0) != fieldmode)
482         op0 = simplify_gen_subreg (fieldmode, op0, GET_MODE (op0),
483                                    byte_offset);
484       emit_move_insn (op0, value);
485       return true;
486     }
487
488   /* Make sure we are playing with integral modes.  Pun with subregs
489      if we aren't.  This must come after the entire register case above,
490      since that case is valid for any mode.  The following cases are only
491      valid for integral modes.  */
492   {
493     enum machine_mode imode = int_mode_for_mode (GET_MODE (op0));
494     if (imode != GET_MODE (op0))
495       {
496         if (MEM_P (op0))
497           op0 = adjust_address (op0, imode, 0);
498         else
499           {
500             gcc_assert (imode != BLKmode);
501             op0 = gen_lowpart (imode, op0);
502           }
503       }
504   }
505
506   /* We may be accessing data outside the field, which means
507      we can alias adjacent data.  */
508   if (MEM_P (op0))
509     {
510       op0 = shallow_copy_rtx (op0);
511       set_mem_alias_set (op0, 0);
512       set_mem_expr (op0, 0);
513     }
514
515   /* If OP0 is a register, BITPOS must count within a word.
516      But as we have it, it counts within whatever size OP0 now has.
517      On a bigendian machine, these are not the same, so convert.  */
518   if (BYTES_BIG_ENDIAN
519       && !MEM_P (op0)
520       && unit > GET_MODE_BITSIZE (GET_MODE (op0)))
521     bitpos += unit - GET_MODE_BITSIZE (GET_MODE (op0));
522
523   /* Storing an lsb-aligned field in a register
524      can be done with a movestrict instruction.  */
525
526   if (!MEM_P (op0)
527       && (BYTES_BIG_ENDIAN ? bitpos + bitsize == unit : bitpos == 0)
528       && bitsize == GET_MODE_BITSIZE (fieldmode)
529       && (optab_handler (movstrict_optab, fieldmode)->insn_code
530           != CODE_FOR_nothing))
531     {
532       int icode = optab_handler (movstrict_optab, fieldmode)->insn_code;
533       rtx insn;
534       rtx start = get_last_insn ();
535       rtx arg0 = op0;
536
537       /* Get appropriate low part of the value being stored.  */
538       if (GET_CODE (value) == CONST_INT || REG_P (value))
539         value = gen_lowpart (fieldmode, value);
540       else if (!(GET_CODE (value) == SYMBOL_REF
541                  || GET_CODE (value) == LABEL_REF
542                  || GET_CODE (value) == CONST))
543         value = convert_to_mode (fieldmode, value, 0);
544
545       if (! (*insn_data[icode].operand[1].predicate) (value, fieldmode))
546         value = copy_to_mode_reg (fieldmode, value);
547
548       if (GET_CODE (op0) == SUBREG)
549         {
550           /* Else we've got some float mode source being extracted into
551              a different float mode destination -- this combination of
552              subregs results in Severe Tire Damage.  */
553           gcc_assert (GET_MODE (SUBREG_REG (op0)) == fieldmode
554                       || GET_MODE_CLASS (fieldmode) == MODE_INT
555                       || GET_MODE_CLASS (fieldmode) == MODE_PARTIAL_INT);
556           arg0 = SUBREG_REG (op0);
557         }
558
559       insn = (GEN_FCN (icode)
560                  (gen_rtx_SUBREG (fieldmode, arg0,
561                                   (bitnum % BITS_PER_WORD) / BITS_PER_UNIT
562                                   + (offset * UNITS_PER_WORD)),
563                                   value));
564       if (insn)
565         {
566           emit_insn (insn);
567           return true;
568         }
569       delete_insns_since (start);
570     }
571
572   /* Handle fields bigger than a word.  */
573
574   if (bitsize > BITS_PER_WORD)
575     {
576       /* Here we transfer the words of the field
577          in the order least significant first.
578          This is because the most significant word is the one which may
579          be less than full.
580          However, only do that if the value is not BLKmode.  */
581
582       unsigned int backwards = WORDS_BIG_ENDIAN && fieldmode != BLKmode;
583       unsigned int nwords = (bitsize + (BITS_PER_WORD - 1)) / BITS_PER_WORD;
584       unsigned int i;
585       rtx last;
586
587       /* This is the mode we must force value to, so that there will be enough
588          subwords to extract.  Note that fieldmode will often (always?) be
589          VOIDmode, because that is what store_field uses to indicate that this
590          is a bit field, but passing VOIDmode to operand_subword_force
591          is not allowed.  */
592       fieldmode = GET_MODE (value);
593       if (fieldmode == VOIDmode)
594         fieldmode = smallest_mode_for_size (nwords * BITS_PER_WORD, MODE_INT);
595
596       last = get_last_insn ();
597       for (i = 0; i < nwords; i++)
598         {
599           /* If I is 0, use the low-order word in both field and target;
600              if I is 1, use the next to lowest word; and so on.  */
601           unsigned int wordnum = (backwards ? nwords - i - 1 : i);
602           unsigned int bit_offset = (backwards
603                                      ? MAX ((int) bitsize - ((int) i + 1)
604                                             * BITS_PER_WORD,
605                                             0)
606                                      : (int) i * BITS_PER_WORD);
607           rtx value_word = operand_subword_force (value, wordnum, fieldmode);
608
609           if (!store_bit_field_1 (op0, MIN (BITS_PER_WORD,
610                                             bitsize - i * BITS_PER_WORD),
611                                   bitnum + bit_offset, word_mode,
612                                   value_word, fallback_p))
613             {
614               delete_insns_since (last);
615               return false;
616             }
617         }
618       return true;
619     }
620
621   /* From here on we can assume that the field to be stored in is
622      a full-word (whatever type that is), since it is shorter than a word.  */
623
624   /* OFFSET is the number of words or bytes (UNIT says which)
625      from STR_RTX to the first word or byte containing part of the field.  */
626
627   if (!MEM_P (op0))
628     {
629       if (offset != 0
630           || GET_MODE_SIZE (GET_MODE (op0)) > UNITS_PER_WORD)
631         {
632           if (!REG_P (op0))
633             {
634               /* Since this is a destination (lvalue), we can't copy
635                  it to a pseudo.  We can remove a SUBREG that does not
636                  change the size of the operand.  Such a SUBREG may
637                  have been added above.  */
638               gcc_assert (GET_CODE (op0) == SUBREG
639                           && (GET_MODE_SIZE (GET_MODE (op0))
640                               == GET_MODE_SIZE (GET_MODE (SUBREG_REG (op0)))));
641               op0 = SUBREG_REG (op0);
642             }
643           op0 = gen_rtx_SUBREG (mode_for_size (BITS_PER_WORD, MODE_INT, 0),
644                                 op0, (offset * UNITS_PER_WORD));
645         }
646       offset = 0;
647     }
648
649   /* If VALUE has a floating-point or complex mode, access it as an
650      integer of the corresponding size.  This can occur on a machine
651      with 64 bit registers that uses SFmode for float.  It can also
652      occur for unaligned float or complex fields.  */
653   orig_value = value;
654   if (GET_MODE (value) != VOIDmode
655       && GET_MODE_CLASS (GET_MODE (value)) != MODE_INT
656       && GET_MODE_CLASS (GET_MODE (value)) != MODE_PARTIAL_INT)
657     {
658       value = gen_reg_rtx (int_mode_for_mode (GET_MODE (value)));
659       emit_move_insn (gen_lowpart (GET_MODE (orig_value), value), orig_value);
660     }
661
662   /* Now OFFSET is nonzero only if OP0 is memory
663      and is therefore always measured in bytes.  */
664
665   if (HAVE_insv
666       && GET_MODE (value) != BLKmode
667       && bitsize > 0
668       && GET_MODE_BITSIZE (op_mode) >= bitsize
669       && ! ((REG_P (op0) || GET_CODE (op0) == SUBREG)
670             && (bitsize + bitpos > GET_MODE_BITSIZE (op_mode)))
671       && insn_data[CODE_FOR_insv].operand[1].predicate (GEN_INT (bitsize),
672                                                         VOIDmode)
673       && check_predicate_volatile_ok (CODE_FOR_insv, 0, op0, VOIDmode))
674     {
675       int xbitpos = bitpos;
676       rtx value1;
677       rtx xop0 = op0;
678       rtx last = get_last_insn ();
679       rtx pat;
680
681       /* Add OFFSET into OP0's address.  */
682       if (MEM_P (xop0))
683         xop0 = adjust_address (xop0, byte_mode, offset);
684
685       /* If xop0 is a register, we need it in OP_MODE
686          to make it acceptable to the format of insv.  */
687       if (GET_CODE (xop0) == SUBREG)
688         /* We can't just change the mode, because this might clobber op0,
689            and we will need the original value of op0 if insv fails.  */
690         xop0 = gen_rtx_SUBREG (op_mode, SUBREG_REG (xop0), SUBREG_BYTE (xop0));
691       if (REG_P (xop0) && GET_MODE (xop0) != op_mode)
692         xop0 = gen_rtx_SUBREG (op_mode, xop0, 0);
693
694       /* On big-endian machines, we count bits from the most significant.
695          If the bit field insn does not, we must invert.  */
696
697       if (BITS_BIG_ENDIAN != BYTES_BIG_ENDIAN)
698         xbitpos = unit - bitsize - xbitpos;
699
700       /* We have been counting XBITPOS within UNIT.
701          Count instead within the size of the register.  */
702       if (BITS_BIG_ENDIAN && !MEM_P (xop0))
703         xbitpos += GET_MODE_BITSIZE (op_mode) - unit;
704
705       unit = GET_MODE_BITSIZE (op_mode);
706
707       /* Convert VALUE to op_mode (which insv insn wants) in VALUE1.  */
708       value1 = value;
709       if (GET_MODE (value) != op_mode)
710         {
711           if (GET_MODE_BITSIZE (GET_MODE (value)) >= bitsize)
712             {
713               /* Optimization: Don't bother really extending VALUE
714                  if it has all the bits we will actually use.  However,
715                  if we must narrow it, be sure we do it correctly.  */
716
717               if (GET_MODE_SIZE (GET_MODE (value)) < GET_MODE_SIZE (op_mode))
718                 {
719                   rtx tmp;
720
721                   tmp = simplify_subreg (op_mode, value1, GET_MODE (value), 0);
722                   if (! tmp)
723                     tmp = simplify_gen_subreg (op_mode,
724                                                force_reg (GET_MODE (value),
725                                                           value1),
726                                                GET_MODE (value), 0);
727                   value1 = tmp;
728                 }
729               else
730                 value1 = gen_lowpart (op_mode, value1);
731             }
732           else if (GET_CODE (value) == CONST_INT)
733             value1 = gen_int_mode (INTVAL (value), op_mode);
734           else
735             /* Parse phase is supposed to make VALUE's data type
736                match that of the component reference, which is a type
737                at least as wide as the field; so VALUE should have
738                a mode that corresponds to that type.  */
739             gcc_assert (CONSTANT_P (value));
740         }
741
742       /* If this machine's insv insists on a register,
743          get VALUE1 into a register.  */
744       if (! ((*insn_data[(int) CODE_FOR_insv].operand[3].predicate)
745              (value1, op_mode)))
746         value1 = force_reg (op_mode, value1);
747
748       pat = gen_insv (xop0, GEN_INT (bitsize), GEN_INT (xbitpos), value1);
749       if (pat)
750         {
751           emit_insn (pat);
752
753           /* If the mode of the insertion is wider than the mode of the
754              target register we created a paradoxical subreg for the
755              target.  Truncate the paradoxical subreg of the target to
756              itself properly.  */
757           if (!TRULY_NOOP_TRUNCATION (GET_MODE_BITSIZE (GET_MODE (op0)),
758                                       GET_MODE_BITSIZE (op_mode))
759               && (REG_P (xop0)
760                   || GET_CODE (xop0) == SUBREG))
761               convert_move (op0, xop0, true);
762           return true;
763         }
764       delete_insns_since (last);
765     }
766
767   /* If OP0 is a memory, try copying it to a register and seeing if a
768      cheap register alternative is available.  */
769   if (HAVE_insv && MEM_P (op0))
770     {
771       enum machine_mode bestmode;
772
773       /* Get the mode to use for inserting into this field.  If OP0 is
774          BLKmode, get the smallest mode consistent with the alignment. If
775          OP0 is a non-BLKmode object that is no wider than OP_MODE, use its
776          mode. Otherwise, use the smallest mode containing the field.  */
777
778       if (GET_MODE (op0) == BLKmode
779           || (op_mode != MAX_MACHINE_MODE
780               && GET_MODE_SIZE (GET_MODE (op0)) > GET_MODE_SIZE (op_mode)))
781         bestmode = get_best_mode (bitsize, bitnum, MEM_ALIGN (op0),
782                                   (op_mode == MAX_MACHINE_MODE
783                                    ? VOIDmode : op_mode),
784                                   MEM_VOLATILE_P (op0));
785       else
786         bestmode = GET_MODE (op0);
787
788       if (bestmode != VOIDmode
789           && GET_MODE_SIZE (bestmode) >= GET_MODE_SIZE (fieldmode)
790           && !(SLOW_UNALIGNED_ACCESS (bestmode, MEM_ALIGN (op0))
791                && GET_MODE_BITSIZE (bestmode) > MEM_ALIGN (op0)))
792         {
793           rtx last, tempreg, xop0;
794           unsigned HOST_WIDE_INT xoffset, xbitpos;
795
796           last = get_last_insn ();
797
798           /* Adjust address to point to the containing unit of
799              that mode.  Compute the offset as a multiple of this unit,
800              counting in bytes.  */
801           unit = GET_MODE_BITSIZE (bestmode);
802           xoffset = (bitnum / unit) * GET_MODE_SIZE (bestmode);
803           xbitpos = bitnum % unit;
804           xop0 = adjust_address (op0, bestmode, xoffset);
805
806           /* Fetch that unit, store the bitfield in it, then store
807              the unit.  */
808           tempreg = copy_to_reg (xop0);
809           if (store_bit_field_1 (tempreg, bitsize, xbitpos,
810                                  fieldmode, orig_value, false))
811             {
812               emit_move_insn (xop0, tempreg);
813               return true;
814             }
815           delete_insns_since (last);
816         }
817     }
818
819   if (!fallback_p)
820     return false;
821
822   store_fixed_bit_field (op0, offset, bitsize, bitpos, value);
823   return true;
824 }
825
826 /* Generate code to store value from rtx VALUE
827    into a bit-field within structure STR_RTX
828    containing BITSIZE bits starting at bit BITNUM.
829    FIELDMODE is the machine-mode of the FIELD_DECL node for this field.  */
830
831 void
832 store_bit_field (rtx str_rtx, unsigned HOST_WIDE_INT bitsize,
833                  unsigned HOST_WIDE_INT bitnum, enum machine_mode fieldmode,
834                  rtx value)
835 {
836   if (!store_bit_field_1 (str_rtx, bitsize, bitnum, fieldmode, value, true))
837     gcc_unreachable ();
838 }
839 \f
840 /* Use shifts and boolean operations to store VALUE
841    into a bit field of width BITSIZE
842    in a memory location specified by OP0 except offset by OFFSET bytes.
843      (OFFSET must be 0 if OP0 is a register.)
844    The field starts at position BITPOS within the byte.
845     (If OP0 is a register, it may be a full word or a narrower mode,
846      but BITPOS still counts within a full word,
847      which is significant on bigendian machines.)  */
848
849 static void
850 store_fixed_bit_field (rtx op0, unsigned HOST_WIDE_INT offset,
851                        unsigned HOST_WIDE_INT bitsize,
852                        unsigned HOST_WIDE_INT bitpos, rtx value)
853 {
854   enum machine_mode mode;
855   unsigned int total_bits = BITS_PER_WORD;
856   rtx temp;
857   int all_zero = 0;
858   int all_one = 0;
859
860   /* There is a case not handled here:
861      a structure with a known alignment of just a halfword
862      and a field split across two aligned halfwords within the structure.
863      Or likewise a structure with a known alignment of just a byte
864      and a field split across two bytes.
865      Such cases are not supposed to be able to occur.  */
866
867   if (REG_P (op0) || GET_CODE (op0) == SUBREG)
868     {
869       gcc_assert (!offset);
870       /* Special treatment for a bit field split across two registers.  */
871       if (bitsize + bitpos > BITS_PER_WORD)
872         {
873           store_split_bit_field (op0, bitsize, bitpos, value);
874           return;
875         }
876     }
877   else
878     {
879       /* Get the proper mode to use for this field.  We want a mode that
880          includes the entire field.  If such a mode would be larger than
881          a word, we won't be doing the extraction the normal way.
882          We don't want a mode bigger than the destination.  */
883
884       mode = GET_MODE (op0);
885       if (GET_MODE_BITSIZE (mode) == 0
886           || GET_MODE_BITSIZE (mode) > GET_MODE_BITSIZE (word_mode))
887         mode = word_mode;
888       mode = get_best_mode (bitsize, bitpos + offset * BITS_PER_UNIT,
889                             MEM_ALIGN (op0), mode, MEM_VOLATILE_P (op0));
890
891       if (mode == VOIDmode)
892         {
893           /* The only way this should occur is if the field spans word
894              boundaries.  */
895           store_split_bit_field (op0, bitsize, bitpos + offset * BITS_PER_UNIT,
896                                  value);
897           return;
898         }
899
900       total_bits = GET_MODE_BITSIZE (mode);
901
902       /* Make sure bitpos is valid for the chosen mode.  Adjust BITPOS to
903          be in the range 0 to total_bits-1, and put any excess bytes in
904          OFFSET.  */
905       if (bitpos >= total_bits)
906         {
907           offset += (bitpos / total_bits) * (total_bits / BITS_PER_UNIT);
908           bitpos -= ((bitpos / total_bits) * (total_bits / BITS_PER_UNIT)
909                      * BITS_PER_UNIT);
910         }
911
912       /* Get ref to an aligned byte, halfword, or word containing the field.
913          Adjust BITPOS to be position within a word,
914          and OFFSET to be the offset of that word.
915          Then alter OP0 to refer to that word.  */
916       bitpos += (offset % (total_bits / BITS_PER_UNIT)) * BITS_PER_UNIT;
917       offset -= (offset % (total_bits / BITS_PER_UNIT));
918       op0 = adjust_address (op0, mode, offset);
919     }
920
921   mode = GET_MODE (op0);
922
923   /* Now MODE is either some integral mode for a MEM as OP0,
924      or is a full-word for a REG as OP0.  TOTAL_BITS corresponds.
925      The bit field is contained entirely within OP0.
926      BITPOS is the starting bit number within OP0.
927      (OP0's mode may actually be narrower than MODE.)  */
928
929   if (BYTES_BIG_ENDIAN)
930       /* BITPOS is the distance between our msb
931          and that of the containing datum.
932          Convert it to the distance from the lsb.  */
933       bitpos = total_bits - bitsize - bitpos;
934
935   /* Now BITPOS is always the distance between our lsb
936      and that of OP0.  */
937
938   /* Shift VALUE left by BITPOS bits.  If VALUE is not constant,
939      we must first convert its mode to MODE.  */
940
941   if (GET_CODE (value) == CONST_INT)
942     {
943       HOST_WIDE_INT v = INTVAL (value);
944
945       if (bitsize < HOST_BITS_PER_WIDE_INT)
946         v &= ((HOST_WIDE_INT) 1 << bitsize) - 1;
947
948       if (v == 0)
949         all_zero = 1;
950       else if ((bitsize < HOST_BITS_PER_WIDE_INT
951                 && v == ((HOST_WIDE_INT) 1 << bitsize) - 1)
952                || (bitsize == HOST_BITS_PER_WIDE_INT && v == -1))
953         all_one = 1;
954
955       value = lshift_value (mode, value, bitpos, bitsize);
956     }
957   else
958     {
959       int must_and = (GET_MODE_BITSIZE (GET_MODE (value)) != bitsize
960                       && bitpos + bitsize != GET_MODE_BITSIZE (mode));
961
962       if (GET_MODE (value) != mode)
963         value = convert_to_mode (mode, value, 1);
964
965       if (must_and)
966         value = expand_binop (mode, and_optab, value,
967                               mask_rtx (mode, 0, bitsize, 0),
968                               NULL_RTX, 1, OPTAB_LIB_WIDEN);
969       if (bitpos > 0)
970         value = expand_shift (LSHIFT_EXPR, mode, value,
971                               build_int_cst (NULL_TREE, bitpos), NULL_RTX, 1);
972     }
973
974   /* Now clear the chosen bits in OP0,
975      except that if VALUE is -1 we need not bother.  */
976   /* We keep the intermediates in registers to allow CSE to combine
977      consecutive bitfield assignments.  */
978
979   temp = force_reg (mode, op0);
980
981   if (! all_one)
982     {
983       temp = expand_binop (mode, and_optab, temp,
984                            mask_rtx (mode, bitpos, bitsize, 1),
985                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
986       temp = force_reg (mode, temp);
987     }
988
989   /* Now logical-or VALUE into OP0, unless it is zero.  */
990
991   if (! all_zero)
992     {
993       temp = expand_binop (mode, ior_optab, temp, value,
994                            NULL_RTX, 1, OPTAB_LIB_WIDEN);
995       temp = force_reg (mode, temp);
996     }
997
998   if (op0 != temp)
999     {
1000       op0 = copy_rtx (op0);
1001       emit_move_insn (op0, temp);
1002     }
1003 }
1004 \f
1005 /* Store a bit field that is split across multiple accessible memory objects.
1006
1007    OP0 is the REG, SUBREG or MEM rtx for the first of the objects.
1008    BITSIZE is the field width; BITPOS the position of its first bit
1009    (within the word).
1010    VALUE is the value to store.
1011
1012    This does not yet handle fields wider than BITS_PER_WORD.  */
1013
1014 static void
1015 store_split_bit_field (rtx op0, unsigned HOST_WIDE_INT bitsize,
1016                        unsigned HOST_WIDE_INT bitpos, rtx value)
1017 {
1018   unsigned int unit;
1019   unsigned int bitsdone = 0;
1020
1021   /* Make sure UNIT isn't larger than BITS_PER_WORD, we can only handle that
1022      much at a time.  */
1023   if (REG_P (op0) || GET_CODE (op0) == SUBREG)
1024     unit = BITS_PER_WORD;
1025   else
1026     unit = MIN (MEM_ALIGN (op0), BITS_PER_WORD);
1027
1028   /* If VALUE is a constant other than a CONST_INT, get it into a register in
1029      WORD_MODE.  If we can do this using gen_lowpart_common, do so.  Note
1030      that VALUE might be a floating-point constant.  */
1031   if (CONSTANT_P (value) && GET_CODE (value) != CONST_INT)
1032     {
1033       rtx word = gen_lowpart_common (word_mode, value);
1034
1035       if (word && (value != word))
1036         value = word;
1037       else
1038         value = gen_lowpart_common (word_mode,
1039                                     force_reg (GET_MODE (value) != VOIDmode
1040                                                ? GET_MODE (value)
1041                                                : word_mode, value));
1042     }
1043
1044   while (bitsdone < bitsize)
1045     {
1046       unsigned HOST_WIDE_INT thissize;
1047       rtx part, word;
1048       unsigned HOST_WIDE_INT thispos;
1049       unsigned HOST_WIDE_INT offset;
1050
1051       offset = (bitpos + bitsdone) / unit;
1052       thispos = (bitpos + bitsdone) % unit;
1053
1054       /* THISSIZE must not overrun a word boundary.  Otherwise,
1055          store_fixed_bit_field will call us again, and we will mutually
1056          recurse forever.  */
1057       thissize = MIN (bitsize - bitsdone, BITS_PER_WORD);
1058       thissize = MIN (thissize, unit - thispos);
1059
1060       if (BYTES_BIG_ENDIAN)
1061         {
1062           int total_bits;
1063
1064           /* We must do an endian conversion exactly the same way as it is
1065              done in extract_bit_field, so that the two calls to
1066              extract_fixed_bit_field will have comparable arguments.  */
1067           if (!MEM_P (value) || GET_MODE (value) == BLKmode)
1068             total_bits = BITS_PER_WORD;
1069           else
1070             total_bits = GET_MODE_BITSIZE (GET_MODE (value));
1071
1072           /* Fetch successively less significant portions.  */
1073           if (GET_CODE (value) == CONST_INT)
1074             part = GEN_INT (((unsigned HOST_WIDE_INT) (INTVAL (value))
1075                              >> (bitsize - bitsdone - thissize))
1076                             & (((HOST_WIDE_INT) 1 << thissize) - 1));
1077           else
1078             /* The args are chosen so that the last part includes the
1079                lsb.  Give extract_bit_field the value it needs (with
1080                endianness compensation) to fetch the piece we want.  */
1081             part = extract_fixed_bit_field (word_mode, value, 0, thissize,
1082                                             total_bits - bitsize + bitsdone,
1083                                             NULL_RTX, 1);
1084         }
1085       else
1086         {
1087           /* Fetch successively more significant portions.  */
1088           if (GET_CODE (value) == CONST_INT)
1089             part = GEN_INT (((unsigned HOST_WIDE_INT) (INTVAL (value))
1090                              >> bitsdone)
1091                             & (((HOST_WIDE_INT) 1 << thissize) - 1));
1092           else
1093             part = extract_fixed_bit_field (word_mode, value, 0, thissize,
1094                                             bitsdone, NULL_RTX, 1);
1095         }
1096
1097       /* If OP0 is a register, then handle OFFSET here.
1098
1099          When handling multiword bitfields, extract_bit_field may pass
1100          down a word_mode SUBREG of a larger REG for a bitfield that actually
1101          crosses a word boundary.  Thus, for a SUBREG, we must find
1102          the current word starting from the base register.  */
1103       if (GET_CODE (op0) == SUBREG)
1104         {
1105           int word_offset = (SUBREG_BYTE (op0) / UNITS_PER_WORD) + offset;
1106           word = operand_subword_force (SUBREG_REG (op0), word_offset,
1107                                         GET_MODE (SUBREG_REG (op0)));
1108           offset = 0;
1109         }
1110       else if (REG_P (op0))
1111         {
1112           word = operand_subword_force (op0, offset, GET_MODE (op0));
1113           offset = 0;
1114         }
1115       else
1116         word = op0;
1117
1118       /* OFFSET is in UNITs, and UNIT is in bits.
1119          store_fixed_bit_field wants offset in bytes.  */
1120       store_fixed_bit_field (word, offset * unit / BITS_PER_UNIT, thissize,
1121                              thispos, part);
1122       bitsdone += thissize;
1123     }
1124 }
1125 \f
1126 /* A subroutine of extract_bit_field_1 that converts return value X
1127    to either MODE or TMODE.  MODE, TMODE and UNSIGNEDP are arguments
1128    to extract_bit_field.  */
1129
1130 static rtx
1131 convert_extracted_bit_field (rtx x, enum machine_mode mode,
1132                              enum machine_mode tmode, bool unsignedp)
1133 {
1134   if (GET_MODE (x) == tmode || GET_MODE (x) == mode)
1135     return x;
1136
1137   /* If the x mode is not a scalar integral, first convert to the
1138      integer mode of that size and then access it as a floating-point
1139      value via a SUBREG.  */
1140   if (!SCALAR_INT_MODE_P (tmode))
1141     {
1142       enum machine_mode smode;
1143
1144       smode = mode_for_size (GET_MODE_BITSIZE (tmode), MODE_INT, 0);
1145       x = convert_to_mode (smode, x, unsignedp);
1146       x = force_reg (smode, x);
1147       return gen_lowpart (tmode, x);
1148     }
1149
1150   return convert_to_mode (tmode, x, unsignedp);
1151 }
1152
1153 /* A subroutine of extract_bit_field, with the same arguments.
1154    If FALLBACK_P is true, fall back to extract_fixed_bit_field
1155    if we can find no other means of implementing the operation.
1156    if FALLBACK_P is false, return NULL instead.  */
1157
1158 static rtx
1159 extract_bit_field_1 (rtx str_rtx, unsigned HOST_WIDE_INT bitsize,
1160                      unsigned HOST_WIDE_INT bitnum, int unsignedp, rtx target,
1161                      enum machine_mode mode, enum machine_mode tmode,
1162                      bool fallback_p)
1163 {
1164   unsigned int unit
1165     = (MEM_P (str_rtx)) ? BITS_PER_UNIT : BITS_PER_WORD;
1166   unsigned HOST_WIDE_INT offset, bitpos;
1167   rtx op0 = str_rtx;
1168   enum machine_mode int_mode;
1169   enum machine_mode ext_mode;
1170   enum machine_mode mode1;
1171   enum insn_code icode;
1172   int byte_offset;
1173
1174   if (tmode == VOIDmode)
1175     tmode = mode;
1176
1177   while (GET_CODE (op0) == SUBREG)
1178     {
1179       bitnum += SUBREG_BYTE (op0) * BITS_PER_UNIT;
1180       op0 = SUBREG_REG (op0);
1181     }
1182
1183   /* If we have an out-of-bounds access to a register, just return an
1184      uninitialized register of the required mode.  This can occur if the
1185      source code contains an out-of-bounds access to a small array.  */
1186   if (REG_P (op0) && bitnum >= GET_MODE_BITSIZE (GET_MODE (op0)))
1187     return gen_reg_rtx (tmode);
1188
1189   if (REG_P (op0)
1190       && mode == GET_MODE (op0)
1191       && bitnum == 0
1192       && bitsize == GET_MODE_BITSIZE (GET_MODE (op0)))
1193     {
1194       /* We're trying to extract a full register from itself.  */
1195       return op0;
1196     }
1197
1198   /* See if we can get a better vector mode before extracting.  */
1199   if (VECTOR_MODE_P (GET_MODE (op0))
1200       && !MEM_P (op0)
1201       && GET_MODE_INNER (GET_MODE (op0)) != tmode)
1202     {
1203       enum machine_mode new_mode;
1204       int nunits = GET_MODE_NUNITS (GET_MODE (op0));
1205
1206       if (GET_MODE_CLASS (tmode) == MODE_FLOAT)
1207         new_mode = MIN_MODE_VECTOR_FLOAT;
1208       else if (GET_MODE_CLASS (tmode) == MODE_FRACT)
1209         new_mode = MIN_MODE_VECTOR_FRACT;
1210       else if (GET_MODE_CLASS (tmode) == MODE_UFRACT)
1211         new_mode = MIN_MODE_VECTOR_UFRACT;
1212       else if (GET_MODE_CLASS (tmode) == MODE_ACCUM)
1213         new_mode = MIN_MODE_VECTOR_ACCUM;
1214       else if (GET_MODE_CLASS (tmode) == MODE_UACCUM)
1215         new_mode = MIN_MODE_VECTOR_UACCUM;
1216       else
1217         new_mode = MIN_MODE_VECTOR_INT;
1218
1219       for (; new_mode != VOIDmode ; new_mode = GET_MODE_WIDER_MODE (new_mode))
1220         if (GET_MODE_NUNITS (new_mode) == nunits
1221             && GET_MODE_SIZE (new_mode) == GET_MODE_SIZE (GET_MODE (op0))
1222             && targetm.vector_mode_supported_p (new_mode))
1223           break;
1224       if (new_mode != VOIDmode)
1225         op0 = gen_lowpart (new_mode, op0);
1226     }
1227
1228   /* Use vec_extract patterns for extracting parts of vectors whenever
1229      available.  */
1230   if (VECTOR_MODE_P (GET_MODE (op0))
1231       && !MEM_P (op0)
1232       && (optab_handler (vec_extract_optab, GET_MODE (op0))->insn_code
1233           != CODE_FOR_nothing)
1234       && ((bitnum + bitsize - 1) / GET_MODE_BITSIZE (GET_MODE_INNER (GET_MODE (op0)))
1235           == bitnum / GET_MODE_BITSIZE (GET_MODE_INNER (GET_MODE (op0)))))
1236     {
1237       enum machine_mode outermode = GET_MODE (op0);
1238       enum machine_mode innermode = GET_MODE_INNER (outermode);
1239       int icode = (int) optab_handler (vec_extract_optab, outermode)->insn_code;
1240       unsigned HOST_WIDE_INT pos = bitnum / GET_MODE_BITSIZE (innermode);
1241       rtx rtxpos = GEN_INT (pos);
1242       rtx src = op0;
1243       rtx dest = NULL, pat, seq;
1244       enum machine_mode mode0 = insn_data[icode].operand[0].mode;
1245       enum machine_mode mode1 = insn_data[icode].operand[1].mode;
1246       enum machine_mode mode2 = insn_data[icode].operand[2].mode;
1247
1248       if (innermode == tmode || innermode == mode)
1249         dest = target;
1250
1251       if (!dest)
1252         dest = gen_reg_rtx (innermode);
1253
1254       start_sequence ();
1255
1256       if (! (*insn_data[icode].operand[0].predicate) (dest, mode0))
1257         dest = copy_to_mode_reg (mode0, dest);
1258
1259       if (! (*insn_data[icode].operand[1].predicate) (src, mode1))
1260         src = copy_to_mode_reg (mode1, src);
1261
1262       if (! (*insn_data[icode].operand[2].predicate) (rtxpos, mode2))
1263         rtxpos = copy_to_mode_reg (mode1, rtxpos);
1264
1265       /* We could handle this, but we should always be called with a pseudo
1266          for our targets and all insns should take them as outputs.  */
1267       gcc_assert ((*insn_data[icode].operand[0].predicate) (dest, mode0)
1268                   && (*insn_data[icode].operand[1].predicate) (src, mode1)
1269                   && (*insn_data[icode].operand[2].predicate) (rtxpos, mode2));
1270
1271       pat = GEN_FCN (icode) (dest, src, rtxpos);
1272       seq = get_insns ();
1273       end_sequence ();
1274       if (pat)
1275         {
1276           emit_insn (seq);
1277           emit_insn (pat);
1278           if (mode0 != mode)
1279             return gen_lowpart (tmode, dest);
1280           return dest;
1281         }
1282     }
1283
1284   /* Make sure we are playing with integral modes.  Pun with subregs
1285      if we aren't.  */
1286   {
1287     enum machine_mode imode = int_mode_for_mode (GET_MODE (op0));
1288     if (imode != GET_MODE (op0))
1289       {
1290         if (MEM_P (op0))
1291           op0 = adjust_address (op0, imode, 0);
1292         else if (imode != BLKmode)
1293           {
1294             op0 = gen_lowpart (imode, op0);
1295
1296             /* If we got a SUBREG, force it into a register since we
1297                aren't going to be able to do another SUBREG on it.  */
1298             if (GET_CODE (op0) == SUBREG)
1299               op0 = force_reg (imode, op0);
1300           }
1301         else if (REG_P (op0))
1302           {
1303             rtx reg, subreg;
1304             imode = smallest_mode_for_size (GET_MODE_BITSIZE (GET_MODE (op0)),
1305                                             MODE_INT);
1306             reg = gen_reg_rtx (imode);
1307             subreg = gen_lowpart_SUBREG (GET_MODE (op0), reg);
1308             emit_move_insn (subreg, op0);
1309             op0 = reg;
1310             bitnum += SUBREG_BYTE (subreg) * BITS_PER_UNIT;
1311           }
1312         else
1313           {
1314             rtx mem = assign_stack_temp (GET_MODE (op0),
1315                                          GET_MODE_SIZE (GET_MODE (op0)), 0);
1316             emit_move_insn (mem, op0);
1317             op0 = adjust_address (mem, BLKmode, 0);
1318           }
1319       }
1320   }
1321
1322   /* We may be accessing data outside the field, which means
1323      we can alias adjacent data.  */
1324   if (MEM_P (op0))
1325     {
1326       op0 = shallow_copy_rtx (op0);
1327       set_mem_alias_set (op0, 0);
1328       set_mem_expr (op0, 0);
1329     }
1330
1331   /* Extraction of a full-word or multi-word value from a structure
1332      in a register or aligned memory can be done with just a SUBREG.
1333      A subword value in the least significant part of a register
1334      can also be extracted with a SUBREG.  For this, we need the
1335      byte offset of the value in op0.  */
1336
1337   bitpos = bitnum % unit;
1338   offset = bitnum / unit;
1339   byte_offset = bitpos / BITS_PER_UNIT + offset * UNITS_PER_WORD;
1340
1341   /* If OP0 is a register, BITPOS must count within a word.
1342      But as we have it, it counts within whatever size OP0 now has.
1343      On a bigendian machine, these are not the same, so convert.  */
1344   if (BYTES_BIG_ENDIAN
1345       && !MEM_P (op0)
1346       && unit > GET_MODE_BITSIZE (GET_MODE (op0)))
1347     bitpos += unit - GET_MODE_BITSIZE (GET_MODE (op0));
1348
1349   /* ??? We currently assume TARGET is at least as big as BITSIZE.
1350      If that's wrong, the solution is to test for it and set TARGET to 0
1351      if needed.  */
1352
1353   /* Only scalar integer modes can be converted via subregs.  There is an
1354      additional problem for FP modes here in that they can have a precision
1355      which is different from the size.  mode_for_size uses precision, but
1356      we want a mode based on the size, so we must avoid calling it for FP
1357      modes.  */
1358   mode1  = (SCALAR_INT_MODE_P (tmode)
1359             ? mode_for_size (bitsize, GET_MODE_CLASS (tmode), 0)
1360             : mode);
1361
1362   if (((bitsize >= BITS_PER_WORD && bitsize == GET_MODE_BITSIZE (mode)
1363         && bitpos % BITS_PER_WORD == 0)
1364        || (mode1 != BLKmode
1365            /* ??? The big endian test here is wrong.  This is correct
1366               if the value is in a register, and if mode_for_size is not
1367               the same mode as op0.  This causes us to get unnecessarily
1368               inefficient code from the Thumb port when -mbig-endian.  */
1369            && (BYTES_BIG_ENDIAN
1370                ? bitpos + bitsize == BITS_PER_WORD
1371                : bitpos == 0)))
1372       && ((!MEM_P (op0)
1373            && TRULY_NOOP_TRUNCATION (GET_MODE_BITSIZE (mode1),
1374                                      GET_MODE_BITSIZE (GET_MODE (op0)))
1375            && GET_MODE_SIZE (mode1) != 0
1376            && byte_offset % GET_MODE_SIZE (mode1) == 0)
1377           || (MEM_P (op0)
1378               && (! SLOW_UNALIGNED_ACCESS (mode, MEM_ALIGN (op0))
1379                   || (offset * BITS_PER_UNIT % bitsize == 0
1380                       && MEM_ALIGN (op0) % bitsize == 0)))))
1381     {
1382       if (MEM_P (op0))
1383         op0 = adjust_address (op0, mode1, offset);
1384       else if (mode1 != GET_MODE (op0))
1385         {
1386           rtx sub = simplify_gen_subreg (mode1, op0, GET_MODE (op0),
1387                                          byte_offset);
1388           if (sub == NULL)
1389             goto no_subreg_mode_swap;
1390           op0 = sub;
1391         }
1392       if (mode1 != mode)
1393         return convert_to_mode (tmode, op0, unsignedp);
1394       return op0;
1395     }
1396  no_subreg_mode_swap:
1397
1398   /* Handle fields bigger than a word.  */
1399
1400   if (bitsize > BITS_PER_WORD)
1401     {
1402       /* Here we transfer the words of the field
1403          in the order least significant first.
1404          This is because the most significant word is the one which may
1405          be less than full.  */
1406
1407       unsigned int nwords = (bitsize + (BITS_PER_WORD - 1)) / BITS_PER_WORD;
1408       unsigned int i;
1409
1410       if (target == 0 || !REG_P (target))
1411         target = gen_reg_rtx (mode);
1412
1413       /* Indicate for flow that the entire target reg is being set.  */
1414       emit_clobber (target);
1415
1416       for (i = 0; i < nwords; i++)
1417         {
1418           /* If I is 0, use the low-order word in both field and target;
1419              if I is 1, use the next to lowest word; and so on.  */
1420           /* Word number in TARGET to use.  */
1421           unsigned int wordnum
1422             = (WORDS_BIG_ENDIAN
1423                ? GET_MODE_SIZE (GET_MODE (target)) / UNITS_PER_WORD - i - 1
1424                : i);
1425           /* Offset from start of field in OP0.  */
1426           unsigned int bit_offset = (WORDS_BIG_ENDIAN
1427                                      ? MAX (0, ((int) bitsize - ((int) i + 1)
1428                                                 * (int) BITS_PER_WORD))
1429                                      : (int) i * BITS_PER_WORD);
1430           rtx target_part = operand_subword (target, wordnum, 1, VOIDmode);
1431           rtx result_part
1432             = extract_bit_field (op0, MIN (BITS_PER_WORD,
1433                                            bitsize - i * BITS_PER_WORD),
1434                                  bitnum + bit_offset, 1, target_part, mode,
1435                                  word_mode);
1436
1437           gcc_assert (target_part);
1438
1439           if (result_part != target_part)
1440             emit_move_insn (target_part, result_part);
1441         }
1442
1443       if (unsignedp)
1444         {
1445           /* Unless we've filled TARGET, the upper regs in a multi-reg value
1446              need to be zero'd out.  */
1447           if (GET_MODE_SIZE (GET_MODE (target)) > nwords * UNITS_PER_WORD)
1448             {
1449               unsigned int i, total_words;
1450
1451               total_words = GET_MODE_SIZE (GET_MODE (target)) / UNITS_PER_WORD;
1452               for (i = nwords; i < total_words; i++)
1453                 emit_move_insn
1454                   (operand_subword (target,
1455                                     WORDS_BIG_ENDIAN ? total_words - i - 1 : i,
1456                                     1, VOIDmode),
1457                    const0_rtx);
1458             }
1459           return target;
1460         }
1461
1462       /* Signed bit field: sign-extend with two arithmetic shifts.  */
1463       target = expand_shift (LSHIFT_EXPR, mode, target,
1464                              build_int_cst (NULL_TREE,
1465                                             GET_MODE_BITSIZE (mode) - bitsize),
1466                              NULL_RTX, 0);
1467       return expand_shift (RSHIFT_EXPR, mode, target,
1468                            build_int_cst (NULL_TREE,
1469                                           GET_MODE_BITSIZE (mode) - bitsize),
1470                            NULL_RTX, 0);
1471     }
1472
1473   /* From here on we know the desired field is smaller than a word.  */
1474
1475   /* Check if there is a correspondingly-sized integer field, so we can
1476      safely extract it as one size of integer, if necessary; then
1477      truncate or extend to the size that is wanted; then use SUBREGs or
1478      convert_to_mode to get one of the modes we really wanted.  */
1479
1480   int_mode = int_mode_for_mode (tmode);
1481   if (int_mode == BLKmode)
1482     int_mode = int_mode_for_mode (mode);
1483   /* Should probably push op0 out to memory and then do a load.  */
1484   gcc_assert (int_mode != BLKmode);
1485
1486   /* OFFSET is the number of words or bytes (UNIT says which)
1487      from STR_RTX to the first word or byte containing part of the field.  */
1488   if (!MEM_P (op0))
1489     {
1490       if (offset != 0
1491           || GET_MODE_SIZE (GET_MODE (op0)) > UNITS_PER_WORD)
1492         {
1493           if (!REG_P (op0))
1494             op0 = copy_to_reg (op0);
1495           op0 = gen_rtx_SUBREG (mode_for_size (BITS_PER_WORD, MODE_INT, 0),
1496                                 op0, (offset * UNITS_PER_WORD));
1497         }
1498       offset = 0;
1499     }
1500
1501   /* Now OFFSET is nonzero only for memory operands.  */
1502   ext_mode = mode_for_extraction (unsignedp ? EP_extzv : EP_extv, 0);
1503   icode = unsignedp ? CODE_FOR_extzv : CODE_FOR_extv;
1504   if (ext_mode != MAX_MACHINE_MODE
1505       && bitsize > 0
1506       && GET_MODE_BITSIZE (ext_mode) >= bitsize
1507       /* If op0 is a register, we need it in EXT_MODE to make it
1508          acceptable to the format of ext(z)v.  */
1509       && !(GET_CODE (op0) == SUBREG && GET_MODE (op0) != ext_mode)
1510       && !((REG_P (op0) || GET_CODE (op0) == SUBREG)
1511            && (bitsize + bitpos > GET_MODE_BITSIZE (ext_mode)))
1512       && check_predicate_volatile_ok (icode, 1, op0, GET_MODE (op0)))
1513     {
1514       unsigned HOST_WIDE_INT xbitpos = bitpos, xoffset = offset;
1515       rtx bitsize_rtx, bitpos_rtx;
1516       rtx last = get_last_insn ();
1517       rtx xop0 = op0;
1518       rtx xtarget = target;
1519       rtx xspec_target = target;
1520       rtx xspec_target_subreg = 0;
1521       rtx pat;
1522
1523       /* If op0 is a register, we need it in EXT_MODE to make it
1524          acceptable to the format of ext(z)v.  */
1525       if (REG_P (xop0) && GET_MODE (xop0) != ext_mode)
1526         xop0 = gen_rtx_SUBREG (ext_mode, xop0, 0);
1527       if (MEM_P (xop0))
1528         /* Get ref to first byte containing part of the field.  */
1529         xop0 = adjust_address (xop0, byte_mode, xoffset);
1530
1531       /* On big-endian machines, we count bits from the most significant.
1532          If the bit field insn does not, we must invert.  */
1533       if (BITS_BIG_ENDIAN != BYTES_BIG_ENDIAN)
1534         xbitpos = unit - bitsize - xbitpos;
1535
1536       /* Now convert from counting within UNIT to counting in EXT_MODE.  */
1537       if (BITS_BIG_ENDIAN && !MEM_P (xop0))
1538         xbitpos += GET_MODE_BITSIZE (ext_mode) - unit;
1539
1540       unit = GET_MODE_BITSIZE (ext_mode);
1541
1542       if (xtarget == 0)
1543         xtarget = xspec_target = gen_reg_rtx (tmode);
1544
1545       if (GET_MODE (xtarget) != ext_mode)
1546         {
1547           /* Don't use LHS paradoxical subreg if explicit truncation is needed
1548              between the mode of the extraction (word_mode) and the target
1549              mode.  Instead, create a temporary and use convert_move to set
1550              the target.  */
1551           if (REG_P (xtarget)
1552               && TRULY_NOOP_TRUNCATION (GET_MODE_BITSIZE (GET_MODE (xtarget)),
1553                                         GET_MODE_BITSIZE (ext_mode)))
1554             {
1555               xtarget = gen_lowpart (ext_mode, xtarget);
1556               if (GET_MODE_SIZE (ext_mode)
1557                   > GET_MODE_SIZE (GET_MODE (xspec_target)))
1558                 xspec_target_subreg = xtarget;
1559             }
1560           else
1561             xtarget = gen_reg_rtx (ext_mode);
1562         }
1563
1564       /* If this machine's ext(z)v insists on a register target,
1565          make sure we have one.  */
1566       if (!insn_data[(int) icode].operand[0].predicate (xtarget, ext_mode))
1567         xtarget = gen_reg_rtx (ext_mode);
1568
1569       bitsize_rtx = GEN_INT (bitsize);
1570       bitpos_rtx = GEN_INT (xbitpos);
1571
1572       pat = (unsignedp
1573              ? gen_extzv (xtarget, xop0, bitsize_rtx, bitpos_rtx)
1574              : gen_extv (xtarget, xop0, bitsize_rtx, bitpos_rtx));
1575       if (pat)
1576         {
1577           emit_insn (pat);
1578           if (xtarget == xspec_target)
1579             return xtarget;
1580           if (xtarget == xspec_target_subreg)
1581             return xspec_target;
1582           return convert_extracted_bit_field (xtarget, mode, tmode, unsignedp);
1583         }
1584       delete_insns_since (last);
1585     }
1586
1587   /* If OP0 is a memory, try copying it to a register and seeing if a
1588      cheap register alternative is available.  */
1589   if (ext_mode != MAX_MACHINE_MODE && MEM_P (op0))
1590     {
1591       enum machine_mode bestmode;
1592
1593       /* Get the mode to use for inserting into this field.  If
1594          OP0 is BLKmode, get the smallest mode consistent with the
1595          alignment. If OP0 is a non-BLKmode object that is no
1596          wider than EXT_MODE, use its mode. Otherwise, use the
1597          smallest mode containing the field.  */
1598
1599       if (GET_MODE (op0) == BLKmode
1600           || (ext_mode != MAX_MACHINE_MODE
1601               && GET_MODE_SIZE (GET_MODE (op0)) > GET_MODE_SIZE (ext_mode)))
1602         bestmode = get_best_mode (bitsize, bitnum, MEM_ALIGN (op0),
1603                                   (ext_mode == MAX_MACHINE_MODE
1604                                    ? VOIDmode : ext_mode),
1605                                   MEM_VOLATILE_P (op0));
1606       else
1607         bestmode = GET_MODE (op0);
1608
1609       if (bestmode != VOIDmode
1610           && !(SLOW_UNALIGNED_ACCESS (bestmode, MEM_ALIGN (op0))
1611                && GET_MODE_BITSIZE (bestmode) > MEM_ALIGN (op0)))
1612         {
1613           unsigned HOST_WIDE_INT xoffset, xbitpos;
1614
1615           /* Compute the offset as a multiple of this unit,
1616              counting in bytes.  */
1617           unit = GET_MODE_BITSIZE (bestmode);
1618           xoffset = (bitnum / unit) * GET_MODE_SIZE (bestmode);
1619           xbitpos = bitnum % unit;
1620
1621           /* Make sure the register is big enough for the whole field.  */
1622           if (xoffset * BITS_PER_UNIT + unit
1623               >= offset * BITS_PER_UNIT + bitsize)
1624             {
1625               rtx last, result, xop0;
1626
1627               last = get_last_insn ();
1628
1629               /* Fetch it to a register in that size.  */
1630               xop0 = adjust_address (op0, bestmode, xoffset);
1631               xop0 = force_reg (bestmode, xop0);
1632               result = extract_bit_field_1 (xop0, bitsize, xbitpos,
1633                                             unsignedp, target,
1634                                             mode, tmode, false);
1635               if (result)
1636                 return result;
1637
1638               delete_insns_since (last);
1639             }
1640         }
1641     }
1642
1643   if (!fallback_p)
1644     return NULL;
1645
1646   target = extract_fixed_bit_field (int_mode, op0, offset, bitsize,
1647                                     bitpos, target, unsignedp);
1648   return convert_extracted_bit_field (target, mode, tmode, unsignedp);
1649 }
1650
1651 /* Generate code to extract a byte-field from STR_RTX
1652    containing BITSIZE bits, starting at BITNUM,
1653    and put it in TARGET if possible (if TARGET is nonzero).
1654    Regardless of TARGET, we return the rtx for where the value is placed.
1655
1656    STR_RTX is the structure containing the byte (a REG or MEM).
1657    UNSIGNEDP is nonzero if this is an unsigned bit field.
1658    MODE is the natural mode of the field value once extracted.
1659    TMODE is the mode the caller would like the value to have;
1660    but the value may be returned with type MODE instead.
1661
1662    If a TARGET is specified and we can store in it at no extra cost,
1663    we do so, and return TARGET.
1664    Otherwise, we return a REG of mode TMODE or MODE, with TMODE preferred
1665    if they are equally easy.  */
1666
1667 rtx
1668 extract_bit_field (rtx str_rtx, unsigned HOST_WIDE_INT bitsize,
1669                    unsigned HOST_WIDE_INT bitnum, int unsignedp, rtx target,
1670                    enum machine_mode mode, enum machine_mode tmode)
1671 {
1672   return extract_bit_field_1 (str_rtx, bitsize, bitnum, unsignedp,
1673                               target, mode, tmode, true);
1674 }
1675 \f
1676 /* Extract a bit field using shifts and boolean operations
1677    Returns an rtx to represent the value.
1678    OP0 addresses a register (word) or memory (byte).
1679    BITPOS says which bit within the word or byte the bit field starts in.
1680    OFFSET says how many bytes farther the bit field starts;
1681     it is 0 if OP0 is a register.
1682    BITSIZE says how many bits long the bit field is.
1683     (If OP0 is a register, it may be narrower than a full word,
1684      but BITPOS still counts within a full word,
1685      which is significant on bigendian machines.)
1686
1687    UNSIGNEDP is nonzero for an unsigned bit field (don't sign-extend value).
1688    If TARGET is nonzero, attempts to store the value there
1689    and return TARGET, but this is not guaranteed.
1690    If TARGET is not used, create a pseudo-reg of mode TMODE for the value.  */
1691
1692 static rtx
1693 extract_fixed_bit_field (enum machine_mode tmode, rtx op0,
1694                          unsigned HOST_WIDE_INT offset,
1695                          unsigned HOST_WIDE_INT bitsize,
1696                          unsigned HOST_WIDE_INT bitpos, rtx target,
1697                          int unsignedp)
1698 {
1699   unsigned int total_bits = BITS_PER_WORD;
1700   enum machine_mode mode;
1701
1702   if (GET_CODE (op0) == SUBREG || REG_P (op0))
1703     {
1704       /* Special treatment for a bit field split across two registers.  */
1705       if (bitsize + bitpos > BITS_PER_WORD)
1706         return extract_split_bit_field (op0, bitsize, bitpos, unsignedp);
1707     }
1708   else
1709     {
1710       /* Get the proper mode to use for this field.  We want a mode that
1711          includes the entire field.  If such a mode would be larger than
1712          a word, we won't be doing the extraction the normal way.  */
1713
1714       mode = get_best_mode (bitsize, bitpos + offset * BITS_PER_UNIT,
1715                             MEM_ALIGN (op0), word_mode, MEM_VOLATILE_P (op0));
1716
1717       if (mode == VOIDmode)
1718         /* The only way this should occur is if the field spans word
1719            boundaries.  */
1720         return extract_split_bit_field (op0, bitsize,
1721                                         bitpos + offset * BITS_PER_UNIT,
1722                                         unsignedp);
1723
1724       total_bits = GET_MODE_BITSIZE (mode);
1725
1726       /* Make sure bitpos is valid for the chosen mode.  Adjust BITPOS to
1727          be in the range 0 to total_bits-1, and put any excess bytes in
1728          OFFSET.  */
1729       if (bitpos >= total_bits)
1730         {
1731           offset += (bitpos / total_bits) * (total_bits / BITS_PER_UNIT);
1732           bitpos -= ((bitpos / total_bits) * (total_bits / BITS_PER_UNIT)
1733                      * BITS_PER_UNIT);
1734         }
1735
1736       /* Get ref to an aligned byte, halfword, or word containing the field.
1737          Adjust BITPOS to be position within a word,
1738          and OFFSET to be the offset of that word.
1739          Then alter OP0 to refer to that word.  */
1740       bitpos += (offset % (total_bits / BITS_PER_UNIT)) * BITS_PER_UNIT;
1741       offset -= (offset % (total_bits / BITS_PER_UNIT));
1742       op0 = adjust_address (op0, mode, offset);
1743     }
1744
1745   mode = GET_MODE (op0);
1746
1747   if (BYTES_BIG_ENDIAN)
1748     /* BITPOS is the distance between our msb and that of OP0.
1749        Convert it to the distance from the lsb.  */
1750     bitpos = total_bits - bitsize - bitpos;
1751
1752   /* Now BITPOS is always the distance between the field's lsb and that of OP0.
1753      We have reduced the big-endian case to the little-endian case.  */
1754
1755   if (unsignedp)
1756     {
1757       if (bitpos)
1758         {
1759           /* If the field does not already start at the lsb,
1760              shift it so it does.  */
1761           tree amount = build_int_cst (NULL_TREE, bitpos);
1762           /* Maybe propagate the target for the shift.  */
1763           /* But not if we will return it--could confuse integrate.c.  */
1764           rtx subtarget = (target != 0 && REG_P (target) ? target : 0);
1765           if (tmode != mode) subtarget = 0;
1766           op0 = expand_shift (RSHIFT_EXPR, mode, op0, amount, subtarget, 1);
1767         }
1768       /* Convert the value to the desired mode.  */
1769       if (mode != tmode)
1770         op0 = convert_to_mode (tmode, op0, 1);
1771
1772       /* Unless the msb of the field used to be the msb when we shifted,
1773          mask out the upper bits.  */
1774
1775       if (GET_MODE_BITSIZE (mode) != bitpos + bitsize)
1776         return expand_binop (GET_MODE (op0), and_optab, op0,
1777                              mask_rtx (GET_MODE (op0), 0, bitsize, 0),
1778                              target, 1, OPTAB_LIB_WIDEN);
1779       return op0;
1780     }
1781
1782   /* To extract a signed bit-field, first shift its msb to the msb of the word,
1783      then arithmetic-shift its lsb to the lsb of the word.  */
1784   op0 = force_reg (mode, op0);
1785   if (mode != tmode)
1786     target = 0;
1787
1788   /* Find the narrowest integer mode that contains the field.  */
1789
1790   for (mode = GET_CLASS_NARROWEST_MODE (MODE_INT); mode != VOIDmode;
1791        mode = GET_MODE_WIDER_MODE (mode))
1792     if (GET_MODE_BITSIZE (mode) >= bitsize + bitpos)
1793       {
1794         op0 = convert_to_mode (mode, op0, 0);
1795         break;
1796       }
1797
1798   if (GET_MODE_BITSIZE (mode) != (bitsize + bitpos))
1799     {
1800       tree amount
1801         = build_int_cst (NULL_TREE,
1802                          GET_MODE_BITSIZE (mode) - (bitsize + bitpos));
1803       /* Maybe propagate the target for the shift.  */
1804       rtx subtarget = (target != 0 && REG_P (target) ? target : 0);
1805       op0 = expand_shift (LSHIFT_EXPR, mode, op0, amount, subtarget, 1);
1806     }
1807
1808   return expand_shift (RSHIFT_EXPR, mode, op0,
1809                        build_int_cst (NULL_TREE,
1810                                       GET_MODE_BITSIZE (mode) - bitsize),
1811                        target, 0);
1812 }
1813 \f
1814 /* Return a constant integer (CONST_INT or CONST_DOUBLE) mask value
1815    of mode MODE with BITSIZE ones followed by BITPOS zeros, or the
1816    complement of that if COMPLEMENT.  The mask is truncated if
1817    necessary to the width of mode MODE.  The mask is zero-extended if
1818    BITSIZE+BITPOS is too small for MODE.  */
1819
1820 static rtx
1821 mask_rtx (enum machine_mode mode, int bitpos, int bitsize, int complement)
1822 {
1823   HOST_WIDE_INT masklow, maskhigh;
1824
1825   if (bitsize == 0)
1826     masklow = 0;
1827   else if (bitpos < HOST_BITS_PER_WIDE_INT)
1828     masklow = (HOST_WIDE_INT) -1 << bitpos;
1829   else
1830     masklow = 0;
1831
1832   if (bitpos + bitsize < HOST_BITS_PER_WIDE_INT)
1833     masklow &= ((unsigned HOST_WIDE_INT) -1
1834                 >> (HOST_BITS_PER_WIDE_INT - bitpos - bitsize));
1835
1836   if (bitpos <= HOST_BITS_PER_WIDE_INT)
1837     maskhigh = -1;
1838   else
1839     maskhigh = (HOST_WIDE_INT) -1 << (bitpos - HOST_BITS_PER_WIDE_INT);
1840
1841   if (bitsize == 0)
1842     maskhigh = 0;
1843   else if (bitpos + bitsize > HOST_BITS_PER_WIDE_INT)
1844     maskhigh &= ((unsigned HOST_WIDE_INT) -1
1845                  >> (2 * HOST_BITS_PER_WIDE_INT - bitpos - bitsize));
1846   else
1847     maskhigh = 0;
1848
1849   if (complement)
1850     {
1851       maskhigh = ~maskhigh;
1852       masklow = ~masklow;
1853     }
1854
1855   return immed_double_const (masklow, maskhigh, mode);
1856 }
1857
1858 /* Return a constant integer (CONST_INT or CONST_DOUBLE) rtx with the value
1859    VALUE truncated to BITSIZE bits and then shifted left BITPOS bits.  */
1860
1861 static rtx
1862 lshift_value (enum machine_mode mode, rtx value, int bitpos, int bitsize)
1863 {
1864   unsigned HOST_WIDE_INT v = INTVAL (value);
1865   HOST_WIDE_INT low, high;
1866
1867   if (bitsize < HOST_BITS_PER_WIDE_INT)
1868     v &= ~((HOST_WIDE_INT) -1 << bitsize);
1869
1870   if (bitpos < HOST_BITS_PER_WIDE_INT)
1871     {
1872       low = v << bitpos;
1873       high = (bitpos > 0 ? (v >> (HOST_BITS_PER_WIDE_INT - bitpos)) : 0);
1874     }
1875   else
1876     {
1877       low = 0;
1878       high = v << (bitpos - HOST_BITS_PER_WIDE_INT);
1879     }
1880
1881   return immed_double_const (low, high, mode);
1882 }
1883 \f
1884 /* Extract a bit field that is split across two words
1885    and return an RTX for the result.
1886
1887    OP0 is the REG, SUBREG or MEM rtx for the first of the two words.
1888    BITSIZE is the field width; BITPOS, position of its first bit, in the word.
1889    UNSIGNEDP is 1 if should zero-extend the contents; else sign-extend.  */
1890
1891 static rtx
1892 extract_split_bit_field (rtx op0, unsigned HOST_WIDE_INT bitsize,
1893                          unsigned HOST_WIDE_INT bitpos, int unsignedp)
1894 {
1895   unsigned int unit;
1896   unsigned int bitsdone = 0;
1897   rtx result = NULL_RTX;
1898   int first = 1;
1899
1900   /* Make sure UNIT isn't larger than BITS_PER_WORD, we can only handle that
1901      much at a time.  */
1902   if (REG_P (op0) || GET_CODE (op0) == SUBREG)
1903     unit = BITS_PER_WORD;
1904   else
1905     unit = MIN (MEM_ALIGN (op0), BITS_PER_WORD);
1906
1907   while (bitsdone < bitsize)
1908     {
1909       unsigned HOST_WIDE_INT thissize;
1910       rtx part, word;
1911       unsigned HOST_WIDE_INT thispos;
1912       unsigned HOST_WIDE_INT offset;
1913
1914       offset = (bitpos + bitsdone) / unit;
1915       thispos = (bitpos + bitsdone) % unit;
1916
1917       /* THISSIZE must not overrun a word boundary.  Otherwise,
1918          extract_fixed_bit_field will call us again, and we will mutually
1919          recurse forever.  */
1920       thissize = MIN (bitsize - bitsdone, BITS_PER_WORD);
1921       thissize = MIN (thissize, unit - thispos);
1922
1923       /* If OP0 is a register, then handle OFFSET here.
1924
1925          When handling multiword bitfields, extract_bit_field may pass
1926          down a word_mode SUBREG of a larger REG for a bitfield that actually
1927          crosses a word boundary.  Thus, for a SUBREG, we must find
1928          the current word starting from the base register.  */
1929       if (GET_CODE (op0) == SUBREG)
1930         {
1931           int word_offset = (SUBREG_BYTE (op0) / UNITS_PER_WORD) + offset;
1932           word = operand_subword_force (SUBREG_REG (op0), word_offset,
1933                                         GET_MODE (SUBREG_REG (op0)));
1934           offset = 0;
1935         }
1936       else if (REG_P (op0))
1937         {
1938           word = operand_subword_force (op0, offset, GET_MODE (op0));
1939           offset = 0;
1940         }
1941       else
1942         word = op0;
1943
1944       /* Extract the parts in bit-counting order,
1945          whose meaning is determined by BYTES_PER_UNIT.
1946          OFFSET is in UNITs, and UNIT is in bits.
1947          extract_fixed_bit_field wants offset in bytes.  */
1948       part = extract_fixed_bit_field (word_mode, word,
1949                                       offset * unit / BITS_PER_UNIT,
1950                                       thissize, thispos, 0, 1);
1951       bitsdone += thissize;
1952
1953       /* Shift this part into place for the result.  */
1954       if (BYTES_BIG_ENDIAN)
1955         {
1956           if (bitsize != bitsdone)
1957             part = expand_shift (LSHIFT_EXPR, word_mode, part,
1958                                  build_int_cst (NULL_TREE, bitsize - bitsdone),
1959                                  0, 1);
1960         }
1961       else
1962         {
1963           if (bitsdone != thissize)
1964             part = expand_shift (LSHIFT_EXPR, word_mode, part,
1965                                  build_int_cst (NULL_TREE,
1966                                                 bitsdone - thissize), 0, 1);
1967         }
1968
1969       if (first)
1970         result = part;
1971       else
1972         /* Combine the parts with bitwise or.  This works
1973            because we extracted each part as an unsigned bit field.  */
1974         result = expand_binop (word_mode, ior_optab, part, result, NULL_RTX, 1,
1975                                OPTAB_LIB_WIDEN);
1976
1977       first = 0;
1978     }
1979
1980   /* Unsigned bit field: we are done.  */
1981   if (unsignedp)
1982     return result;
1983   /* Signed bit field: sign-extend with two arithmetic shifts.  */
1984   result = expand_shift (LSHIFT_EXPR, word_mode, result,
1985                          build_int_cst (NULL_TREE, BITS_PER_WORD - bitsize),
1986                          NULL_RTX, 0);
1987   return expand_shift (RSHIFT_EXPR, word_mode, result,
1988                        build_int_cst (NULL_TREE, BITS_PER_WORD - bitsize),
1989                        NULL_RTX, 0);
1990 }
1991 \f
1992 /* Try to read the low bits of SRC as an rvalue of mode MODE, preserving
1993    the bit pattern.  SRC_MODE is the mode of SRC; if this is smaller than
1994    MODE, fill the upper bits with zeros.  Fail if the layout of either
1995    mode is unknown (as for CC modes) or if the extraction would involve
1996    unprofitable mode punning.  Return the value on success, otherwise
1997    return null.
1998
1999    This is different from gen_lowpart* in these respects:
2000
2001      - the returned value must always be considered an rvalue
2002
2003      - when MODE is wider than SRC_MODE, the extraction involves
2004        a zero extension
2005
2006      - when MODE is smaller than SRC_MODE, the extraction involves
2007        a truncation (and is thus subject to TRULY_NOOP_TRUNCATION).
2008
2009    In other words, this routine performs a computation, whereas the
2010    gen_lowpart* routines are conceptually lvalue or rvalue subreg
2011    operations.  */
2012
2013 rtx
2014 extract_low_bits (enum machine_mode mode, enum machine_mode src_mode, rtx src)
2015 {
2016   enum machine_mode int_mode, src_int_mode;
2017
2018   if (mode == src_mode)
2019     return src;
2020
2021   if (CONSTANT_P (src))
2022     {
2023       /* simplify_gen_subreg can't be used here, as if simplify_subreg
2024          fails, it will happily create (subreg (symbol_ref)) or similar
2025          invalid SUBREGs.  */
2026       unsigned int byte = subreg_lowpart_offset (mode, src_mode);
2027       rtx ret = simplify_subreg (mode, src, src_mode, byte);
2028       if (ret)
2029         return ret;
2030
2031       if (GET_MODE (src) == VOIDmode
2032           || !validate_subreg (mode, src_mode, src, byte))
2033         return NULL_RTX;
2034
2035       src = force_reg (GET_MODE (src), src);
2036       return gen_rtx_SUBREG (mode, src, byte);
2037     }
2038
2039   if (GET_MODE_CLASS (mode) == MODE_CC || GET_MODE_CLASS (src_mode) == MODE_CC)
2040     return NULL_RTX;
2041
2042   if (GET_MODE_BITSIZE (mode) == GET_MODE_BITSIZE (src_mode)
2043       && MODES_TIEABLE_P (mode, src_mode))
2044     {
2045       rtx x = gen_lowpart_common (mode, src);
2046       if (x)
2047         return x;
2048     }
2049
2050   src_int_mode = int_mode_for_mode (src_mode);
2051   int_mode = int_mode_for_mode (mode);
2052   if (src_int_mode == BLKmode || int_mode == BLKmode)
2053     return NULL_RTX;
2054
2055   if (!MODES_TIEABLE_P (src_int_mode, src_mode))
2056     return NULL_RTX;
2057   if (!MODES_TIEABLE_P (int_mode, mode))
2058     return NULL_RTX;
2059
2060   src = gen_lowpart (src_int_mode, src);
2061   src = convert_modes (int_mode, src_int_mode, src, true);
2062   src = gen_lowpart (mode, src);
2063   return src;
2064 }
2065 \f
2066 /* Add INC into TARGET.  */
2067
2068 void
2069 expand_inc (rtx target, rtx inc)
2070 {
2071   rtx value = expand_binop (GET_MODE (target), add_optab,
2072                             target, inc,
2073                             target, 0, OPTAB_LIB_WIDEN);
2074   if (value != target)
2075     emit_move_insn (target, value);
2076 }
2077
2078 /* Subtract DEC from TARGET.  */
2079
2080 void
2081 expand_dec (rtx target, rtx dec)
2082 {
2083   rtx value = expand_binop (GET_MODE (target), sub_optab,
2084                             target, dec,
2085                             target, 0, OPTAB_LIB_WIDEN);
2086   if (value != target)
2087     emit_move_insn (target, value);
2088 }
2089 \f
2090 /* Output a shift instruction for expression code CODE,
2091    with SHIFTED being the rtx for the value to shift,
2092    and AMOUNT the tree for the amount to shift by.
2093    Store the result in the rtx TARGET, if that is convenient.
2094    If UNSIGNEDP is nonzero, do a logical shift; otherwise, arithmetic.
2095    Return the rtx for where the value is.  */
2096
2097 rtx
2098 expand_shift (enum tree_code code, enum machine_mode mode, rtx shifted,
2099               tree amount, rtx target, int unsignedp)
2100 {
2101   rtx op1, temp = 0;
2102   int left = (code == LSHIFT_EXPR || code == LROTATE_EXPR);
2103   int rotate = (code == LROTATE_EXPR || code == RROTATE_EXPR);
2104   optab lshift_optab = ashl_optab;
2105   optab rshift_arith_optab = ashr_optab;
2106   optab rshift_uns_optab = lshr_optab;
2107   optab lrotate_optab = rotl_optab;
2108   optab rrotate_optab = rotr_optab;
2109   enum machine_mode op1_mode;
2110   int attempt;
2111   bool speed = optimize_insn_for_speed_p ();
2112
2113   op1 = expand_normal (amount);
2114   op1_mode = GET_MODE (op1);
2115
2116   /* Determine whether the shift/rotate amount is a vector, or scalar.  If the
2117      shift amount is a vector, use the vector/vector shift patterns.  */
2118   if (VECTOR_MODE_P (mode) && VECTOR_MODE_P (op1_mode))
2119     {
2120       lshift_optab = vashl_optab;
2121       rshift_arith_optab = vashr_optab;
2122       rshift_uns_optab = vlshr_optab;
2123       lrotate_optab = vrotl_optab;
2124       rrotate_optab = vrotr_optab;
2125     }
2126
2127   /* Previously detected shift-counts computed by NEGATE_EXPR
2128      and shifted in the other direction; but that does not work
2129      on all machines.  */
2130
2131   if (SHIFT_COUNT_TRUNCATED)
2132     {
2133       if (GET_CODE (op1) == CONST_INT
2134           && ((unsigned HOST_WIDE_INT) INTVAL (op1) >=
2135               (unsigned HOST_WIDE_INT) GET_MODE_BITSIZE (mode)))
2136         op1 = GEN_INT ((unsigned HOST_WIDE_INT) INTVAL (op1)
2137                        % GET_MODE_BITSIZE (mode));
2138       else if (GET_CODE (op1) == SUBREG
2139                && subreg_lowpart_p (op1)
2140                && INTEGRAL_MODE_P (GET_MODE (SUBREG_REG (op1))))
2141         op1 = SUBREG_REG (op1);
2142     }
2143
2144   if (op1 == const0_rtx)
2145     return shifted;
2146
2147   /* Check whether its cheaper to implement a left shift by a constant
2148      bit count by a sequence of additions.  */
2149   if (code == LSHIFT_EXPR
2150       && GET_CODE (op1) == CONST_INT
2151       && INTVAL (op1) > 0
2152       && INTVAL (op1) < GET_MODE_BITSIZE (mode)
2153       && INTVAL (op1) < MAX_BITS_PER_WORD
2154       && shift_cost[speed][mode][INTVAL (op1)] > INTVAL (op1) * add_cost[speed][mode]
2155       && shift_cost[speed][mode][INTVAL (op1)] != MAX_COST)
2156     {
2157       int i;
2158       for (i = 0; i < INTVAL (op1); i++)
2159         {
2160           temp = force_reg (mode, shifted);
2161           shifted = expand_binop (mode, add_optab, temp, temp, NULL_RTX,
2162                                   unsignedp, OPTAB_LIB_WIDEN);
2163         }
2164       return shifted;
2165     }
2166
2167   for (attempt = 0; temp == 0 && attempt < 3; attempt++)
2168     {
2169       enum optab_methods methods;
2170
2171       if (attempt == 0)
2172         methods = OPTAB_DIRECT;
2173       else if (attempt == 1)
2174         methods = OPTAB_WIDEN;
2175       else
2176         methods = OPTAB_LIB_WIDEN;
2177
2178       if (rotate)
2179         {
2180           /* Widening does not work for rotation.  */
2181           if (methods == OPTAB_WIDEN)
2182             continue;
2183           else if (methods == OPTAB_LIB_WIDEN)
2184             {
2185               /* If we have been unable to open-code this by a rotation,
2186                  do it as the IOR of two shifts.  I.e., to rotate A
2187                  by N bits, compute (A << N) | ((unsigned) A >> (C - N))
2188                  where C is the bitsize of A.
2189
2190                  It is theoretically possible that the target machine might
2191                  not be able to perform either shift and hence we would
2192                  be making two libcalls rather than just the one for the
2193                  shift (similarly if IOR could not be done).  We will allow
2194                  this extremely unlikely lossage to avoid complicating the
2195                  code below.  */
2196
2197               rtx subtarget = target == shifted ? 0 : target;
2198               tree new_amount, other_amount;
2199               rtx temp1;
2200               tree type = TREE_TYPE (amount);
2201               if (GET_MODE (op1) != TYPE_MODE (type)
2202                   && GET_MODE (op1) != VOIDmode)
2203                 op1 = convert_to_mode (TYPE_MODE (type), op1, 1);
2204               new_amount = make_tree (type, op1);
2205               other_amount
2206                 = fold_build2 (MINUS_EXPR, type,
2207                                build_int_cst (type, GET_MODE_BITSIZE (mode)),
2208                                new_amount);
2209
2210               shifted = force_reg (mode, shifted);
2211
2212               temp = expand_shift (left ? LSHIFT_EXPR : RSHIFT_EXPR,
2213                                    mode, shifted, new_amount, 0, 1);
2214               temp1 = expand_shift (left ? RSHIFT_EXPR : LSHIFT_EXPR,
2215                                     mode, shifted, other_amount, subtarget, 1);
2216               return expand_binop (mode, ior_optab, temp, temp1, target,
2217                                    unsignedp, methods);
2218             }
2219
2220           temp = expand_binop (mode,
2221                                left ? lrotate_optab : rrotate_optab,
2222                                shifted, op1, target, unsignedp, methods);
2223         }
2224       else if (unsignedp)
2225         temp = expand_binop (mode,
2226                              left ? lshift_optab : rshift_uns_optab,
2227                              shifted, op1, target, unsignedp, methods);
2228
2229       /* Do arithmetic shifts.
2230          Also, if we are going to widen the operand, we can just as well
2231          use an arithmetic right-shift instead of a logical one.  */
2232       if (temp == 0 && ! rotate
2233           && (! unsignedp || (! left && methods == OPTAB_WIDEN)))
2234         {
2235           enum optab_methods methods1 = methods;
2236
2237           /* If trying to widen a log shift to an arithmetic shift,
2238              don't accept an arithmetic shift of the same size.  */
2239           if (unsignedp)
2240             methods1 = OPTAB_MUST_WIDEN;
2241
2242           /* Arithmetic shift */
2243
2244           temp = expand_binop (mode,
2245                                left ? lshift_optab : rshift_arith_optab,
2246                                shifted, op1, target, unsignedp, methods1);
2247         }
2248
2249       /* We used to try extzv here for logical right shifts, but that was
2250          only useful for one machine, the VAX, and caused poor code
2251          generation there for lshrdi3, so the code was deleted and a
2252          define_expand for lshrsi3 was added to vax.md.  */
2253     }
2254
2255   gcc_assert (temp);
2256   return temp;
2257 }
2258 \f
2259 enum alg_code {
2260   alg_unknown,
2261   alg_zero,
2262   alg_m, alg_shift,
2263   alg_add_t_m2,
2264   alg_sub_t_m2,
2265   alg_add_factor,
2266   alg_sub_factor,
2267   alg_add_t2_m,
2268   alg_sub_t2_m,
2269   alg_impossible
2270 };
2271
2272 /* This structure holds the "cost" of a multiply sequence.  The
2273    "cost" field holds the total rtx_cost of every operator in the
2274    synthetic multiplication sequence, hence cost(a op b) is defined
2275    as rtx_cost(op) + cost(a) + cost(b), where cost(leaf) is zero.
2276    The "latency" field holds the minimum possible latency of the
2277    synthetic multiply, on a hypothetical infinitely parallel CPU.
2278    This is the critical path, or the maximum height, of the expression
2279    tree which is the sum of rtx_costs on the most expensive path from
2280    any leaf to the root.  Hence latency(a op b) is defined as zero for
2281    leaves and rtx_cost(op) + max(latency(a), latency(b)) otherwise.  */
2282
2283 struct mult_cost {
2284   short cost;     /* Total rtx_cost of the multiplication sequence.  */
2285   short latency;  /* The latency of the multiplication sequence.  */
2286 };
2287
2288 /* This macro is used to compare a pointer to a mult_cost against an
2289    single integer "rtx_cost" value.  This is equivalent to the macro
2290    CHEAPER_MULT_COST(X,Z) where Z = {Y,Y}.  */
2291 #define MULT_COST_LESS(X,Y) ((X)->cost < (Y)    \
2292                              || ((X)->cost == (Y) && (X)->latency < (Y)))
2293
2294 /* This macro is used to compare two pointers to mult_costs against
2295    each other.  The macro returns true if X is cheaper than Y.
2296    Currently, the cheaper of two mult_costs is the one with the
2297    lower "cost".  If "cost"s are tied, the lower latency is cheaper.  */
2298 #define CHEAPER_MULT_COST(X,Y)  ((X)->cost < (Y)->cost          \
2299                                  || ((X)->cost == (Y)->cost     \
2300                                      && (X)->latency < (Y)->latency))
2301
2302 /* This structure records a sequence of operations.
2303    `ops' is the number of operations recorded.
2304    `cost' is their total cost.
2305    The operations are stored in `op' and the corresponding
2306    logarithms of the integer coefficients in `log'.
2307
2308    These are the operations:
2309    alg_zero             total := 0;
2310    alg_m                total := multiplicand;
2311    alg_shift            total := total * coeff
2312    alg_add_t_m2         total := total + multiplicand * coeff;
2313    alg_sub_t_m2         total := total - multiplicand * coeff;
2314    alg_add_factor       total := total * coeff + total;
2315    alg_sub_factor       total := total * coeff - total;
2316    alg_add_t2_m         total := total * coeff + multiplicand;
2317    alg_sub_t2_m         total := total * coeff - multiplicand;
2318
2319    The first operand must be either alg_zero or alg_m.  */
2320
2321 struct algorithm
2322 {
2323   struct mult_cost cost;
2324   short ops;
2325   /* The size of the OP and LOG fields are not directly related to the
2326      word size, but the worst-case algorithms will be if we have few
2327      consecutive ones or zeros, i.e., a multiplicand like 10101010101...
2328      In that case we will generate shift-by-2, add, shift-by-2, add,...,
2329      in total wordsize operations.  */
2330   enum alg_code op[MAX_BITS_PER_WORD];
2331   char log[MAX_BITS_PER_WORD];
2332 };
2333
2334 /* The entry for our multiplication cache/hash table.  */
2335 struct alg_hash_entry {
2336   /* The number we are multiplying by.  */
2337   unsigned HOST_WIDE_INT t;
2338
2339   /* The mode in which we are multiplying something by T.  */
2340   enum machine_mode mode;
2341
2342   /* The best multiplication algorithm for t.  */
2343   enum alg_code alg;
2344
2345   /* The cost of multiplication if ALG_CODE is not alg_impossible.
2346      Otherwise, the cost within which multiplication by T is
2347      impossible.  */
2348   struct mult_cost cost;
2349  
2350   /* OPtimized for speed? */
2351   bool speed;
2352 };
2353
2354 /* The number of cache/hash entries.  */
2355 #if HOST_BITS_PER_WIDE_INT == 64
2356 #define NUM_ALG_HASH_ENTRIES 1031
2357 #else
2358 #define NUM_ALG_HASH_ENTRIES 307
2359 #endif
2360
2361 /* Each entry of ALG_HASH caches alg_code for some integer.  This is
2362    actually a hash table.  If we have a collision, that the older
2363    entry is kicked out.  */
2364 static struct alg_hash_entry alg_hash[NUM_ALG_HASH_ENTRIES];
2365
2366 /* Indicates the type of fixup needed after a constant multiplication.
2367    BASIC_VARIANT means no fixup is needed, NEGATE_VARIANT means that
2368    the result should be negated, and ADD_VARIANT means that the
2369    multiplicand should be added to the result.  */
2370 enum mult_variant {basic_variant, negate_variant, add_variant};
2371
2372 static void synth_mult (struct algorithm *, unsigned HOST_WIDE_INT,
2373                         const struct mult_cost *, enum machine_mode mode);
2374 static bool choose_mult_variant (enum machine_mode, HOST_WIDE_INT,
2375                                  struct algorithm *, enum mult_variant *, int);
2376 static rtx expand_mult_const (enum machine_mode, rtx, HOST_WIDE_INT, rtx,
2377                               const struct algorithm *, enum mult_variant);
2378 static unsigned HOST_WIDE_INT choose_multiplier (unsigned HOST_WIDE_INT, int,
2379                                                  int, rtx *, int *, int *);
2380 static unsigned HOST_WIDE_INT invert_mod2n (unsigned HOST_WIDE_INT, int);
2381 static rtx extract_high_half (enum machine_mode, rtx);
2382 static rtx expand_mult_highpart (enum machine_mode, rtx, rtx, rtx, int, int);
2383 static rtx expand_mult_highpart_optab (enum machine_mode, rtx, rtx, rtx,
2384                                        int, int);
2385 /* Compute and return the best algorithm for multiplying by T.
2386    The algorithm must cost less than cost_limit
2387    If retval.cost >= COST_LIMIT, no algorithm was found and all
2388    other field of the returned struct are undefined.
2389    MODE is the machine mode of the multiplication.  */
2390
2391 static void
2392 synth_mult (struct algorithm *alg_out, unsigned HOST_WIDE_INT t,
2393             const struct mult_cost *cost_limit, enum machine_mode mode)
2394 {
2395   int m;
2396   struct algorithm *alg_in, *best_alg;
2397   struct mult_cost best_cost;
2398   struct mult_cost new_limit;
2399   int op_cost, op_latency;
2400   unsigned HOST_WIDE_INT q;
2401   int maxm = MIN (BITS_PER_WORD, GET_MODE_BITSIZE (mode));
2402   int hash_index;
2403   bool cache_hit = false;
2404   enum alg_code cache_alg = alg_zero;
2405   bool speed = optimize_insn_for_speed_p ();
2406
2407   /* Indicate that no algorithm is yet found.  If no algorithm
2408      is found, this value will be returned and indicate failure.  */
2409   alg_out->cost.cost = cost_limit->cost + 1;
2410   alg_out->cost.latency = cost_limit->latency + 1;
2411
2412   if (cost_limit->cost < 0
2413       || (cost_limit->cost == 0 && cost_limit->latency <= 0))
2414     return;
2415
2416   /* Restrict the bits of "t" to the multiplication's mode.  */
2417   t &= GET_MODE_MASK (mode);
2418
2419   /* t == 1 can be done in zero cost.  */
2420   if (t == 1)
2421     {
2422       alg_out->ops = 1;
2423       alg_out->cost.cost = 0;
2424       alg_out->cost.latency = 0;
2425       alg_out->op[0] = alg_m;
2426       return;
2427     }
2428
2429   /* t == 0 sometimes has a cost.  If it does and it exceeds our limit,
2430      fail now.  */
2431   if (t == 0)
2432     {
2433       if (MULT_COST_LESS (cost_limit, zero_cost[speed]))
2434         return;
2435       else
2436         {
2437           alg_out->ops = 1;
2438           alg_out->cost.cost = zero_cost[speed];
2439           alg_out->cost.latency = zero_cost[speed];
2440           alg_out->op[0] = alg_zero;
2441           return;
2442         }
2443     }
2444
2445   /* We'll be needing a couple extra algorithm structures now.  */
2446
2447   alg_in = XALLOCA (struct algorithm);
2448   best_alg = XALLOCA (struct algorithm);
2449   best_cost = *cost_limit;
2450
2451   /* Compute the hash index.  */
2452   hash_index = (t ^ (unsigned int) mode ^ (speed * 256)) % NUM_ALG_HASH_ENTRIES;
2453
2454   /* See if we already know what to do for T.  */
2455   if (alg_hash[hash_index].t == t
2456       && alg_hash[hash_index].mode == mode
2457       && alg_hash[hash_index].mode == mode
2458       && alg_hash[hash_index].speed == speed
2459       && alg_hash[hash_index].alg != alg_unknown)
2460     {
2461       cache_alg = alg_hash[hash_index].alg;
2462
2463       if (cache_alg == alg_impossible)
2464         {
2465           /* The cache tells us that it's impossible to synthesize
2466              multiplication by T within alg_hash[hash_index].cost.  */
2467           if (!CHEAPER_MULT_COST (&alg_hash[hash_index].cost, cost_limit))
2468             /* COST_LIMIT is at least as restrictive as the one
2469                recorded in the hash table, in which case we have no
2470                hope of synthesizing a multiplication.  Just
2471                return.  */
2472             return;
2473
2474           /* If we get here, COST_LIMIT is less restrictive than the
2475              one recorded in the hash table, so we may be able to
2476              synthesize a multiplication.  Proceed as if we didn't
2477              have the cache entry.  */
2478         }
2479       else
2480         {
2481           if (CHEAPER_MULT_COST (cost_limit, &alg_hash[hash_index].cost))
2482             /* The cached algorithm shows that this multiplication
2483                requires more cost than COST_LIMIT.  Just return.  This
2484                way, we don't clobber this cache entry with
2485                alg_impossible but retain useful information.  */
2486             return;
2487
2488           cache_hit = true;
2489
2490           switch (cache_alg)
2491             {
2492             case alg_shift:
2493               goto do_alg_shift;
2494
2495             case alg_add_t_m2:
2496             case alg_sub_t_m2:
2497               goto do_alg_addsub_t_m2;
2498
2499             case alg_add_factor:
2500             case alg_sub_factor:
2501               goto do_alg_addsub_factor;
2502
2503             case alg_add_t2_m:
2504               goto do_alg_add_t2_m;
2505
2506             case alg_sub_t2_m:
2507               goto do_alg_sub_t2_m;
2508
2509             default:
2510               gcc_unreachable ();
2511             }
2512         }
2513     }
2514
2515   /* If we have a group of zero bits at the low-order part of T, try
2516      multiplying by the remaining bits and then doing a shift.  */
2517
2518   if ((t & 1) == 0)
2519     {
2520     do_alg_shift:
2521       m = floor_log2 (t & -t);  /* m = number of low zero bits */
2522       if (m < maxm)
2523         {
2524           q = t >> m;
2525           /* The function expand_shift will choose between a shift and
2526              a sequence of additions, so the observed cost is given as
2527              MIN (m * add_cost[speed][mode], shift_cost[speed][mode][m]).  */
2528           op_cost = m * add_cost[speed][mode];
2529           if (shift_cost[speed][mode][m] < op_cost)
2530             op_cost = shift_cost[speed][mode][m];
2531           new_limit.cost = best_cost.cost - op_cost;
2532           new_limit.latency = best_cost.latency - op_cost;
2533           synth_mult (alg_in, q, &new_limit, mode);
2534
2535           alg_in->cost.cost += op_cost;
2536           alg_in->cost.latency += op_cost;
2537           if (CHEAPER_MULT_COST (&alg_in->cost, &best_cost))
2538             {
2539               struct algorithm *x;
2540               best_cost = alg_in->cost;
2541               x = alg_in, alg_in = best_alg, best_alg = x;
2542               best_alg->log[best_alg->ops] = m;
2543               best_alg->op[best_alg->ops] = alg_shift;
2544             }
2545         }
2546       if (cache_hit)
2547         goto done;
2548     }
2549
2550   /* If we have an odd number, add or subtract one.  */
2551   if ((t & 1) != 0)
2552     {
2553       unsigned HOST_WIDE_INT w;
2554
2555     do_alg_addsub_t_m2:
2556       for (w = 1; (w & t) != 0; w <<= 1)
2557         ;
2558       /* If T was -1, then W will be zero after the loop.  This is another
2559          case where T ends with ...111.  Handling this with (T + 1) and
2560          subtract 1 produces slightly better code and results in algorithm
2561          selection much faster than treating it like the ...0111 case
2562          below.  */
2563       if (w == 0
2564           || (w > 2
2565               /* Reject the case where t is 3.
2566                  Thus we prefer addition in that case.  */
2567               && t != 3))
2568         {
2569           /* T ends with ...111.  Multiply by (T + 1) and subtract 1.  */
2570
2571           op_cost = add_cost[speed][mode];
2572           new_limit.cost = best_cost.cost - op_cost;
2573           new_limit.latency = best_cost.latency - op_cost;
2574           synth_mult (alg_in, t + 1, &new_limit, mode);
2575
2576           alg_in->cost.cost += op_cost;
2577           alg_in->cost.latency += op_cost;
2578           if (CHEAPER_MULT_COST (&alg_in->cost, &best_cost))
2579             {
2580               struct algorithm *x;
2581               best_cost = alg_in->cost;
2582               x = alg_in, alg_in = best_alg, best_alg = x;
2583               best_alg->log[best_alg->ops] = 0;
2584               best_alg->op[best_alg->ops] = alg_sub_t_m2;
2585             }
2586         }
2587       else
2588         {
2589           /* T ends with ...01 or ...011.  Multiply by (T - 1) and add 1.  */
2590
2591           op_cost = add_cost[speed][mode];
2592           new_limit.cost = best_cost.cost - op_cost;
2593           new_limit.latency = best_cost.latency - op_cost;
2594           synth_mult (alg_in, t - 1, &new_limit, mode);
2595
2596           alg_in->cost.cost += op_cost;
2597           alg_in->cost.latency += op_cost;
2598           if (CHEAPER_MULT_COST (&alg_in->cost, &best_cost))
2599             {
2600               struct algorithm *x;
2601               best_cost = alg_in->cost;
2602               x = alg_in, alg_in = best_alg, best_alg = x;
2603               best_alg->log[best_alg->ops] = 0;
2604               best_alg->op[best_alg->ops] = alg_add_t_m2;
2605             }
2606         }
2607       if (cache_hit)
2608         goto done;
2609     }
2610
2611   /* Look for factors of t of the form
2612      t = q(2**m +- 1), 2 <= m <= floor(log2(t - 1)).
2613      If we find such a factor, we can multiply by t using an algorithm that
2614      multiplies by q, shift the result by m and add/subtract it to itself.
2615
2616      We search for large factors first and loop down, even if large factors
2617      are less probable than small; if we find a large factor we will find a
2618      good sequence quickly, and therefore be able to prune (by decreasing
2619      COST_LIMIT) the search.  */
2620
2621  do_alg_addsub_factor:
2622   for (m = floor_log2 (t - 1); m >= 2; m--)
2623     {
2624       unsigned HOST_WIDE_INT d;
2625
2626       d = ((unsigned HOST_WIDE_INT) 1 << m) + 1;
2627       if (t % d == 0 && t > d && m < maxm
2628           && (!cache_hit || cache_alg == alg_add_factor))
2629         {
2630           /* If the target has a cheap shift-and-add instruction use
2631              that in preference to a shift insn followed by an add insn.
2632              Assume that the shift-and-add is "atomic" with a latency
2633              equal to its cost, otherwise assume that on superscalar
2634              hardware the shift may be executed concurrently with the
2635              earlier steps in the algorithm.  */
2636           op_cost = add_cost[speed][mode] + shift_cost[speed][mode][m];
2637           if (shiftadd_cost[speed][mode][m] < op_cost)
2638             {
2639               op_cost = shiftadd_cost[speed][mode][m];
2640               op_latency = op_cost;
2641             }
2642           else
2643             op_latency = add_cost[speed][mode];
2644
2645           new_limit.cost = best_cost.cost - op_cost;
2646           new_limit.latency = best_cost.latency - op_latency;
2647           synth_mult (alg_in, t / d, &new_limit, mode);
2648
2649           alg_in->cost.cost += op_cost;
2650           alg_in->cost.latency += op_latency;
2651           if (alg_in->cost.latency < op_cost)
2652             alg_in->cost.latency = op_cost;
2653           if (CHEAPER_MULT_COST (&alg_in->cost, &best_cost))
2654             {
2655               struct algorithm *x;
2656               best_cost = alg_in->cost;
2657               x = alg_in, alg_in = best_alg, best_alg = x;
2658               best_alg->log[best_alg->ops] = m;
2659               best_alg->op[best_alg->ops] = alg_add_factor;
2660             }
2661           /* Other factors will have been taken care of in the recursion.  */
2662           break;
2663         }
2664
2665       d = ((unsigned HOST_WIDE_INT) 1 << m) - 1;
2666       if (t % d == 0 && t > d && m < maxm
2667           && (!cache_hit || cache_alg == alg_sub_factor))
2668         {
2669           /* If the target has a cheap shift-and-subtract insn use
2670              that in preference to a shift insn followed by a sub insn.
2671              Assume that the shift-and-sub is "atomic" with a latency
2672              equal to it's cost, otherwise assume that on superscalar
2673              hardware the shift may be executed concurrently with the
2674              earlier steps in the algorithm.  */
2675           op_cost = add_cost[speed][mode] + shift_cost[speed][mode][m];
2676           if (shiftsub_cost[speed][mode][m] < op_cost)
2677             {
2678               op_cost = shiftsub_cost[speed][mode][m];
2679               op_latency = op_cost;
2680             }
2681           else
2682             op_latency = add_cost[speed][mode];
2683
2684           new_limit.cost = best_cost.cost - op_cost;
2685           new_limit.latency = best_cost.latency - op_latency;
2686           synth_mult (alg_in, t / d, &new_limit, mode);
2687
2688           alg_in->cost.cost += op_cost;
2689           alg_in->cost.latency += op_latency;
2690           if (alg_in->cost.latency < op_cost)
2691             alg_in->cost.latency = op_cost;
2692           if (CHEAPER_MULT_COST (&alg_in->cost, &best_cost))
2693             {
2694               struct algorithm *x;
2695               best_cost = alg_in->cost;
2696               x = alg_in, alg_in = best_alg, best_alg = x;
2697               best_alg->log[best_alg->ops] = m;
2698               best_alg->op[best_alg->ops] = alg_sub_factor;
2699             }
2700           break;
2701         }
2702     }
2703   if (cache_hit)
2704     goto done;
2705
2706   /* Try shift-and-add (load effective address) instructions,
2707      i.e. do a*3, a*5, a*9.  */
2708   if ((t & 1) != 0)
2709     {
2710     do_alg_add_t2_m:
2711       q = t - 1;
2712       q = q & -q;
2713       m = exact_log2 (q);
2714       if (m >= 0 && m < maxm)
2715         {
2716           op_cost = shiftadd_cost[speed][mode][m];
2717           new_limit.cost = best_cost.cost - op_cost;
2718           new_limit.latency = best_cost.latency - op_cost;
2719           synth_mult (alg_in, (t - 1) >> m, &new_limit, mode);
2720
2721           alg_in->cost.cost += op_cost;
2722           alg_in->cost.latency += op_cost;
2723           if (CHEAPER_MULT_COST (&alg_in->cost, &best_cost))
2724             {
2725               struct algorithm *x;
2726               best_cost = alg_in->cost;
2727               x = alg_in, alg_in = best_alg, best_alg = x;
2728               best_alg->log[best_alg->ops] = m;
2729               best_alg->op[best_alg->ops] = alg_add_t2_m;
2730             }
2731         }
2732       if (cache_hit)
2733         goto done;
2734
2735     do_alg_sub_t2_m:
2736       q = t + 1;
2737       q = q & -q;
2738       m = exact_log2 (q);
2739       if (m >= 0 && m < maxm)
2740         {
2741           op_cost = shiftsub_cost[speed][mode][m];
2742           new_limit.cost = best_cost.cost - op_cost;
2743           new_limit.latency = best_cost.latency - op_cost;
2744           synth_mult (alg_in, (t + 1) >> m, &new_limit, mode);
2745
2746           alg_in->cost.cost += op_cost;
2747           alg_in->cost.latency += op_cost;
2748           if (CHEAPER_MULT_COST (&alg_in->cost, &best_cost))
2749             {
2750               struct algorithm *x;
2751               best_cost = alg_in->cost;
2752               x = alg_in, alg_in = best_alg, best_alg = x;
2753               best_alg->log[best_alg->ops] = m;
2754               best_alg->op[best_alg->ops] = alg_sub_t2_m;
2755             }
2756         }
2757       if (cache_hit)
2758         goto done;
2759     }
2760
2761  done:
2762   /* If best_cost has not decreased, we have not found any algorithm.  */
2763   if (!CHEAPER_MULT_COST (&best_cost, cost_limit))
2764     {
2765       /* We failed to find an algorithm.  Record alg_impossible for
2766          this case (that is, <T, MODE, COST_LIMIT>) so that next time
2767          we are asked to find an algorithm for T within the same or
2768          lower COST_LIMIT, we can immediately return to the
2769          caller.  */
2770       alg_hash[hash_index].t = t;
2771       alg_hash[hash_index].mode = mode;
2772       alg_hash[hash_index].speed = speed;
2773       alg_hash[hash_index].alg = alg_impossible;
2774       alg_hash[hash_index].cost = *cost_limit;
2775       return;
2776     }
2777
2778   /* Cache the result.  */
2779   if (!cache_hit)
2780     {
2781       alg_hash[hash_index].t = t;
2782       alg_hash[hash_index].mode = mode;
2783       alg_hash[hash_index].speed = speed;
2784       alg_hash[hash_index].alg = best_alg->op[best_alg->ops];
2785       alg_hash[hash_index].cost.cost = best_cost.cost;
2786       alg_hash[hash_index].cost.latency = best_cost.latency;
2787     }
2788
2789   /* If we are getting a too long sequence for `struct algorithm'
2790      to record, make this search fail.  */
2791   if (best_alg->ops == MAX_BITS_PER_WORD)
2792     return;
2793
2794   /* Copy the algorithm from temporary space to the space at alg_out.
2795      We avoid using structure assignment because the majority of
2796      best_alg is normally undefined, and this is a critical function.  */
2797   alg_out->ops = best_alg->ops + 1;
2798   alg_out->cost = best_cost;
2799   memcpy (alg_out->op, best_alg->op,
2800           alg_out->ops * sizeof *alg_out->op);
2801   memcpy (alg_out->log, best_alg->log,
2802           alg_out->ops * sizeof *alg_out->log);
2803 }
2804 \f
2805 /* Find the cheapest way of multiplying a value of mode MODE by VAL.
2806    Try three variations:
2807
2808        - a shift/add sequence based on VAL itself
2809        - a shift/add sequence based on -VAL, followed by a negation
2810        - a shift/add sequence based on VAL - 1, followed by an addition.
2811
2812    Return true if the cheapest of these cost less than MULT_COST,
2813    describing the algorithm in *ALG and final fixup in *VARIANT.  */
2814
2815 static bool
2816 choose_mult_variant (enum machine_mode mode, HOST_WIDE_INT val,
2817                      struct algorithm *alg, enum mult_variant *variant,
2818                      int mult_cost)
2819 {
2820   struct algorithm alg2;
2821   struct mult_cost limit;
2822   int op_cost;
2823   bool speed = optimize_insn_for_speed_p ();
2824
2825   /* Fail quickly for impossible bounds.  */
2826   if (mult_cost < 0)
2827     return false;
2828
2829   /* Ensure that mult_cost provides a reasonable upper bound.
2830      Any constant multiplication can be performed with less
2831      than 2 * bits additions.  */
2832   op_cost = 2 * GET_MODE_BITSIZE (mode) * add_cost[speed][mode];
2833   if (mult_cost > op_cost)
2834     mult_cost = op_cost;
2835
2836   *variant = basic_variant;
2837   limit.cost = mult_cost;
2838   limit.latency = mult_cost;
2839   synth_mult (alg, val, &limit, mode);
2840
2841   /* This works only if the inverted value actually fits in an
2842      `unsigned int' */
2843   if (HOST_BITS_PER_INT >= GET_MODE_BITSIZE (mode))
2844     {
2845       op_cost = neg_cost[speed][mode];
2846       if (MULT_COST_LESS (&alg->cost, mult_cost))
2847         {
2848           limit.cost = alg->cost.cost - op_cost;
2849           limit.latency = alg->cost.latency - op_cost;
2850         }
2851       else
2852         {
2853           limit.cost = mult_cost - op_cost;
2854           limit.latency = mult_cost - op_cost;
2855         }
2856
2857       synth_mult (&alg2, -val, &limit, mode);
2858       alg2.cost.cost += op_cost;
2859       alg2.cost.latency += op_cost;
2860       if (CHEAPER_MULT_COST (&alg2.cost, &alg->cost))
2861         *alg = alg2, *variant = negate_variant;
2862     }
2863
2864   /* This proves very useful for division-by-constant.  */
2865   op_cost = add_cost[speed][mode];
2866   if (MULT_COST_LESS (&alg->cost, mult_cost))
2867     {
2868       limit.cost = alg->cost.cost - op_cost;
2869       limit.latency = alg->cost.latency - op_cost;
2870     }
2871   else
2872     {
2873       limit.cost = mult_cost - op_cost;
2874       limit.latency = mult_cost - op_cost;
2875     }
2876
2877   synth_mult (&alg2, val - 1, &limit, mode);
2878   alg2.cost.cost += op_cost;
2879   alg2.cost.latency += op_cost;
2880   if (CHEAPER_MULT_COST (&alg2.cost, &alg->cost))
2881     *alg = alg2, *variant = add_variant;
2882
2883   return MULT_COST_LESS (&alg->cost, mult_cost);
2884 }
2885
2886 /* A subroutine of expand_mult, used for constant multiplications.
2887    Multiply OP0 by VAL in mode MODE, storing the result in TARGET if
2888    convenient.  Use the shift/add sequence described by ALG and apply
2889    the final fixup specified by VARIANT.  */
2890
2891 static rtx
2892 expand_mult_const (enum machine_mode mode, rtx op0, HOST_WIDE_INT val,
2893                    rtx target, const struct algorithm *alg,
2894                    enum mult_variant variant)
2895 {
2896   HOST_WIDE_INT val_so_far;
2897   rtx insn, accum, tem;
2898   int opno;
2899   enum machine_mode nmode;
2900
2901   /* Avoid referencing memory over and over and invalid sharing
2902      on SUBREGs.  */
2903   op0 = force_reg (mode, op0);
2904
2905   /* ACCUM starts out either as OP0 or as a zero, depending on
2906      the first operation.  */
2907
2908   if (alg->op[0] == alg_zero)
2909     {
2910       accum = copy_to_mode_reg (mode, const0_rtx);
2911       val_so_far = 0;
2912     }
2913   else if (alg->op[0] == alg_m)
2914     {
2915       accum = copy_to_mode_reg (mode, op0);
2916       val_so_far = 1;
2917     }
2918   else
2919     gcc_unreachable ();
2920
2921   for (opno = 1; opno < alg->ops; opno++)
2922     {
2923       int log = alg->log[opno];
2924       rtx shift_subtarget = optimize ? 0 : accum;
2925       rtx add_target
2926         = (opno == alg->ops - 1 && target != 0 && variant != add_variant
2927            && !optimize)
2928           ? target : 0;
2929       rtx accum_target = optimize ? 0 : accum;
2930
2931       switch (alg->op[opno])
2932         {
2933         case alg_shift:
2934           tem = expand_shift (LSHIFT_EXPR, mode, accum,
2935                               build_int_cst (NULL_TREE, log),
2936                               NULL_RTX, 0);
2937           /* REG_EQUAL note will be attached to the following insn.  */
2938           emit_move_insn (accum, tem);
2939           val_so_far <<= log;
2940           break;
2941
2942         case alg_add_t_m2:
2943           tem = expand_shift (LSHIFT_EXPR, mode, op0,
2944                               build_int_cst (NULL_TREE, log),
2945                               NULL_RTX, 0);
2946           accum = force_operand (gen_rtx_PLUS (mode, accum, tem),
2947                                  add_target ? add_target : accum_target);
2948           val_so_far += (HOST_WIDE_INT) 1 << log;
2949           break;
2950
2951         case alg_sub_t_m2:
2952           tem = expand_shift (LSHIFT_EXPR, mode, op0,
2953                               build_int_cst (NULL_TREE, log),
2954                               NULL_RTX, 0);
2955           accum = force_operand (gen_rtx_MINUS (mode, accum, tem),
2956                                  add_target ? add_target : accum_target);
2957           val_so_far -= (HOST_WIDE_INT) 1 << log;
2958           break;
2959
2960         case alg_add_t2_m:
2961           accum = expand_shift (LSHIFT_EXPR, mode, accum,
2962                                 build_int_cst (NULL_TREE, log),
2963                                 shift_subtarget,
2964                                 0);
2965           accum = force_operand (gen_rtx_PLUS (mode, accum, op0),
2966                                  add_target ? add_target : accum_target);
2967           val_so_far = (val_so_far << log) + 1;
2968           break;
2969
2970         case alg_sub_t2_m:
2971           accum = expand_shift (LSHIFT_EXPR, mode, accum,
2972                                 build_int_cst (NULL_TREE, log),
2973                                 shift_subtarget, 0);
2974           accum = force_operand (gen_rtx_MINUS (mode, accum, op0),
2975                                  add_target ? add_target : accum_target);
2976           val_so_far = (val_so_far << log) - 1;
2977           break;
2978
2979         case alg_add_factor:
2980           tem = expand_shift (LSHIFT_EXPR, mode, accum,
2981                               build_int_cst (NULL_TREE, log),
2982                               NULL_RTX, 0);
2983           accum = force_operand (gen_rtx_PLUS (mode, accum, tem),
2984                                  add_target ? add_target : accum_target);
2985           val_so_far += val_so_far << log;
2986           break;
2987
2988         case alg_sub_factor:
2989           tem = expand_shift (LSHIFT_EXPR, mode, accum,
2990                               build_int_cst (NULL_TREE, log),
2991                               NULL_RTX, 0);
2992           accum = force_operand (gen_rtx_MINUS (mode, tem, accum),
2993                                  (add_target
2994                                   ? add_target : (optimize ? 0 : tem)));
2995           val_so_far = (val_so_far << log) - val_so_far;
2996           break;
2997
2998         default:
2999           gcc_unreachable ();
3000         }
3001
3002       /* Write a REG_EQUAL note on the last insn so that we can cse
3003          multiplication sequences.  Note that if ACCUM is a SUBREG,
3004          we've set the inner register and must properly indicate
3005          that.  */
3006
3007       tem = op0, nmode = mode;
3008       if (GET_CODE (accum) == SUBREG)
3009         {
3010           nmode = GET_MODE (SUBREG_REG (accum));
3011           tem = gen_lowpart (nmode, op0);
3012         }
3013
3014       insn = get_last_insn ();
3015       set_unique_reg_note (insn, REG_EQUAL,
3016                            gen_rtx_MULT (nmode, tem,
3017                                          GEN_INT (val_so_far)));
3018     }
3019
3020   if (variant == negate_variant)
3021     {
3022       val_so_far = -val_so_far;
3023       accum = expand_unop (mode, neg_optab, accum, target, 0);
3024     }
3025   else if (variant == add_variant)
3026     {
3027       val_so_far = val_so_far + 1;
3028       accum = force_operand (gen_rtx_PLUS (mode, accum, op0), target);
3029     }
3030
3031   /* Compare only the bits of val and val_so_far that are significant
3032      in the result mode, to avoid sign-/zero-extension confusion.  */
3033   val &= GET_MODE_MASK (mode);
3034   val_so_far &= GET_MODE_MASK (mode);
3035   gcc_assert (val == val_so_far);
3036
3037   return accum;
3038 }
3039
3040 /* Perform a multiplication and return an rtx for the result.
3041    MODE is mode of value; OP0 and OP1 are what to multiply (rtx's);
3042    TARGET is a suggestion for where to store the result (an rtx).
3043
3044    We check specially for a constant integer as OP1.
3045    If you want this check for OP0 as well, then before calling
3046    you should swap the two operands if OP0 would be constant.  */
3047
3048 rtx
3049 expand_mult (enum machine_mode mode, rtx op0, rtx op1, rtx target,
3050              int unsignedp)
3051 {
3052   enum mult_variant variant;
3053   struct algorithm algorithm;
3054   int max_cost;
3055   bool speed = optimize_insn_for_speed_p ();
3056
3057   /* Handling const0_rtx here allows us to use zero as a rogue value for
3058      coeff below.  */
3059   if (op1 == const0_rtx)
3060     return const0_rtx;
3061   if (op1 == const1_rtx)
3062     return op0;
3063   if (op1 == constm1_rtx)
3064     return expand_unop (mode,
3065                         GET_MODE_CLASS (mode) == MODE_INT
3066                         && !unsignedp && flag_trapv
3067                         ? negv_optab : neg_optab,
3068                         op0, target, 0);
3069
3070   /* These are the operations that are potentially turned into a sequence
3071      of shifts and additions.  */
3072   if (SCALAR_INT_MODE_P (mode)
3073       && (unsignedp || !flag_trapv))
3074     {
3075       HOST_WIDE_INT coeff = 0;
3076       rtx fake_reg = gen_raw_REG (mode, LAST_VIRTUAL_REGISTER + 1);
3077
3078       /* synth_mult does an `unsigned int' multiply.  As long as the mode is
3079          less than or equal in size to `unsigned int' this doesn't matter.
3080          If the mode is larger than `unsigned int', then synth_mult works
3081          only if the constant value exactly fits in an `unsigned int' without
3082          any truncation.  This means that multiplying by negative values does
3083          not work; results are off by 2^32 on a 32 bit machine.  */
3084
3085       if (GET_CODE (op1) == CONST_INT)
3086         {
3087           /* Attempt to handle multiplication of DImode values by negative
3088              coefficients, by performing the multiplication by a positive
3089              multiplier and then inverting the result.  */
3090           if (INTVAL (op1) < 0
3091               && GET_MODE_BITSIZE (mode) > HOST_BITS_PER_WIDE_INT)
3092             {
3093               /* Its safe to use -INTVAL (op1) even for INT_MIN, as the
3094                  result is interpreted as an unsigned coefficient.
3095                  Exclude cost of op0 from max_cost to match the cost
3096                  calculation of the synth_mult.  */
3097               max_cost = rtx_cost (gen_rtx_MULT (mode, fake_reg, op1), SET, speed)
3098                          - neg_cost[speed][mode];
3099               if (max_cost > 0
3100                   && choose_mult_variant (mode, -INTVAL (op1), &algorithm,
3101                                           &variant, max_cost))
3102                 {
3103                   rtx temp = expand_mult_const (mode, op0, -INTVAL (op1),
3104                                                 NULL_RTX, &algorithm,
3105                                                 variant);
3106                   return expand_unop (mode, neg_optab, temp, target, 0);
3107                 }
3108             }
3109           else coeff = INTVAL (op1);
3110         }
3111       else if (GET_CODE (op1) == CONST_DOUBLE)
3112         {
3113           /* If we are multiplying in DImode, it may still be a win
3114              to try to work with shifts and adds.  */
3115           if (CONST_DOUBLE_HIGH (op1) == 0
3116               && CONST_DOUBLE_LOW (op1) > 0)
3117             coeff = CONST_DOUBLE_LOW (op1);
3118           else if (CONST_DOUBLE_LOW (op1) == 0
3119                    && EXACT_POWER_OF_2_OR_ZERO_P (CONST_DOUBLE_HIGH (op1)))
3120             {
3121               int shift = floor_log2 (CONST_DOUBLE_HIGH (op1))
3122                           + HOST_BITS_PER_WIDE_INT;
3123               return expand_shift (LSHIFT_EXPR, mode, op0,
3124                                    build_int_cst (NULL_TREE, shift),
3125                                    target, unsignedp);
3126             }
3127         }
3128         
3129       /* We used to test optimize here, on the grounds that it's better to
3130          produce a smaller program when -O is not used.  But this causes
3131          such a terrible slowdown sometimes that it seems better to always
3132          use synth_mult.  */
3133       if (coeff != 0)
3134         {
3135           /* Special case powers of two.  */
3136           if (EXACT_POWER_OF_2_OR_ZERO_P (coeff))
3137             return expand_shift (LSHIFT_EXPR, mode, op0,
3138                                  build_int_cst (NULL_TREE, floor_log2 (coeff)),
3139                                  target, unsignedp);
3140
3141           /* Exclude cost of op0 from max_cost to match the cost
3142              calculation of the synth_mult.  */
3143           max_cost = rtx_cost (gen_rtx_MULT (mode, fake_reg, op1), SET, speed);
3144           if (choose_mult_variant (mode, coeff, &algorithm, &variant,
3145                                    max_cost))
3146             return expand_mult_const (mode, op0, coeff, target,
3147                                       &algorithm, variant);
3148         }
3149     }
3150
3151   if (GET_CODE (op0) == CONST_DOUBLE)
3152     {
3153       rtx temp = op0;
3154       op0 = op1;
3155       op1 = temp;
3156     }
3157
3158   /* Expand x*2.0 as x+x.  */
3159   if (GET_CODE (op1) == CONST_DOUBLE
3160       && SCALAR_FLOAT_MODE_P (mode))
3161     {
3162       REAL_VALUE_TYPE d;
3163       REAL_VALUE_FROM_CONST_DOUBLE (d, op1);
3164
3165       if (REAL_VALUES_EQUAL (d, dconst2))
3166         {
3167           op0 = force_reg (GET_MODE (op0), op0);
3168           return expand_binop (mode, add_optab, op0, op0,
3169                                target, unsignedp, OPTAB_LIB_WIDEN);
3170         }
3171     }
3172
3173   /* This used to use umul_optab if unsigned, but for non-widening multiply
3174      there is no difference between signed and unsigned.  */
3175   op0 = expand_binop (mode,
3176                       ! unsignedp
3177                       && flag_trapv && (GET_MODE_CLASS(mode) == MODE_INT)
3178                       ? smulv_optab : smul_optab,
3179                       op0, op1, target, unsignedp, OPTAB_LIB_WIDEN);
3180   gcc_assert (op0);
3181   return op0;
3182 }
3183 \f
3184 /* Return the smallest n such that 2**n >= X.  */
3185
3186 int
3187 ceil_log2 (unsigned HOST_WIDE_INT x)
3188 {
3189   return floor_log2 (x - 1) + 1;
3190 }
3191
3192 /* Choose a minimal N + 1 bit approximation to 1/D that can be used to
3193    replace division by D, and put the least significant N bits of the result
3194    in *MULTIPLIER_PTR and return the most significant bit.
3195
3196    The width of operations is N (should be <= HOST_BITS_PER_WIDE_INT), the
3197    needed precision is in PRECISION (should be <= N).
3198
3199    PRECISION should be as small as possible so this function can choose
3200    multiplier more freely.
3201
3202    The rounded-up logarithm of D is placed in *lgup_ptr.  A shift count that
3203    is to be used for a final right shift is placed in *POST_SHIFT_PTR.
3204
3205    Using this function, x/D will be equal to (x * m) >> (*POST_SHIFT_PTR),
3206    where m is the full HOST_BITS_PER_WIDE_INT + 1 bit multiplier.  */
3207
3208 static
3209 unsigned HOST_WIDE_INT
3210 choose_multiplier (unsigned HOST_WIDE_INT d, int n, int precision,
3211                    rtx *multiplier_ptr, int *post_shift_ptr, int *lgup_ptr)
3212 {
3213   HOST_WIDE_INT mhigh_hi, mlow_hi;
3214   unsigned HOST_WIDE_INT mhigh_lo, mlow_lo;
3215   int lgup, post_shift;
3216   int pow, pow2;
3217   unsigned HOST_WIDE_INT nl, dummy1;
3218   HOST_WIDE_INT nh, dummy2;
3219
3220   /* lgup = ceil(log2(divisor)); */
3221   lgup = ceil_log2 (d);
3222
3223   gcc_assert (lgup <= n);
3224
3225   pow = n + lgup;
3226   pow2 = n + lgup - precision;
3227
3228   /* We could handle this with some effort, but this case is much
3229      better handled directly with a scc insn, so rely on caller using
3230      that.  */
3231   gcc_assert (pow != 2 * HOST_BITS_PER_WIDE_INT);
3232
3233   /* mlow = 2^(N + lgup)/d */
3234  if (pow >= HOST_BITS_PER_WIDE_INT)
3235     {
3236       nh = (HOST_WIDE_INT) 1 << (pow - HOST_BITS_PER_WIDE_INT);
3237       nl = 0;
3238     }
3239   else
3240     {
3241       nh = 0;
3242       nl = (unsigned HOST_WIDE_INT) 1 << pow;
3243     }
3244   div_and_round_double (TRUNC_DIV_EXPR, 1, nl, nh, d, (HOST_WIDE_INT) 0,
3245                         &mlow_lo, &mlow_hi, &dummy1, &dummy2);
3246
3247   /* mhigh = (2^(N + lgup) + 2^N + lgup - precision)/d */
3248   if (pow2 >= HOST_BITS_PER_WIDE_INT)
3249     nh |= (HOST_WIDE_INT) 1 << (pow2 - HOST_BITS_PER_WIDE_INT);
3250   else
3251     nl |= (unsigned HOST_WIDE_INT) 1 << pow2;
3252   div_and_round_double (TRUNC_DIV_EXPR, 1, nl, nh, d, (HOST_WIDE_INT) 0,
3253                         &mhigh_lo, &mhigh_hi, &dummy1, &dummy2);
3254
3255   gcc_assert (!mhigh_hi || nh - d < d);
3256   gcc_assert (mhigh_hi <= 1 && mlow_hi <= 1);
3257   /* Assert that mlow < mhigh.  */
3258   gcc_assert (mlow_hi < mhigh_hi
3259               || (mlow_hi == mhigh_hi && mlow_lo < mhigh_lo));
3260
3261   /* If precision == N, then mlow, mhigh exceed 2^N
3262      (but they do not exceed 2^(N+1)).  */
3263
3264   /* Reduce to lowest terms.  */
3265   for (post_shift = lgup; post_shift > 0; post_shift--)
3266     {
3267       unsigned HOST_WIDE_INT ml_lo = (mlow_hi << (HOST_BITS_PER_WIDE_INT - 1)) | (mlow_lo >> 1);
3268       unsigned HOST_WIDE_INT mh_lo = (mhigh_hi << (HOST_BITS_PER_WIDE_INT - 1)) | (mhigh_lo >> 1);
3269       if (ml_lo >= mh_lo)
3270         break;
3271
3272       mlow_hi = 0;
3273       mlow_lo = ml_lo;
3274       mhigh_hi = 0;
3275       mhigh_lo = mh_lo;
3276     }
3277
3278   *post_shift_ptr = post_shift;
3279   *lgup_ptr = lgup;
3280   if (n < HOST_BITS_PER_WIDE_INT)
3281     {
3282       unsigned HOST_WIDE_INT mask = ((unsigned HOST_WIDE_INT) 1 << n) - 1;
3283       *multiplier_ptr = GEN_INT (mhigh_lo & mask);
3284       return mhigh_lo >= mask;
3285     }
3286   else
3287     {
3288       *multiplier_ptr = GEN_INT (mhigh_lo);
3289       return mhigh_hi;
3290     }
3291 }
3292
3293 /* Compute the inverse of X mod 2**n, i.e., find Y such that X * Y is
3294    congruent to 1 (mod 2**N).  */
3295
3296 static unsigned HOST_WIDE_INT
3297 invert_mod2n (unsigned HOST_WIDE_INT x, int n)
3298 {
3299   /* Solve x*y == 1 (mod 2^n), where x is odd.  Return y.  */
3300
3301   /* The algorithm notes that the choice y = x satisfies
3302      x*y == 1 mod 2^3, since x is assumed odd.
3303      Each iteration doubles the number of bits of significance in y.  */
3304
3305   unsigned HOST_WIDE_INT mask;
3306   unsigned HOST_WIDE_INT y = x;
3307   int nbit = 3;
3308
3309   mask = (n == HOST_BITS_PER_WIDE_INT
3310           ? ~(unsigned HOST_WIDE_INT) 0
3311           : ((unsigned HOST_WIDE_INT) 1 << n) - 1);
3312
3313   while (nbit < n)
3314     {
3315       y = y * (2 - x*y) & mask;         /* Modulo 2^N */
3316       nbit *= 2;
3317     }
3318   return y;
3319 }
3320
3321 /* Emit code to adjust ADJ_OPERAND after multiplication of wrong signedness
3322    flavor of OP0 and OP1.  ADJ_OPERAND is already the high half of the
3323    product OP0 x OP1.  If UNSIGNEDP is nonzero, adjust the signed product
3324    to become unsigned, if UNSIGNEDP is zero, adjust the unsigned product to
3325    become signed.
3326
3327    The result is put in TARGET if that is convenient.
3328
3329    MODE is the mode of operation.  */
3330
3331 rtx
3332 expand_mult_highpart_adjust (enum machine_mode mode, rtx adj_operand, rtx op0,
3333                              rtx op1, rtx target, int unsignedp)
3334 {
3335   rtx tem;
3336   enum rtx_code adj_code = unsignedp ? PLUS : MINUS;
3337
3338   tem = expand_shift (RSHIFT_EXPR, mode, op0,
3339                       build_int_cst (NULL_TREE, GET_MODE_BITSIZE (mode) - 1),
3340                       NULL_RTX, 0);
3341   tem = expand_and (mode, tem, op1, NULL_RTX);
3342   adj_operand
3343     = force_operand (gen_rtx_fmt_ee (adj_code, mode, adj_operand, tem),
3344                      adj_operand);
3345
3346   tem = expand_shift (RSHIFT_EXPR, mode, op1,
3347                       build_int_cst (NULL_TREE, GET_MODE_BITSIZE (mode) - 1),
3348                       NULL_RTX, 0);
3349   tem = expand_and (mode, tem, op0, NULL_RTX);
3350   target = force_operand (gen_rtx_fmt_ee (adj_code, mode, adj_operand, tem),
3351                           target);
3352
3353   return target;
3354 }
3355
3356 /* Subroutine of expand_mult_highpart.  Return the MODE high part of OP.  */
3357
3358 static rtx
3359 extract_high_half (enum machine_mode mode, rtx op)
3360 {
3361   enum machine_mode wider_mode;
3362
3363   if (mode == word_mode)
3364     return gen_highpart (mode, op);
3365
3366   gcc_assert (!SCALAR_FLOAT_MODE_P (mode));
3367
3368   wider_mode = GET_MODE_WIDER_MODE (mode);
3369   op = expand_shift (RSHIFT_EXPR, wider_mode, op,
3370                      build_int_cst (NULL_TREE, GET_MODE_BITSIZE (mode)), 0, 1);
3371   return convert_modes (mode, wider_mode, op, 0);
3372 }
3373
3374 /* Like expand_mult_highpart, but only consider using a multiplication
3375    optab.  OP1 is an rtx for the constant operand.  */
3376
3377 static rtx
3378 expand_mult_highpart_optab (enum machine_mode mode, rtx op0, rtx op1,
3379                             rtx target, int unsignedp, int max_cost)
3380 {
3381   rtx narrow_op1 = gen_int_mode (INTVAL (op1), mode);
3382   enum machine_mode wider_mode;
3383   optab moptab;
3384   rtx tem;
3385   int size;
3386   bool speed = optimize_insn_for_speed_p ();
3387
3388   gcc_assert (!SCALAR_FLOAT_MODE_P (mode));
3389
3390   wider_mode = GET_MODE_WIDER_MODE (mode);
3391   size = GET_MODE_BITSIZE (mode);
3392
3393   /* Firstly, try using a multiplication insn that only generates the needed
3394      high part of the product, and in the sign flavor of unsignedp.  */
3395   if (mul_highpart_cost[speed][mode] < max_cost)
3396     {
3397       moptab = unsignedp ? umul_highpart_optab : smul_highpart_optab;
3398       tem = expand_binop (mode, moptab, op0, narrow_op1, target,
3399                           unsignedp, OPTAB_DIRECT);
3400       if (tem)
3401         return tem;
3402     }
3403
3404   /* Secondly, same as above, but use sign flavor opposite of unsignedp.
3405      Need to adjust the result after the multiplication.  */
3406   if (size - 1 < BITS_PER_WORD
3407       && (mul_highpart_cost[speed][mode] + 2 * shift_cost[speed][mode][size-1]
3408           + 4 * add_cost[speed][mode] < max_cost))
3409     {
3410       moptab = unsignedp ? smul_highpart_optab : umul_highpart_optab;
3411       tem = expand_binop (mode, moptab, op0, narrow_op1, target,
3412                           unsignedp, OPTAB_DIRECT);
3413       if (tem)
3414         /* We used the wrong signedness.  Adjust the result.  */
3415         return expand_mult_highpart_adjust (mode, tem, op0, narrow_op1,
3416                                             tem, unsignedp);
3417     }
3418
3419   /* Try widening multiplication.  */
3420   moptab = unsignedp ? umul_widen_optab : smul_widen_optab;
3421   if (optab_handler (moptab, wider_mode)->insn_code != CODE_FOR_nothing
3422       && mul_widen_cost[speed][wider_mode] < max_cost)
3423     {
3424       tem = expand_binop (wider_mode, moptab, op0, narrow_op1, 0,
3425                           unsignedp, OPTAB_WIDEN);
3426       if (tem)
3427         return extract_high_half (mode, tem);
3428     }
3429
3430   /* Try widening the mode and perform a non-widening multiplication.  */
3431   if (optab_handler (smul_optab, wider_mode)->insn_code != CODE_FOR_nothing
3432       && size - 1 < BITS_PER_WORD
3433       && mul_cost[speed][wider_mode] + shift_cost[speed][mode][size-1] < max_cost)
3434     {
3435       rtx insns, wop0, wop1;
3436
3437       /* We need to widen the operands, for example to ensure the
3438          constant multiplier is correctly sign or zero extended.
3439          Use a sequence to clean-up any instructions emitted by
3440          the conversions if things don't work out.  */
3441       start_sequence ();
3442       wop0 = convert_modes (wider_mode, mode, op0, unsignedp);
3443       wop1 = convert_modes (wider_mode, mode, op1, unsignedp);
3444       tem = expand_binop (wider_mode, smul_optab, wop0, wop1, 0,
3445                           unsignedp, OPTAB_WIDEN);
3446       insns = get_insns ();
3447       end_sequence ();
3448
3449       if (tem)
3450         {
3451           emit_insn (insns);
3452           return extract_high_half (mode, tem);
3453         }
3454     }
3455
3456   /* Try widening multiplication of opposite signedness, and adjust.  */
3457   moptab = unsignedp ? smul_widen_optab : umul_widen_optab;
3458   if (optab_handler (moptab, wider_mode)->insn_code != CODE_FOR_nothing
3459       && size - 1 < BITS_PER_WORD
3460       && (mul_widen_cost[speed][wider_mode] + 2 * shift_cost[speed][mode][size-1]
3461           + 4 * add_cost[speed][mode] < max_cost))
3462     {
3463       tem = expand_binop (wider_mode, moptab, op0, narrow_op1,
3464                           NULL_RTX, ! unsignedp, OPTAB_WIDEN);
3465       if (tem != 0)
3466         {
3467           tem = extract_high_half (mode, tem);
3468           /* We used the wrong signedness.  Adjust the result.  */
3469           return expand_mult_highpart_adjust (mode, tem, op0, narrow_op1,
3470                                               target, unsignedp);
3471         }
3472     }
3473
3474   return 0;
3475 }
3476
3477 /* Emit code to multiply OP0 and OP1 (where OP1 is an integer constant),
3478    putting the high half of the result in TARGET if that is convenient,
3479    and return where the result is.  If the operation can not be performed,
3480    0 is returned.
3481
3482    MODE is the mode of operation and result.
3483
3484    UNSIGNEDP nonzero means unsigned multiply.
3485
3486    MAX_COST is the total allowed cost for the expanded RTL.  */
3487
3488 static rtx
3489 expand_mult_highpart (enum machine_mode mode, rtx op0, rtx op1,
3490                       rtx target, int unsignedp, int max_cost)
3491 {
3492   enum machine_mode wider_mode = GET_MODE_WIDER_MODE (mode);
3493   unsigned HOST_WIDE_INT cnst1;
3494   int extra_cost;
3495   bool sign_adjust = false;
3496   enum mult_variant variant;
3497   struct algorithm alg;
3498   rtx tem;
3499   bool speed = optimize_insn_for_speed_p ();
3500
3501   gcc_assert (!SCALAR_FLOAT_MODE_P (mode));
3502   /* We can't support modes wider than HOST_BITS_PER_INT.  */
3503   gcc_assert (GET_MODE_BITSIZE (mode) <= HOST_BITS_PER_WIDE_INT);
3504
3505   cnst1 = INTVAL (op1) & GET_MODE_MASK (mode);
3506
3507   /* We can't optimize modes wider than BITS_PER_WORD. 
3508      ??? We might be able to perform double-word arithmetic if 
3509      mode == word_mode, however all the cost calculations in
3510      synth_mult etc. assume single-word operations.  */
3511   if (GET_MODE_BITSIZE (wider_mode) > BITS_PER_WORD)
3512     return expand_mult_highpart_optab (mode, op0, op1, target,
3513                                        unsignedp, max_cost);
3514
3515   extra_cost = shift_cost[speed][mode][GET_MODE_BITSIZE (mode) - 1];
3516
3517   /* Check whether we try to multiply by a negative constant.  */
3518   if (!unsignedp && ((cnst1 >> (GET_MODE_BITSIZE (mode) - 1)) & 1))
3519     {
3520       sign_adjust = true;
3521       extra_cost += add_cost[speed][mode];
3522     }
3523
3524   /* See whether shift/add multiplication is cheap enough.  */
3525   if (choose_mult_variant (wider_mode, cnst1, &alg, &variant,
3526                            max_cost - extra_cost))
3527     {
3528       /* See whether the specialized multiplication optabs are
3529          cheaper than the shift/add version.  */
3530       tem = expand_mult_highpart_optab (mode, op0, op1, target, unsignedp,
3531                                         alg.cost.cost + extra_cost);
3532       if (tem)
3533         return tem;
3534
3535       tem = convert_to_mode (wider_mode, op0, unsignedp);
3536       tem = expand_mult_const (wider_mode, tem, cnst1, 0, &alg, variant);
3537       tem = extract_high_half (mode, tem);
3538
3539       /* Adjust result for signedness.  */
3540       if (sign_adjust)
3541         tem = force_operand (gen_rtx_MINUS (mode, tem, op0), tem);
3542
3543       return tem;
3544     }
3545   return expand_mult_highpart_optab (mode, op0, op1, target,
3546                                      unsignedp, max_cost);
3547 }
3548
3549
3550 /* Expand signed modulus of OP0 by a power of two D in mode MODE.  */
3551
3552 static rtx
3553 expand_smod_pow2 (enum machine_mode mode, rtx op0, HOST_WIDE_INT d)
3554 {
3555   unsigned HOST_WIDE_INT masklow, maskhigh;
3556   rtx result, temp, shift, label;
3557   int logd;
3558
3559   logd = floor_log2 (d);
3560   result = gen_reg_rtx (mode);
3561
3562   /* Avoid conditional branches when they're expensive.  */
3563   if (BRANCH_COST (optimize_insn_for_speed_p (), false) >= 2
3564       && optimize_insn_for_speed_p ())
3565     {
3566       rtx signmask = emit_store_flag (result, LT, op0, const0_rtx,
3567                                       mode, 0, -1);
3568       if (signmask)
3569         {
3570           signmask = force_reg (mode, signmask);
3571           masklow = ((HOST_WIDE_INT) 1 << logd) - 1;
3572           shift = GEN_INT (GET_MODE_BITSIZE (mode) - logd);
3573
3574           /* Use the rtx_cost of a LSHIFTRT instruction to determine
3575              which instruction sequence to use.  If logical right shifts
3576              are expensive the use 2 XORs, 2 SUBs and an AND, otherwise
3577              use a LSHIFTRT, 1 ADD, 1 SUB and an AND.  */
3578
3579           temp = gen_rtx_LSHIFTRT (mode, result, shift);
3580           if (optab_handler (lshr_optab, mode)->insn_code == CODE_FOR_nothing
3581               || rtx_cost (temp, SET, optimize_insn_for_speed_p ()) > COSTS_N_INSNS (2))
3582             {
3583               temp = expand_binop (mode, xor_optab, op0, signmask,
3584                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3585               temp = expand_binop (mode, sub_optab, temp, signmask,
3586                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3587               temp = expand_binop (mode, and_optab, temp, GEN_INT (masklow),
3588                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3589               temp = expand_binop (mode, xor_optab, temp, signmask,
3590                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3591               temp = expand_binop (mode, sub_optab, temp, signmask,
3592                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3593             }
3594           else
3595             {
3596               signmask = expand_binop (mode, lshr_optab, signmask, shift,
3597                                        NULL_RTX, 1, OPTAB_LIB_WIDEN);
3598               signmask = force_reg (mode, signmask);
3599
3600               temp = expand_binop (mode, add_optab, op0, signmask,
3601                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3602               temp = expand_binop (mode, and_optab, temp, GEN_INT (masklow),
3603                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3604               temp = expand_binop (mode, sub_optab, temp, signmask,
3605                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3606             }
3607           return temp;
3608         }
3609     }
3610
3611   /* Mask contains the mode's signbit and the significant bits of the
3612      modulus.  By including the signbit in the operation, many targets
3613      can avoid an explicit compare operation in the following comparison
3614      against zero.  */
3615
3616   masklow = ((HOST_WIDE_INT) 1 << logd) - 1;
3617   if (GET_MODE_BITSIZE (mode) <= HOST_BITS_PER_WIDE_INT)
3618     {
3619       masklow |= (HOST_WIDE_INT) -1 << (GET_MODE_BITSIZE (mode) - 1);
3620       maskhigh = -1;
3621     }
3622   else
3623     maskhigh = (HOST_WIDE_INT) -1
3624                  << (GET_MODE_BITSIZE (mode) - HOST_BITS_PER_WIDE_INT - 1);
3625
3626   temp = expand_binop (mode, and_optab, op0,
3627                        immed_double_const (masklow, maskhigh, mode),
3628                        result, 1, OPTAB_LIB_WIDEN);
3629   if (temp != result)
3630     emit_move_insn (result, temp);
3631
3632   label = gen_label_rtx ();
3633   do_cmp_and_jump (result, const0_rtx, GE, mode, label);
3634
3635   temp = expand_binop (mode, sub_optab, result, const1_rtx, result,
3636                        0, OPTAB_LIB_WIDEN);
3637   masklow = (HOST_WIDE_INT) -1 << logd;
3638   maskhigh = -1;
3639   temp = expand_binop (mode, ior_optab, temp,
3640                        immed_double_const (masklow, maskhigh, mode),
3641                        result, 1, OPTAB_LIB_WIDEN);
3642   temp = expand_binop (mode, add_optab, temp, const1_rtx, result,
3643                        0, OPTAB_LIB_WIDEN);
3644   if (temp != result)
3645     emit_move_insn (result, temp);
3646   emit_label (label);
3647   return result;
3648 }
3649
3650 /* Expand signed division of OP0 by a power of two D in mode MODE.
3651    This routine is only called for positive values of D.  */
3652
3653 static rtx
3654 expand_sdiv_pow2 (enum machine_mode mode, rtx op0, HOST_WIDE_INT d)
3655 {
3656   rtx temp, label;
3657   tree shift;
3658   int logd;
3659
3660   logd = floor_log2 (d);
3661   shift = build_int_cst (NULL_TREE, logd);
3662
3663   if (d == 2
3664       && BRANCH_COST (optimize_insn_for_speed_p (),
3665                       false) >= 1)
3666     {
3667       temp = gen_reg_rtx (mode);
3668       temp = emit_store_flag (temp, LT, op0, const0_rtx, mode, 0, 1);
3669       temp = expand_binop (mode, add_optab, temp, op0, NULL_RTX,
3670                            0, OPTAB_LIB_WIDEN);
3671       return expand_shift (RSHIFT_EXPR, mode, temp, shift, NULL_RTX, 0);
3672     }
3673
3674 #ifdef HAVE_conditional_move
3675   if (BRANCH_COST (optimize_insn_for_speed_p (), false)
3676       >= 2)
3677     {
3678       rtx temp2;
3679
3680       /* ??? emit_conditional_move forces a stack adjustment via
3681          compare_from_rtx so, if the sequence is discarded, it will
3682          be lost.  Do it now instead.  */
3683       do_pending_stack_adjust ();
3684
3685       start_sequence ();
3686       temp2 = copy_to_mode_reg (mode, op0);
3687       temp = expand_binop (mode, add_optab, temp2, GEN_INT (d-1),
3688                            NULL_RTX, 0, OPTAB_LIB_WIDEN);
3689       temp = force_reg (mode, temp);
3690
3691       /* Construct "temp2 = (temp2 < 0) ? temp : temp2".  */
3692       temp2 = emit_conditional_move (temp2, LT, temp2, const0_rtx,
3693                                      mode, temp, temp2, mode, 0);
3694       if (temp2)
3695         {
3696           rtx seq = get_insns ();
3697           end_sequence ();
3698           emit_insn (seq);
3699           return expand_shift (RSHIFT_EXPR, mode, temp2, shift, NULL_RTX, 0);
3700         }
3701       end_sequence ();
3702     }
3703 #endif
3704
3705   if (BRANCH_COST (optimize_insn_for_speed_p (),
3706                    false) >= 2)
3707     {
3708       int ushift = GET_MODE_BITSIZE (mode) - logd;
3709
3710       temp = gen_reg_rtx (mode);
3711       temp = emit_store_flag (temp, LT, op0, const0_rtx, mode, 0, -1);
3712       if (shift_cost[optimize_insn_for_speed_p ()][mode][ushift] > COSTS_N_INSNS (1))
3713         temp = expand_binop (mode, and_optab, temp, GEN_INT (d - 1),
3714                              NULL_RTX, 0, OPTAB_LIB_WIDEN);
3715       else
3716         temp = expand_shift (RSHIFT_EXPR, mode, temp,
3717                              build_int_cst (NULL_TREE, ushift),
3718                              NULL_RTX, 1);
3719       temp = expand_binop (mode, add_optab, temp, op0, NULL_RTX,
3720                            0, OPTAB_LIB_WIDEN);
3721       return expand_shift (RSHIFT_EXPR, mode, temp, shift, NULL_RTX, 0);
3722     }
3723
3724   label = gen_label_rtx ();
3725   temp = copy_to_mode_reg (mode, op0);
3726   do_cmp_and_jump (temp, const0_rtx, GE, mode, label);
3727   expand_inc (temp, GEN_INT (d - 1));
3728   emit_label (label);
3729   return expand_shift (RSHIFT_EXPR, mode, temp, shift, NULL_RTX, 0);
3730 }
3731 \f
3732 /* Emit the code to divide OP0 by OP1, putting the result in TARGET
3733    if that is convenient, and returning where the result is.
3734    You may request either the quotient or the remainder as the result;
3735    specify REM_FLAG nonzero to get the remainder.
3736
3737    CODE is the expression code for which kind of division this is;
3738    it controls how rounding is done.  MODE is the machine mode to use.
3739    UNSIGNEDP nonzero means do unsigned division.  */
3740
3741 /* ??? For CEIL_MOD_EXPR, can compute incorrect remainder with ANDI
3742    and then correct it by or'ing in missing high bits
3743    if result of ANDI is nonzero.
3744    For ROUND_MOD_EXPR, can use ANDI and then sign-extend the result.
3745    This could optimize to a bfexts instruction.
3746    But C doesn't use these operations, so their optimizations are
3747    left for later.  */
3748 /* ??? For modulo, we don't actually need the highpart of the first product,
3749    the low part will do nicely.  And for small divisors, the second multiply
3750    can also be a low-part only multiply or even be completely left out.
3751    E.g. to calculate the remainder of a division by 3 with a 32 bit
3752    multiply, multiply with 0x55555556 and extract the upper two bits;
3753    the result is exact for inputs up to 0x1fffffff.
3754    The input range can be reduced by using cross-sum rules.
3755    For odd divisors >= 3, the following table gives right shift counts
3756    so that if a number is shifted by an integer multiple of the given
3757    amount, the remainder stays the same:
3758    2, 4, 3, 6, 10, 12, 4, 8, 18, 6, 11, 20, 18, 0, 5, 10, 12, 0, 12, 20,
3759    14, 12, 23, 21, 8, 0, 20, 18, 0, 0, 6, 12, 0, 22, 0, 18, 20, 30, 0, 0,
3760    0, 8, 0, 11, 12, 10, 36, 0, 30, 0, 0, 12, 0, 0, 0, 0, 44, 12, 24, 0,
3761    20, 0, 7, 14, 0, 18, 36, 0, 0, 46, 60, 0, 42, 0, 15, 24, 20, 0, 0, 33,
3762    0, 20, 0, 0, 18, 0, 60, 0, 0, 0, 0, 0, 40, 18, 0, 0, 12
3763
3764    Cross-sum rules for even numbers can be derived by leaving as many bits
3765    to the right alone as the divisor has zeros to the right.
3766    E.g. if x is an unsigned 32 bit number:
3767    (x mod 12) == (((x & 1023) + ((x >> 8) & ~3)) * 0x15555558 >> 2 * 3) >> 28
3768    */
3769
3770 rtx
3771 expand_divmod (int rem_flag, enum tree_code code, enum machine_mode mode,
3772                rtx op0, rtx op1, rtx target, int unsignedp)
3773 {
3774   enum machine_mode compute_mode;
3775   rtx tquotient;
3776   rtx quotient = 0, remainder = 0;
3777   rtx last;
3778   int size;
3779   rtx insn, set;
3780   optab optab1, optab2;
3781   int op1_is_constant, op1_is_pow2 = 0;
3782   int max_cost, extra_cost;
3783   static HOST_WIDE_INT last_div_const = 0;
3784   static HOST_WIDE_INT ext_op1;
3785   bool speed = optimize_insn_for_speed_p ();
3786
3787   op1_is_constant = GET_CODE (op1) == CONST_INT;
3788   if (op1_is_constant)
3789     {
3790       ext_op1 = INTVAL (op1);
3791       if (unsignedp)
3792         ext_op1 &= GET_MODE_MASK (mode);
3793       op1_is_pow2 = ((EXACT_POWER_OF_2_OR_ZERO_P (ext_op1)
3794                      || (! unsignedp && EXACT_POWER_OF_2_OR_ZERO_P (-ext_op1))));
3795     }
3796
3797   /*
3798      This is the structure of expand_divmod:
3799
3800      First comes code to fix up the operands so we can perform the operations
3801      correctly and efficiently.
3802
3803      Second comes a switch statement with code specific for each rounding mode.
3804      For some special operands this code emits all RTL for the desired
3805      operation, for other cases, it generates only a quotient and stores it in
3806      QUOTIENT.  The case for trunc division/remainder might leave quotient = 0,
3807      to indicate that it has not done anything.
3808
3809      Last comes code that finishes the operation.  If QUOTIENT is set and
3810      REM_FLAG is set, the remainder is computed as OP0 - QUOTIENT * OP1.  If
3811      QUOTIENT is not set, it is computed using trunc rounding.
3812
3813      We try to generate special code for division and remainder when OP1 is a
3814      constant.  If |OP1| = 2**n we can use shifts and some other fast
3815      operations.  For other values of OP1, we compute a carefully selected
3816      fixed-point approximation m = 1/OP1, and generate code that multiplies OP0
3817      by m.
3818
3819      In all cases but EXACT_DIV_EXPR, this multiplication requires the upper
3820      half of the product.  Different strategies for generating the product are
3821      implemented in expand_mult_highpart.
3822
3823      If what we actually want is the remainder, we generate that by another
3824      by-constant multiplication and a subtraction.  */
3825
3826   /* We shouldn't be called with OP1 == const1_rtx, but some of the
3827      code below will malfunction if we are, so check here and handle
3828      the special case if so.  */
3829   if (op1 == const1_rtx)
3830     return rem_flag ? const0_rtx : op0;
3831
3832     /* When dividing by -1, we could get an overflow.
3833      negv_optab can handle overflows.  */
3834   if (! unsignedp && op1 == constm1_rtx)
3835     {
3836       if (rem_flag)
3837         return const0_rtx;
3838       return expand_unop (mode, flag_trapv && GET_MODE_CLASS(mode) == MODE_INT
3839                           ? negv_optab : neg_optab, op0, target, 0);
3840     }
3841
3842   if (target
3843       /* Don't use the function value register as a target
3844          since we have to read it as well as write it,
3845          and function-inlining gets confused by this.  */
3846       && ((REG_P (target) && REG_FUNCTION_VALUE_P (target))
3847           /* Don't clobber an operand while doing a multi-step calculation.  */
3848           || ((rem_flag || op1_is_constant)
3849               && (reg_mentioned_p (target, op0)
3850                   || (MEM_P (op0) && MEM_P (target))))
3851           || reg_mentioned_p (target, op1)
3852           || (MEM_P (op1) && MEM_P (target))))
3853     target = 0;
3854
3855   /* Get the mode in which to perform this computation.  Normally it will
3856      be MODE, but sometimes we can't do the desired operation in MODE.
3857      If so, pick a wider mode in which we can do the operation.  Convert
3858      to that mode at the start to avoid repeated conversions.
3859
3860      First see what operations we need.  These depend on the expression
3861      we are evaluating.  (We assume that divxx3 insns exist under the
3862      same conditions that modxx3 insns and that these insns don't normally
3863      fail.  If these assumptions are not correct, we may generate less
3864      efficient code in some cases.)
3865
3866      Then see if we find a mode in which we can open-code that operation
3867      (either a division, modulus, or shift).  Finally, check for the smallest
3868      mode for which we can do the operation with a library call.  */
3869
3870   /* We might want to refine this now that we have division-by-constant
3871      optimization.  Since expand_mult_highpart tries so many variants, it is
3872      not straightforward to generalize this.  Maybe we should make an array
3873      of possible modes in init_expmed?  Save this for GCC 2.7.  */
3874
3875   optab1 = ((op1_is_pow2 && op1 != const0_rtx)
3876             ? (unsignedp ? lshr_optab : ashr_optab)
3877             : (unsignedp ? udiv_optab : sdiv_optab));
3878   optab2 = ((op1_is_pow2 && op1 != const0_rtx)
3879             ? optab1
3880             : (unsignedp ? udivmod_optab : sdivmod_optab));
3881
3882   for (compute_mode = mode; compute_mode != VOIDmode;
3883        compute_mode = GET_MODE_WIDER_MODE (compute_mode))
3884     if (optab_handler (optab1, compute_mode)->insn_code != CODE_FOR_nothing
3885         || optab_handler (optab2, compute_mode)->insn_code != CODE_FOR_nothing)
3886       break;
3887
3888   if (compute_mode == VOIDmode)
3889     for (compute_mode = mode; compute_mode != VOIDmode;
3890          compute_mode = GET_MODE_WIDER_MODE (compute_mode))
3891       if (optab_libfunc (optab1, compute_mode)
3892           || optab_libfunc (optab2, compute_mode))
3893         break;
3894
3895   /* If we still couldn't find a mode, use MODE, but expand_binop will
3896      probably die.  */
3897   if (compute_mode == VOIDmode)
3898     compute_mode = mode;
3899
3900   if (target && GET_MODE (target) == compute_mode)
3901     tquotient = target;
3902   else
3903     tquotient = gen_reg_rtx (compute_mode);
3904
3905   size = GET_MODE_BITSIZE (compute_mode);
3906 #if 0
3907   /* It should be possible to restrict the precision to GET_MODE_BITSIZE
3908      (mode), and thereby get better code when OP1 is a constant.  Do that
3909      later.  It will require going over all usages of SIZE below.  */
3910   size = GET_MODE_BITSIZE (mode);
3911 #endif
3912
3913   /* Only deduct something for a REM if the last divide done was
3914      for a different constant.   Then set the constant of the last
3915      divide.  */
3916   max_cost = unsignedp ? udiv_cost[speed][compute_mode] : sdiv_cost[speed][compute_mode];
3917   if (rem_flag && ! (last_div_const != 0 && op1_is_constant
3918                      && INTVAL (op1) == last_div_const))
3919     max_cost -= mul_cost[speed][compute_mode] + add_cost[speed][compute_mode];
3920
3921   last_div_const = ! rem_flag && op1_is_constant ? INTVAL (op1) : 0;
3922
3923   /* Now convert to the best mode to use.  */
3924   if (compute_mode != mode)
3925     {
3926       op0 = convert_modes (compute_mode, mode, op0, unsignedp);
3927       op1 = convert_modes (compute_mode, mode, op1, unsignedp);
3928
3929       /* convert_modes may have placed op1 into a register, so we
3930          must recompute the following.  */
3931       op1_is_constant = GET_CODE (op1) == CONST_INT;
3932       op1_is_pow2 = (op1_is_constant
3933                      && ((EXACT_POWER_OF_2_OR_ZERO_P (INTVAL (op1))
3934                           || (! unsignedp
3935                               && EXACT_POWER_OF_2_OR_ZERO_P (-INTVAL (op1)))))) ;
3936     }
3937
3938   /* If one of the operands is a volatile MEM, copy it into a register.  */
3939
3940   if (MEM_P (op0) && MEM_VOLATILE_P (op0))
3941     op0 = force_reg (compute_mode, op0);
3942   if (MEM_P (op1) && MEM_VOLATILE_P (op1))
3943     op1 = force_reg (compute_mode, op1);
3944
3945   /* If we need the remainder or if OP1 is constant, we need to
3946      put OP0 in a register in case it has any queued subexpressions.  */
3947   if (rem_flag || op1_is_constant)
3948     op0 = force_reg (compute_mode, op0);
3949
3950   last = get_last_insn ();
3951
3952   /* Promote floor rounding to trunc rounding for unsigned operations.  */
3953   if (unsignedp)
3954     {
3955       if (code == FLOOR_DIV_EXPR)
3956         code = TRUNC_DIV_EXPR;
3957       if (code == FLOOR_MOD_EXPR)
3958         code = TRUNC_MOD_EXPR;
3959       if (code == EXACT_DIV_EXPR && op1_is_pow2)
3960         code = TRUNC_DIV_EXPR;
3961     }
3962
3963   if (op1 != const0_rtx)
3964     switch (code)
3965       {
3966       case TRUNC_MOD_EXPR:
3967       case TRUNC_DIV_EXPR:
3968         if (op1_is_constant)
3969           {
3970             if (unsignedp)
3971               {
3972                 unsigned HOST_WIDE_INT mh;
3973                 int pre_shift, post_shift;
3974                 int dummy;
3975                 rtx ml;
3976                 unsigned HOST_WIDE_INT d = (INTVAL (op1)
3977                                             & GET_MODE_MASK (compute_mode));
3978
3979                 if (EXACT_POWER_OF_2_OR_ZERO_P (d))
3980                   {
3981                     pre_shift = floor_log2 (d);
3982                     if (rem_flag)
3983                       {
3984                         remainder
3985                           = expand_binop (compute_mode, and_optab, op0,
3986                                           GEN_INT (((HOST_WIDE_INT) 1 << pre_shift) - 1),
3987                                           remainder, 1,
3988                                           OPTAB_LIB_WIDEN);
3989                         if (remainder)
3990                           return gen_lowpart (mode, remainder);
3991                       }
3992                     quotient = expand_shift (RSHIFT_EXPR, compute_mode, op0,
3993                                              build_int_cst (NULL_TREE,
3994                                                             pre_shift),
3995                                              tquotient, 1);
3996                   }
3997                 else if (size <= HOST_BITS_PER_WIDE_INT)
3998                   {
3999                     if (d >= ((unsigned HOST_WIDE_INT) 1 << (size - 1)))
4000                       {
4001                         /* Most significant bit of divisor is set; emit an scc
4002                            insn.  */
4003                         quotient = emit_store_flag (tquotient, GEU, op0, op1,
4004                                                     compute_mode, 1, 1);
4005                         if (quotient == 0)
4006                           goto fail1;
4007                       }
4008                     else
4009                       {
4010                         /* Find a suitable multiplier and right shift count
4011                            instead of multiplying with D.  */
4012
4013                         mh = choose_multiplier (d, size, size,
4014                                                 &ml, &post_shift, &dummy);
4015
4016                         /* If the suggested multiplier is more than SIZE bits,
4017                            we can do better for even divisors, using an
4018                            initial right shift.  */
4019                         if (mh != 0 && (d & 1) == 0)
4020                           {
4021                             pre_shift = floor_log2 (d & -d);
4022                             mh = choose_multiplier (d >> pre_shift, size,
4023                                                     size - pre_shift,
4024                                                     &ml, &post_shift, &dummy);
4025                             gcc_assert (!mh);
4026                           }
4027                         else
4028                           pre_shift = 0;
4029
4030                         if (mh != 0)
4031                           {
4032                             rtx t1, t2, t3, t4;
4033
4034                             if (post_shift - 1 >= BITS_PER_WORD)
4035                               goto fail1;
4036
4037                             extra_cost
4038                               = (shift_cost[speed][compute_mode][post_shift - 1]
4039                                  + shift_cost[speed][compute_mode][1]
4040                                  + 2 * add_cost[speed][compute_mode]);
4041                             t1 = expand_mult_highpart (compute_mode, op0, ml,
4042                                                        NULL_RTX, 1,
4043                                                        max_cost - extra_cost);
4044                             if (t1 == 0)
4045                               goto fail1;
4046                             t2 = force_operand (gen_rtx_MINUS (compute_mode,
4047                                                                op0, t1),
4048                                                 NULL_RTX);
4049                             t3 = expand_shift
4050                               (RSHIFT_EXPR, compute_mode, t2,
4051                                build_int_cst (NULL_TREE, 1),
4052                                NULL_RTX,1);
4053                             t4 = force_operand (gen_rtx_PLUS (compute_mode,
4054                                                               t1, t3),
4055                                                 NULL_RTX);
4056                             quotient = expand_shift
4057                               (RSHIFT_EXPR, compute_mode, t4,
4058                                build_int_cst (NULL_TREE, post_shift - 1),
4059                                tquotient, 1);
4060                           }
4061                         else
4062                           {
4063                             rtx t1, t2;
4064
4065                             if (pre_shift >= BITS_PER_WORD
4066                                 || post_shift >= BITS_PER_WORD)
4067                               goto fail1;
4068
4069                             t1 = expand_shift
4070                               (RSHIFT_EXPR, compute_mode, op0,
4071                                build_int_cst (NULL_TREE, pre_shift),
4072                                NULL_RTX, 1);
4073                             extra_cost
4074                               = (shift_cost[speed][compute_mode][pre_shift]
4075                                  + shift_cost[speed][compute_mode][post_shift]);
4076                             t2 = expand_mult_highpart (compute_mode, t1, ml,
4077                                                        NULL_RTX, 1,
4078                                                        max_cost - extra_cost);
4079                             if (t2 == 0)
4080                               goto fail1;
4081                             quotient = expand_shift
4082                               (RSHIFT_EXPR, compute_mode, t2,
4083                                build_int_cst (NULL_TREE, post_shift),
4084                                tquotient, 1);
4085                           }
4086                       }
4087                   }
4088                 else            /* Too wide mode to use tricky code */
4089                   break;
4090
4091                 insn = get_last_insn ();
4092                 if (insn != last
4093                     && (set = single_set (insn)) != 0
4094                     && SET_DEST (set) == quotient)
4095                   set_unique_reg_note (insn,
4096                                        REG_EQUAL,
4097                                        gen_rtx_UDIV (compute_mode, op0, op1));
4098               }
4099             else                /* TRUNC_DIV, signed */
4100               {
4101                 unsigned HOST_WIDE_INT ml;
4102                 int lgup, post_shift;
4103                 rtx mlr;
4104                 HOST_WIDE_INT d = INTVAL (op1);
4105                 unsigned HOST_WIDE_INT abs_d;
4106
4107                 /* Since d might be INT_MIN, we have to cast to
4108                    unsigned HOST_WIDE_INT before negating to avoid
4109                    undefined signed overflow.  */
4110                 abs_d = (d >= 0
4111                          ? (unsigned HOST_WIDE_INT) d
4112                          : - (unsigned HOST_WIDE_INT) d);
4113
4114                 /* n rem d = n rem -d */
4115                 if (rem_flag && d < 0)
4116                   {
4117                     d = abs_d;
4118                     op1 = gen_int_mode (abs_d, compute_mode);
4119                   }
4120
4121                 if (d == 1)
4122                   quotient = op0;
4123                 else if (d == -1)
4124                   quotient = expand_unop (compute_mode, neg_optab, op0,
4125                                           tquotient, 0);
4126                 else if (HOST_BITS_PER_WIDE_INT >= size
4127                          && abs_d == (unsigned HOST_WIDE_INT) 1 << (size - 1))
4128                   {
4129                     /* This case is not handled correctly below.  */
4130                     quotient = emit_store_flag (tquotient, EQ, op0, op1,
4131                                                 compute_mode, 1, 1);
4132                     if (quotient == 0)
4133                       goto fail1;
4134                   }
4135                 else if (EXACT_POWER_OF_2_OR_ZERO_P (d)
4136                          && (rem_flag ? smod_pow2_cheap[speed][compute_mode]
4137                                       : sdiv_pow2_cheap[speed][compute_mode])
4138                          /* We assume that cheap metric is true if the
4139                             optab has an expander for this mode.  */
4140                          && ((optab_handler ((rem_flag ? smod_optab
4141                                               : sdiv_optab),
4142                                               compute_mode)->insn_code
4143                               != CODE_FOR_nothing)
4144                              || (optab_handler(sdivmod_optab,
4145                                                compute_mode)
4146                                  ->insn_code != CODE_FOR_nothing)))
4147                   ;
4148                 else if (EXACT_POWER_OF_2_OR_ZERO_P (abs_d))
4149                   {
4150                     if (rem_flag)
4151                       {
4152                         remainder = expand_smod_pow2 (compute_mode, op0, d);
4153                         if (remainder)
4154                           return gen_lowpart (mode, remainder);
4155                       }
4156
4157                     if (sdiv_pow2_cheap[speed][compute_mode]
4158                         && ((optab_handler (sdiv_optab, compute_mode)->insn_code
4159                              != CODE_FOR_nothing)
4160                             || (optab_handler (sdivmod_optab, compute_mode)->insn_code
4161                                 != CODE_FOR_nothing)))
4162                       quotient = expand_divmod (0, TRUNC_DIV_EXPR,
4163                                                 compute_mode, op0,
4164                                                 gen_int_mode (abs_d,
4165                                                               compute_mode),
4166                                                 NULL_RTX, 0);
4167                     else
4168                       quotient = expand_sdiv_pow2 (compute_mode, op0, abs_d);
4169
4170                     /* We have computed OP0 / abs(OP1).  If OP1 is negative,
4171                        negate the quotient.  */
4172                     if (d < 0)
4173                       {
4174                         insn = get_last_insn ();
4175                         if (insn != last
4176                             && (set = single_set (insn)) != 0
4177                             && SET_DEST (set) == quotient
4178                             && abs_d < ((unsigned HOST_WIDE_INT) 1
4179                                         << (HOST_BITS_PER_WIDE_INT - 1)))
4180                           set_unique_reg_note (insn,
4181                                                REG_EQUAL,
4182                                                gen_rtx_DIV (compute_mode,
4183                                                             op0,
4184                                                             GEN_INT
4185                                                             (trunc_int_for_mode
4186                                                              (abs_d,
4187                                                               compute_mode))));
4188
4189                         quotient = expand_unop (compute_mode, neg_optab,
4190                                                 quotient, quotient, 0);
4191                       }
4192                   }
4193                 else if (size <= HOST_BITS_PER_WIDE_INT)
4194                   {
4195                     choose_multiplier (abs_d, size, size - 1,
4196                                        &mlr, &post_shift, &lgup);
4197                     ml = (unsigned HOST_WIDE_INT) INTVAL (mlr);
4198                     if (ml < (unsigned HOST_WIDE_INT) 1 << (size - 1))
4199                       {
4200                         rtx t1, t2, t3;
4201
4202                         if (post_shift >= BITS_PER_WORD
4203                             || size - 1 >= BITS_PER_WORD)
4204                           goto fail1;
4205
4206                         extra_cost = (shift_cost[speed][compute_mode][post_shift]
4207                                       + shift_cost[speed][compute_mode][size - 1]
4208                                       + add_cost[speed][compute_mode]);
4209                         t1 = expand_mult_highpart (compute_mode, op0, mlr,
4210                                                    NULL_RTX, 0,
4211                                                    max_cost - extra_cost);
4212                         if (t1 == 0)
4213                           goto fail1;
4214                         t2 = expand_shift
4215                           (RSHIFT_EXPR, compute_mode, t1,
4216                            build_int_cst (NULL_TREE, post_shift),
4217                            NULL_RTX, 0);
4218                         t3 = expand_shift
4219                           (RSHIFT_EXPR, compute_mode, op0,
4220                            build_int_cst (NULL_TREE, size - 1),
4221                            NULL_RTX, 0);
4222                         if (d < 0)
4223                           quotient
4224                             = force_operand (gen_rtx_MINUS (compute_mode,
4225                                                             t3, t2),
4226                                              tquotient);
4227                         else
4228                           quotient
4229                             = force_operand (gen_rtx_MINUS (compute_mode,
4230                                                             t2, t3),
4231                                              tquotient);
4232                       }
4233                     else
4234                       {
4235                         rtx t1, t2, t3, t4;
4236
4237                         if (post_shift >= BITS_PER_WORD
4238                             || size - 1 >= BITS_PER_WORD)
4239                           goto fail1;
4240
4241                         ml |= (~(unsigned HOST_WIDE_INT) 0) << (size - 1);
4242                         mlr = gen_int_mode (ml, compute_mode);
4243                         extra_cost = (shift_cost[speed][compute_mode][post_shift]
4244                                       + shift_cost[speed][compute_mode][size - 1]
4245                                       + 2 * add_cost[speed][compute_mode]);
4246                         t1 = expand_mult_highpart (compute_mode, op0, mlr,
4247                                                    NULL_RTX, 0,
4248                                                    max_cost - extra_cost);
4249                         if (t1 == 0)
4250                           goto fail1;
4251                         t2 = force_operand (gen_rtx_PLUS (compute_mode,
4252                                                           t1, op0),
4253                                             NULL_RTX);
4254                         t3 = expand_shift
4255                           (RSHIFT_EXPR, compute_mode, t2,
4256                            build_int_cst (NULL_TREE, post_shift),
4257                            NULL_RTX, 0);
4258                         t4 = expand_shift
4259                           (RSHIFT_EXPR, compute_mode, op0,
4260                            build_int_cst (NULL_TREE, size - 1),
4261                            NULL_RTX, 0);
4262                         if (d < 0)
4263                           quotient
4264                             = force_operand (gen_rtx_MINUS (compute_mode,
4265                                                             t4, t3),
4266                                              tquotient);
4267                         else
4268                           quotient
4269                             = force_operand (gen_rtx_MINUS (compute_mode,
4270                                                             t3, t4),
4271                                              tquotient);
4272                       }
4273                   }
4274                 else            /* Too wide mode to use tricky code */
4275                   break;
4276
4277                 insn = get_last_insn ();
4278                 if (insn != last
4279                     && (set = single_set (insn)) != 0
4280                     && SET_DEST (set) == quotient)
4281                   set_unique_reg_note (insn,
4282                                        REG_EQUAL,
4283                                        gen_rtx_DIV (compute_mode, op0, op1));
4284               }
4285             break;
4286           }
4287       fail1:
4288         delete_insns_since (last);
4289         break;
4290
4291       case FLOOR_DIV_EXPR:
4292       case FLOOR_MOD_EXPR:
4293       /* We will come here only for signed operations.  */
4294         if (op1_is_constant && HOST_BITS_PER_WIDE_INT >= size)
4295           {
4296             unsigned HOST_WIDE_INT mh;
4297             int pre_shift, lgup, post_shift;
4298             HOST_WIDE_INT d = INTVAL (op1);
4299             rtx ml;
4300
4301             if (d > 0)
4302               {
4303                 /* We could just as easily deal with negative constants here,
4304                    but it does not seem worth the trouble for GCC 2.6.  */
4305                 if (EXACT_POWER_OF_2_OR_ZERO_P (d))
4306                   {
4307                     pre_shift = floor_log2 (d);
4308                     if (rem_flag)
4309                       {
4310                         remainder = expand_binop (compute_mode, and_optab, op0,
4311                                                   GEN_INT (((HOST_WIDE_INT) 1 << pre_shift) - 1),
4312                                                   remainder, 0, OPTAB_LIB_WIDEN);
4313                         if (remainder)
4314                           return gen_lowpart (mode, remainder);
4315                       }
4316                     quotient = expand_shift
4317                       (RSHIFT_EXPR, compute_mode, op0,
4318                        build_int_cst (NULL_TREE, pre_shift),
4319                        tquotient, 0);
4320                   }
4321                 else
4322                   {
4323                     rtx t1, t2, t3, t4;
4324
4325                     mh = choose_multiplier (d, size, size - 1,
4326                                             &ml, &post_shift, &lgup);
4327                     gcc_assert (!mh);
4328
4329                     if (post_shift < BITS_PER_WORD
4330                         && size - 1 < BITS_PER_WORD)
4331                       {
4332                         t1 = expand_shift
4333                           (RSHIFT_EXPR, compute_mode, op0,
4334                            build_int_cst (NULL_TREE, size - 1),
4335                            NULL_RTX, 0);
4336                         t2 = expand_binop (compute_mode, xor_optab, op0, t1,
4337                                            NULL_RTX, 0, OPTAB_WIDEN);
4338                         extra_cost = (shift_cost[speed][compute_mode][post_shift]
4339                                       + shift_cost[speed][compute_mode][size - 1]
4340                                       + 2 * add_cost[speed][compute_mode]);
4341                         t3 = expand_mult_highpart (compute_mode, t2, ml,
4342                                                    NULL_RTX, 1,
4343                                                    max_cost - extra_cost);
4344                         if (t3 != 0)
4345                           {
4346                             t4 = expand_shift
4347                               (RSHIFT_EXPR, compute_mode, t3,
4348                                build_int_cst (NULL_TREE, post_shift),
4349                                NULL_RTX, 1);
4350                             quotient = expand_binop (compute_mode, xor_optab,
4351                                                      t4, t1, tquotient, 0,
4352                                                      OPTAB_WIDEN);
4353                           }
4354                       }
4355                   }
4356               }
4357             else
4358               {
4359                 rtx nsign, t1, t2, t3, t4;
4360                 t1 = force_operand (gen_rtx_PLUS (compute_mode,
4361                                                   op0, constm1_rtx), NULL_RTX);
4362                 t2 = expand_binop (compute_mode, ior_optab, op0, t1, NULL_RTX,
4363                                    0, OPTAB_WIDEN);
4364                 nsign = expand_shift
4365                   (RSHIFT_EXPR, compute_mode, t2,
4366                    build_int_cst (NULL_TREE, size - 1),
4367                    NULL_RTX, 0);
4368                 t3 = force_operand (gen_rtx_MINUS (compute_mode, t1, nsign),
4369                                     NULL_RTX);
4370                 t4 = expand_divmod (0, TRUNC_DIV_EXPR, compute_mode, t3, op1,
4371                                     NULL_RTX, 0);
4372                 if (t4)
4373                   {
4374                     rtx t5;
4375                     t5 = expand_unop (compute_mode, one_cmpl_optab, nsign,
4376                                       NULL_RTX, 0);
4377                     quotient = force_operand (gen_rtx_PLUS (compute_mode,
4378                                                             t4, t5),
4379                                               tquotient);
4380                   }
4381               }
4382           }
4383
4384         if (quotient != 0)
4385           break;
4386         delete_insns_since (last);
4387
4388         /* Try using an instruction that produces both the quotient and
4389            remainder, using truncation.  We can easily compensate the quotient
4390            or remainder to get floor rounding, once we have the remainder.
4391            Notice that we compute also the final remainder value here,
4392            and return the result right away.  */
4393         if (target == 0 || GET_MODE (target) != compute_mode)
4394           target = gen_reg_rtx (compute_mode);
4395
4396         if (rem_flag)
4397           {
4398             remainder
4399               = REG_P (target) ? target : gen_reg_rtx (compute_mode);
4400             quotient = gen_reg_rtx (compute_mode);
4401           }
4402         else
4403           {
4404             quotient
4405               = REG_P (target) ? target : gen_reg_rtx (compute_mode);
4406             remainder = gen_reg_rtx (compute_mode);
4407           }
4408
4409         if (expand_twoval_binop (sdivmod_optab, op0, op1,
4410                                  quotient, remainder, 0))
4411           {
4412             /* This could be computed with a branch-less sequence.
4413                Save that for later.  */
4414             rtx tem;
4415             rtx label = gen_label_rtx ();
4416             do_cmp_and_jump (remainder, const0_rtx, EQ, compute_mode, label);
4417             tem = expand_binop (compute_mode, xor_optab, op0, op1,
4418                                 NULL_RTX, 0, OPTAB_WIDEN);
4419             do_cmp_and_jump (tem, const0_rtx, GE, compute_mode, label);
4420             expand_dec (quotient, const1_rtx);
4421             expand_inc (remainder, op1);
4422             emit_label (label);
4423             return gen_lowpart (mode, rem_flag ? remainder : quotient);
4424           }
4425
4426         /* No luck with division elimination or divmod.  Have to do it
4427            by conditionally adjusting op0 *and* the result.  */
4428         {
4429           rtx label1, label2, label3, label4, label5;
4430           rtx adjusted_op0;
4431           rtx tem;
4432
4433           quotient = gen_reg_rtx (compute_mode);
4434           adjusted_op0 = copy_to_mode_reg (compute_mode, op0);
4435           label1 = gen_label_rtx ();
4436           label2 = gen_label_rtx ();
4437           label3 = gen_label_rtx ();
4438           label4 = gen_label_rtx ();
4439           label5 = gen_label_rtx ();
4440           do_cmp_and_jump (op1, const0_rtx, LT, compute_mode, label2);
4441           do_cmp_and_jump (adjusted_op0, const0_rtx, LT, compute_mode, label1);
4442           tem = expand_binop (compute_mode, sdiv_optab, adjusted_op0, op1,
4443                               quotient, 0, OPTAB_LIB_WIDEN);
4444           if (tem != quotient)
4445             emit_move_insn (quotient, tem);
4446           emit_jump_insn (gen_jump (label5));
4447           emit_barrier ();
4448           emit_label (label1);
4449           expand_inc (adjusted_op0, const1_rtx);
4450           emit_jump_insn (gen_jump (label4));
4451           emit_barrier ();
4452           emit_label (label2);
4453           do_cmp_and_jump (adjusted_op0, const0_rtx, GT, compute_mode, label3);
4454           tem = expand_binop (compute_mode, sdiv_optab, adjusted_op0, op1,
4455                               quotient, 0, OPTAB_LIB_WIDEN);
4456           if (tem != quotient)
4457             emit_move_insn (quotient, tem);
4458           emit_jump_insn (gen_jump (label5));
4459           emit_barrier ();
4460           emit_label (label3);
4461           expand_dec (adjusted_op0, const1_rtx);
4462           emit_label (label4);
4463           tem = expand_binop (compute_mode, sdiv_optab, adjusted_op0, op1,
4464                               quotient, 0, OPTAB_LIB_WIDEN);
4465           if (tem != quotient)
4466             emit_move_insn (quotient, tem);
4467           expand_dec (quotient, const1_rtx);
4468           emit_label (label5);
4469         }
4470         break;
4471
4472       case CEIL_DIV_EXPR:
4473       case CEIL_MOD_EXPR:
4474         if (unsignedp)
4475           {
4476             if (op1_is_constant && EXACT_POWER_OF_2_OR_ZERO_P (INTVAL (op1)))
4477               {
4478                 rtx t1, t2, t3;
4479                 unsigned HOST_WIDE_INT d = INTVAL (op1);
4480                 t1 = expand_shift (RSHIFT_EXPR, compute_mode, op0,
4481                                    build_int_cst (NULL_TREE, floor_log2 (d)),
4482                                    tquotient, 1);
4483                 t2 = expand_binop (compute_mode, and_optab, op0,
4484                                    GEN_INT (d - 1),
4485                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
4486                 t3 = gen_reg_rtx (compute_mode);
4487                 t3 = emit_store_flag (t3, NE, t2, const0_rtx,
4488                                       compute_mode, 1, 1);
4489                 if (t3 == 0)
4490                   {
4491                     rtx lab;
4492                     lab = gen_label_rtx ();
4493                     do_cmp_and_jump (t2, const0_rtx, EQ, compute_mode, lab);
4494                     expand_inc (t1, const1_rtx);
4495                     emit_label (lab);
4496                     quotient = t1;
4497                   }
4498                 else
4499                   quotient = force_operand (gen_rtx_PLUS (compute_mode,
4500                                                           t1, t3),
4501                                             tquotient);
4502                 break;
4503               }
4504
4505             /* Try using an instruction that produces both the quotient and
4506                remainder, using truncation.  We can easily compensate the
4507                quotient or remainder to get ceiling rounding, once we have the
4508                remainder.  Notice that we compute also the final remainder
4509                value here, and return the result right away.  */
4510             if (target == 0 || GET_MODE (target) != compute_mode)
4511               target = gen_reg_rtx (compute_mode);
4512
4513             if (rem_flag)
4514               {
4515                 remainder = (REG_P (target)
4516                              ? target : gen_reg_rtx (compute_mode));
4517                 quotient = gen_reg_rtx (compute_mode);
4518               }
4519             else
4520               {
4521                 quotient = (REG_P (target)
4522                             ? target : gen_reg_rtx (compute_mode));
4523                 remainder = gen_reg_rtx (compute_mode);
4524               }
4525
4526             if (expand_twoval_binop (udivmod_optab, op0, op1, quotient,
4527                                      remainder, 1))
4528               {
4529                 /* This could be computed with a branch-less sequence.
4530                    Save that for later.  */
4531                 rtx label = gen_label_rtx ();
4532                 do_cmp_and_jump (remainder, const0_rtx, EQ,
4533                                  compute_mode, label);
4534                 expand_inc (quotient, const1_rtx);
4535                 expand_dec (remainder, op1);
4536                 emit_label (label);
4537                 return gen_lowpart (mode, rem_flag ? remainder : quotient);
4538               }
4539
4540             /* No luck with division elimination or divmod.  Have to do it
4541                by conditionally adjusting op0 *and* the result.  */
4542             {
4543               rtx label1, label2;
4544               rtx adjusted_op0, tem;
4545
4546               quotient = gen_reg_rtx (compute_mode);
4547               adjusted_op0 = copy_to_mode_reg (compute_mode, op0);
4548               label1 = gen_label_rtx ();
4549               label2 = gen_label_rtx ();
4550               do_cmp_and_jump (adjusted_op0, const0_rtx, NE,
4551                                compute_mode, label1);
4552               emit_move_insn  (quotient, const0_rtx);
4553               emit_jump_insn (gen_jump (label2));
4554               emit_barrier ();
4555               emit_label (label1);
4556               expand_dec (adjusted_op0, const1_rtx);
4557               tem = expand_binop (compute_mode, udiv_optab, adjusted_op0, op1,
4558                                   quotient, 1, OPTAB_LIB_WIDEN);
4559               if (tem != quotient)
4560                 emit_move_insn (quotient, tem);
4561               expand_inc (quotient, const1_rtx);
4562               emit_label (label2);
4563             }
4564           }
4565         else /* signed */
4566           {
4567             if (op1_is_constant && EXACT_POWER_OF_2_OR_ZERO_P (INTVAL (op1))
4568                 && INTVAL (op1) >= 0)
4569               {
4570                 /* This is extremely similar to the code for the unsigned case
4571                    above.  For 2.7 we should merge these variants, but for
4572                    2.6.1 I don't want to touch the code for unsigned since that
4573                    get used in C.  The signed case will only be used by other
4574                    languages (Ada).  */
4575
4576                 rtx t1, t2, t3;
4577                 unsigned HOST_WIDE_INT d = INTVAL (op1);
4578                 t1 = expand_shift (RSHIFT_EXPR, compute_mode, op0,
4579                                    build_int_cst (NULL_TREE, floor_log2 (d)),
4580                                    tquotient, 0);
4581                 t2 = expand_binop (compute_mode, and_optab, op0,
4582                                    GEN_INT (d - 1),
4583                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
4584                 t3 = gen_reg_rtx (compute_mode);
4585                 t3 = emit_store_flag (t3, NE, t2, const0_rtx,
4586                                       compute_mode, 1, 1);
4587                 if (t3 == 0)
4588                   {
4589                     rtx lab;
4590                     lab = gen_label_rtx ();
4591                     do_cmp_and_jump (t2, const0_rtx, EQ, compute_mode, lab);
4592                     expand_inc (t1, const1_rtx);
4593                     emit_label (lab);
4594                     quotient = t1;
4595                   }
4596                 else
4597                   quotient = force_operand (gen_rtx_PLUS (compute_mode,
4598                                                           t1, t3),
4599                                             tquotient);
4600                 break;
4601               }
4602
4603             /* Try using an instruction that produces both the quotient and
4604                remainder, using truncation.  We can easily compensate the
4605                quotient or remainder to get ceiling rounding, once we have the
4606                remainder.  Notice that we compute also the final remainder
4607                value here, and return the result right away.  */
4608             if (target == 0 || GET_MODE (target) != compute_mode)
4609               target = gen_reg_rtx (compute_mode);
4610             if (rem_flag)
4611               {
4612                 remainder= (REG_P (target)
4613                             ? target : gen_reg_rtx (compute_mode));
4614                 quotient = gen_reg_rtx (compute_mode);
4615               }
4616             else
4617               {
4618                 quotient = (REG_P (target)
4619                             ? target : gen_reg_rtx (compute_mode));
4620                 remainder = gen_reg_rtx (compute_mode);
4621               }
4622
4623             if (expand_twoval_binop (sdivmod_optab, op0, op1, quotient,
4624                                      remainder, 0))
4625               {
4626                 /* This could be computed with a branch-less sequence.
4627                    Save that for later.  */
4628                 rtx tem;
4629                 rtx label = gen_label_rtx ();
4630                 do_cmp_and_jump (remainder, const0_rtx, EQ,
4631                                  compute_mode, label);
4632                 tem = expand_binop (compute_mode, xor_optab, op0, op1,
4633                                     NULL_RTX, 0, OPTAB_WIDEN);
4634                 do_cmp_and_jump (tem, const0_rtx, LT, compute_mode, label);
4635                 expand_inc (quotient, const1_rtx);
4636                 expand_dec (remainder, op1);
4637                 emit_label (label);
4638                 return gen_lowpart (mode, rem_flag ? remainder : quotient);
4639               }
4640
4641             /* No luck with division elimination or divmod.  Have to do it
4642                by conditionally adjusting op0 *and* the result.  */
4643             {
4644               rtx label1, label2, label3, label4, label5;
4645               rtx adjusted_op0;
4646               rtx tem;
4647
4648               quotient = gen_reg_rtx (compute_mode);
4649               adjusted_op0 = copy_to_mode_reg (compute_mode, op0);
4650               label1 = gen_label_rtx ();
4651               label2 = gen_label_rtx ();
4652               label3 = gen_label_rtx ();
4653               label4 = gen_label_rtx ();
4654               label5 = gen_label_rtx ();
4655               do_cmp_and_jump (op1, const0_rtx, LT, compute_mode, label2);
4656               do_cmp_and_jump (adjusted_op0, const0_rtx, GT,
4657                                compute_mode, label1);
4658               tem = expand_binop (compute_mode, sdiv_optab, adjusted_op0, op1,
4659                                   quotient, 0, OPTAB_LIB_WIDEN);
4660               if (tem != quotient)
4661                 emit_move_insn (quotient, tem);
4662               emit_jump_insn (gen_jump (label5));
4663               emit_barrier ();
4664               emit_label (label1);
4665               expand_dec (adjusted_op0, const1_rtx);
4666               emit_jump_insn (gen_jump (label4));
4667               emit_barrier ();
4668               emit_label (label2);
4669               do_cmp_and_jump (adjusted_op0, const0_rtx, LT,
4670                                compute_mode, label3);
4671               tem = expand_binop (compute_mode, sdiv_optab, adjusted_op0, op1,
4672                                   quotient, 0, OPTAB_LIB_WIDEN);
4673               if (tem != quotient)
4674                 emit_move_insn (quotient, tem);
4675               emit_jump_insn (gen_jump (label5));
4676               emit_barrier ();
4677               emit_label (label3);
4678               expand_inc (adjusted_op0, const1_rtx);
4679               emit_label (label4);
4680               tem = expand_binop (compute_mode, sdiv_optab, adjusted_op0, op1,
4681                                   quotient, 0, OPTAB_LIB_WIDEN);
4682               if (tem != quotient)
4683                 emit_move_insn (quotient, tem);
4684               expand_inc (quotient, const1_rtx);
4685               emit_label (label5);
4686             }
4687           }
4688         break;
4689
4690       case EXACT_DIV_EXPR:
4691         if (op1_is_constant && HOST_BITS_PER_WIDE_INT >= size)
4692           {
4693             HOST_WIDE_INT d = INTVAL (op1);
4694             unsigned HOST_WIDE_INT ml;
4695             int pre_shift;
4696             rtx t1;
4697
4698             pre_shift = floor_log2 (d & -d);
4699             ml = invert_mod2n (d >> pre_shift, size);
4700             t1 = expand_shift (RSHIFT_EXPR, compute_mode, op0,
4701                                build_int_cst (NULL_TREE, pre_shift),
4702                                NULL_RTX, unsignedp);
4703             quotient = expand_mult (compute_mode, t1,
4704                                     gen_int_mode (ml, compute_mode),
4705                                     NULL_RTX, 1);
4706
4707             insn = get_last_insn ();
4708             set_unique_reg_note (insn,
4709                                  REG_EQUAL,
4710                                  gen_rtx_fmt_ee (unsignedp ? UDIV : DIV,
4711                                                  compute_mode,
4712                                                  op0, op1));
4713           }
4714         break;
4715
4716       case ROUND_DIV_EXPR:
4717       case ROUND_MOD_EXPR:
4718         if (unsignedp)
4719           {
4720             rtx tem;
4721             rtx label;
4722             label = gen_label_rtx ();
4723             quotient = gen_reg_rtx (compute_mode);
4724             remainder = gen_reg_rtx (compute_mode);
4725             if (expand_twoval_binop (udivmod_optab, op0, op1, quotient, remainder, 1) == 0)
4726               {
4727                 rtx tem;
4728                 quotient = expand_binop (compute_mode, udiv_optab, op0, op1,
4729                                          quotient, 1, OPTAB_LIB_WIDEN);
4730                 tem = expand_mult (compute_mode, quotient, op1, NULL_RTX, 1);
4731                 remainder = expand_binop (compute_mode, sub_optab, op0, tem,
4732                                           remainder, 1, OPTAB_LIB_WIDEN);
4733               }
4734             tem = plus_constant (op1, -1);
4735             tem = expand_shift (RSHIFT_EXPR, compute_mode, tem,
4736                                 build_int_cst (NULL_TREE, 1),
4737                                 NULL_RTX, 1);
4738             do_cmp_and_jump (remainder, tem, LEU, compute_mode, label);
4739             expand_inc (quotient, const1_rtx);
4740             expand_dec (remainder, op1);
4741             emit_label (label);
4742           }
4743         else
4744           {
4745             rtx abs_rem, abs_op1, tem, mask;
4746             rtx label;
4747             label = gen_label_rtx ();
4748             quotient = gen_reg_rtx (compute_mode);
4749             remainder = gen_reg_rtx (compute_mode);
4750             if (expand_twoval_binop (sdivmod_optab, op0, op1, quotient, remainder, 0) == 0)
4751               {
4752                 rtx tem;
4753                 quotient = expand_binop (compute_mode, sdiv_optab, op0, op1,
4754                                          quotient, 0, OPTAB_LIB_WIDEN);
4755                 tem = expand_mult (compute_mode, quotient, op1, NULL_RTX, 0);
4756                 remainder = expand_binop (compute_mode, sub_optab, op0, tem,
4757                                           remainder, 0, OPTAB_LIB_WIDEN);
4758               }
4759             abs_rem = expand_abs (compute_mode, remainder, NULL_RTX, 1, 0);
4760             abs_op1 = expand_abs (compute_mode, op1, NULL_RTX, 1, 0);
4761             tem = expand_shift (LSHIFT_EXPR, compute_mode, abs_rem,
4762                                 build_int_cst (NULL_TREE, 1),
4763                                 NULL_RTX, 1);
4764             do_cmp_and_jump (tem, abs_op1, LTU, compute_mode, label);
4765             tem = expand_binop (compute_mode, xor_optab, op0, op1,
4766                                 NULL_RTX, 0, OPTAB_WIDEN);
4767             mask = expand_shift (RSHIFT_EXPR, compute_mode, tem,
4768                                  build_int_cst (NULL_TREE, size - 1),
4769                                  NULL_RTX, 0);
4770             tem = expand_binop (compute_mode, xor_optab, mask, const1_rtx,
4771                                 NULL_RTX, 0, OPTAB_WIDEN);
4772             tem = expand_binop (compute_mode, sub_optab, tem, mask,
4773                                 NULL_RTX, 0, OPTAB_WIDEN);
4774             expand_inc (quotient, tem);
4775             tem = expand_binop (compute_mode, xor_optab, mask, op1,
4776                                 NULL_RTX, 0, OPTAB_WIDEN);
4777             tem = expand_binop (compute_mode, sub_optab, tem, mask,
4778                                 NULL_RTX, 0, OPTAB_WIDEN);
4779             expand_dec (remainder, tem);
4780             emit_label (label);
4781           }
4782         return gen_lowpart (mode, rem_flag ? remainder : quotient);
4783
4784       default:
4785         gcc_unreachable ();
4786       }
4787
4788   if (quotient == 0)
4789     {
4790       if (target && GET_MODE (target) != compute_mode)
4791         target = 0;
4792
4793       if (rem_flag)
4794         {
4795           /* Try to produce the remainder without producing the quotient.
4796              If we seem to have a divmod pattern that does not require widening,
4797              don't try widening here.  We should really have a WIDEN argument
4798              to expand_twoval_binop, since what we'd really like to do here is
4799              1) try a mod insn in compute_mode
4800              2) try a divmod insn in compute_mode
4801              3) try a div insn in compute_mode and multiply-subtract to get
4802                 remainder
4803              4) try the same things with widening allowed.  */
4804           remainder
4805             = sign_expand_binop (compute_mode, umod_optab, smod_optab,
4806                                  op0, op1, target,
4807                                  unsignedp,
4808                                  ((optab_handler (optab2, compute_mode)->insn_code
4809                                    != CODE_FOR_nothing)
4810                                   ? OPTAB_DIRECT : OPTAB_WIDEN));
4811           if (remainder == 0)
4812             {
4813               /* No luck there.  Can we do remainder and divide at once
4814                  without a library call?  */
4815               remainder = gen_reg_rtx (compute_mode);
4816               if (! expand_twoval_binop ((unsignedp
4817                                           ? udivmod_optab
4818                                           : sdivmod_optab),
4819                                          op0, op1,
4820                                          NULL_RTX, remainder, unsignedp))
4821                 remainder = 0;
4822             }
4823
4824           if (remainder)
4825             return gen_lowpart (mode, remainder);
4826         }
4827
4828       /* Produce the quotient.  Try a quotient insn, but not a library call.
4829          If we have a divmod in this mode, use it in preference to widening
4830          the div (for this test we assume it will not fail). Note that optab2
4831          is set to the one of the two optabs that the call below will use.  */
4832       quotient
4833         = sign_expand_binop (compute_mode, udiv_optab, sdiv_optab,
4834                              op0, op1, rem_flag ? NULL_RTX : target,
4835                              unsignedp,
4836                              ((optab_handler (optab2, compute_mode)->insn_code
4837                                != CODE_FOR_nothing)
4838                               ? OPTAB_DIRECT : OPTAB_WIDEN));
4839
4840       if (quotient == 0)
4841         {
4842           /* No luck there.  Try a quotient-and-remainder insn,
4843              keeping the quotient alone.  */
4844           quotient = gen_reg_rtx (compute_mode);
4845           if (! expand_twoval_binop (unsignedp ? udivmod_optab : sdivmod_optab,
4846                                      op0, op1,
4847                                      quotient, NULL_RTX, unsignedp))
4848             {
4849               quotient = 0;
4850               if (! rem_flag)
4851                 /* Still no luck.  If we are not computing the remainder,
4852                    use a library call for the quotient.  */
4853                 quotient = sign_expand_binop (compute_mode,
4854                                               udiv_optab, sdiv_optab,
4855                                               op0, op1, target,
4856                                               unsignedp, OPTAB_LIB_WIDEN);
4857             }
4858         }
4859     }
4860
4861   if (rem_flag)
4862     {
4863       if (target && GET_MODE (target) != compute_mode)
4864         target = 0;
4865
4866       if (quotient == 0)
4867         {
4868           /* No divide instruction either.  Use library for remainder.  */
4869           remainder = sign_expand_binop (compute_mode, umod_optab, smod_optab,
4870                                          op0, op1, target,
4871                                          unsignedp, OPTAB_LIB_WIDEN);
4872           /* No remainder function.  Try a quotient-and-remainder
4873              function, keeping the remainder.  */
4874           if (!remainder)
4875             {
4876               remainder = gen_reg_rtx (compute_mode);
4877               if (!expand_twoval_binop_libfunc 
4878                   (unsignedp ? udivmod_optab : sdivmod_optab,
4879                    op0, op1,
4880                    NULL_RTX, remainder,
4881                    unsignedp ? UMOD : MOD))
4882                 remainder = NULL_RTX;
4883             }
4884         }
4885       else
4886         {
4887           /* We divided.  Now finish doing X - Y * (X / Y).  */
4888           remainder = expand_mult (compute_mode, quotient, op1,
4889                                    NULL_RTX, unsignedp);
4890           remainder = expand_binop (compute_mode, sub_optab, op0,
4891                                     remainder, target, unsignedp,
4892                                     OPTAB_LIB_WIDEN);
4893         }
4894     }
4895
4896   return gen_lowpart (mode, rem_flag ? remainder : quotient);
4897 }
4898 \f
4899 /* Return a tree node with data type TYPE, describing the value of X.
4900    Usually this is an VAR_DECL, if there is no obvious better choice.
4901    X may be an expression, however we only support those expressions
4902    generated by loop.c.  */
4903
4904 tree
4905 make_tree (tree type, rtx x)
4906 {
4907   tree t;
4908
4909   switch (GET_CODE (x))
4910     {
4911     case CONST_INT:
4912       {
4913         HOST_WIDE_INT hi = 0;
4914
4915         if (INTVAL (x) < 0
4916             && !(TYPE_UNSIGNED (type)
4917                  && (GET_MODE_BITSIZE (TYPE_MODE (type))
4918                      < HOST_BITS_PER_WIDE_INT)))
4919           hi = -1;
4920       
4921         t = build_int_cst_wide (type, INTVAL (x), hi);
4922         
4923         return t;
4924       }
4925       
4926     case CONST_DOUBLE:
4927       if (GET_MODE (x) == VOIDmode)
4928         t = build_int_cst_wide (type,
4929                                 CONST_DOUBLE_LOW (x), CONST_DOUBLE_HIGH (x));
4930       else
4931         {
4932           REAL_VALUE_TYPE d;
4933
4934           REAL_VALUE_FROM_CONST_DOUBLE (d, x);
4935           t = build_real (type, d);
4936         }
4937
4938       return t;
4939
4940     case CONST_VECTOR:
4941       {
4942         int units = CONST_VECTOR_NUNITS (x);
4943         tree itype = TREE_TYPE (type);
4944         tree t = NULL_TREE;
4945         int i;
4946
4947
4948         /* Build a tree with vector elements.  */
4949         for (i = units - 1; i >= 0; --i)
4950           {
4951             rtx elt = CONST_VECTOR_ELT (x, i);
4952             t = tree_cons (NULL_TREE, make_tree (itype, elt), t);
4953           }
4954
4955         return build_vector (type, t);
4956       }
4957
4958     case PLUS:
4959       return fold_build2 (PLUS_EXPR, type, make_tree (type, XEXP (x, 0)),
4960                           make_tree (type, XEXP (x, 1)));
4961
4962     case MINUS:
4963       return fold_build2 (MINUS_EXPR, type, make_tree (type, XEXP (x, 0)),
4964                           make_tree (type, XEXP (x, 1)));
4965
4966     case NEG:
4967       return fold_build1 (NEGATE_EXPR, type, make_tree (type, XEXP (x, 0)));
4968
4969     case MULT:
4970       return fold_build2 (MULT_EXPR, type, make_tree (type, XEXP (x, 0)),
4971                           make_tree (type, XEXP (x, 1)));
4972
4973     case ASHIFT:
4974       return fold_build2 (LSHIFT_EXPR, type, make_tree (type, XEXP (x, 0)),
4975                           make_tree (type, XEXP (x, 1)));
4976
4977     case LSHIFTRT:
4978       t = unsigned_type_for (type);
4979       return fold_convert (type, build2 (RSHIFT_EXPR, t,
4980                                          make_tree (t, XEXP (x, 0)),
4981                                          make_tree (type, XEXP (x, 1))));
4982
4983     case ASHIFTRT:
4984       t = signed_type_for (type);
4985       return fold_convert (type, build2 (RSHIFT_EXPR, t,
4986                                          make_tree (t, XEXP (x, 0)),
4987                                          make_tree (type, XEXP (x, 1))));
4988
4989     case DIV:
4990       if (TREE_CODE (type) != REAL_TYPE)
4991         t = signed_type_for (type);
4992       else
4993         t = type;
4994
4995       return fold_convert (type, build2 (TRUNC_DIV_EXPR, t,
4996                                          make_tree (t, XEXP (x, 0)),
4997                                          make_tree (t, XEXP (x, 1))));
4998     case UDIV:
4999       t = unsigned_type_for (type);
5000       return fold_convert (type, build2 (TRUNC_DIV_EXPR, t,
5001                                          make_tree (t, XEXP (x, 0)),
5002                                          make_tree (t, XEXP (x, 1))));
5003
5004     case SIGN_EXTEND:
5005     case ZERO_EXTEND:
5006       t = lang_hooks.types.type_for_mode (GET_MODE (XEXP (x, 0)),
5007                                           GET_CODE (x) == ZERO_EXTEND);
5008       return fold_convert (type, make_tree (t, XEXP (x, 0)));
5009
5010     case CONST:
5011       return make_tree (type, XEXP (x, 0));
5012
5013     case SYMBOL_REF:
5014       t = SYMBOL_REF_DECL (x);
5015       if (t)
5016         return fold_convert (type, build_fold_addr_expr (t));
5017       /* else fall through.  */
5018
5019     default:
5020       t = build_decl (VAR_DECL, NULL_TREE, type);
5021
5022       /* If TYPE is a POINTER_TYPE, X might be Pmode with TYPE_MODE being
5023          ptr_mode.  So convert.  */
5024       if (POINTER_TYPE_P (type))
5025         x = convert_memory_address (TYPE_MODE (type), x);
5026
5027       /* Note that we do *not* use SET_DECL_RTL here, because we do not
5028          want set_decl_rtl to go adjusting REG_ATTRS for this temporary.  */
5029       t->decl_with_rtl.rtl = x;
5030
5031       return t;
5032     }
5033 }
5034 \f
5035 /* Compute the logical-and of OP0 and OP1, storing it in TARGET
5036    and returning TARGET.
5037
5038    If TARGET is 0, a pseudo-register or constant is returned.  */
5039
5040 rtx
5041 expand_and (enum machine_mode mode, rtx op0, rtx op1, rtx target)
5042 {
5043   rtx tem = 0;
5044
5045   if (GET_MODE (op0) == VOIDmode && GET_MODE (op1) == VOIDmode)
5046     tem = simplify_binary_operation (AND, mode, op0, op1);
5047   if (tem == 0)
5048     tem = expand_binop (mode, and_optab, op0, op1, target, 0, OPTAB_LIB_WIDEN);
5049
5050   if (target == 0)
5051     target = tem;
5052   else if (tem != target)
5053     emit_move_insn (target, tem);
5054   return target;
5055 }
5056 \f
5057 /* Helper function for emit_store_flag.  */
5058 static rtx
5059 emit_store_flag_1 (rtx target, rtx subtarget, enum machine_mode mode,
5060                    int normalizep)
5061 {
5062   rtx op0;
5063   enum machine_mode target_mode = GET_MODE (target);
5064   
5065   /* If we are converting to a wider mode, first convert to
5066      TARGET_MODE, then normalize.  This produces better combining
5067      opportunities on machines that have a SIGN_EXTRACT when we are
5068      testing a single bit.  This mostly benefits the 68k.
5069
5070      If STORE_FLAG_VALUE does not have the sign bit set when
5071      interpreted in MODE, we can do this conversion as unsigned, which
5072      is usually more efficient.  */
5073   if (GET_MODE_SIZE (target_mode) > GET_MODE_SIZE (mode))
5074     {
5075       convert_move (target, subtarget,
5076                     (GET_MODE_BITSIZE (mode) <= HOST_BITS_PER_WIDE_INT)
5077                     && 0 == (STORE_FLAG_VALUE
5078                              & ((HOST_WIDE_INT) 1
5079                                 << (GET_MODE_BITSIZE (mode) -1))));
5080       op0 = target;
5081       mode = target_mode;
5082     }
5083   else
5084     op0 = subtarget;
5085
5086   /* If we want to keep subexpressions around, don't reuse our last
5087      target.  */
5088   if (optimize)
5089     subtarget = 0;
5090
5091   /* Now normalize to the proper value in MODE.  Sometimes we don't
5092      have to do anything.  */
5093   if (normalizep == 0 || normalizep == STORE_FLAG_VALUE)
5094     ;
5095   /* STORE_FLAG_VALUE might be the most negative number, so write
5096      the comparison this way to avoid a compiler-time warning.  */
5097   else if (- normalizep == STORE_FLAG_VALUE)
5098     op0 = expand_unop (mode, neg_optab, op0, subtarget, 0);
5099
5100   /* We don't want to use STORE_FLAG_VALUE < 0 below since this makes
5101      it hard to use a value of just the sign bit due to ANSI integer
5102      constant typing rules.  */
5103   else if (GET_MODE_BITSIZE (mode) <= HOST_BITS_PER_WIDE_INT
5104            && (STORE_FLAG_VALUE
5105                & ((HOST_WIDE_INT) 1 << (GET_MODE_BITSIZE (mode) - 1))))
5106     op0 = expand_shift (RSHIFT_EXPR, mode, op0,
5107                         size_int (GET_MODE_BITSIZE (mode) - 1), subtarget,
5108                         normalizep == 1);
5109   else
5110     {
5111       gcc_assert (STORE_FLAG_VALUE & 1);
5112
5113       op0 = expand_and (mode, op0, const1_rtx, subtarget);
5114       if (normalizep == -1)
5115         op0 = expand_unop (mode, neg_optab, op0, op0, 0);
5116     }
5117
5118   /* If we were converting to a smaller mode, do the conversion now.  */
5119   if (target_mode != mode)
5120     {
5121       convert_move (target, op0, 0);
5122       return target;
5123     }
5124   else
5125     return op0;
5126 }
5127
5128 /* Emit a store-flags instruction for comparison CODE on OP0 and OP1
5129    and storing in TARGET.  Normally return TARGET.
5130    Return 0 if that cannot be done.
5131
5132    MODE is the mode to use for OP0 and OP1 should they be CONST_INTs.  If
5133    it is VOIDmode, they cannot both be CONST_INT.
5134
5135    UNSIGNEDP is for the case where we have to widen the operands
5136    to perform the operation.  It says to use zero-extension.
5137
5138    NORMALIZEP is 1 if we should convert the result to be either zero
5139    or one.  Normalize is -1 if we should convert the result to be
5140    either zero or -1.  If NORMALIZEP is zero, the result will be left
5141    "raw" out of the scc insn.  */
5142
5143 rtx
5144 emit_store_flag (rtx target, enum rtx_code code, rtx op0, rtx op1,
5145                  enum machine_mode mode, int unsignedp, int normalizep)
5146 {
5147   rtx subtarget;
5148   enum insn_code icode;
5149   enum machine_mode compare_mode;
5150   enum machine_mode target_mode = GET_MODE (target);
5151   rtx tem;
5152   rtx last = get_last_insn ();
5153   rtx pattern, comparison;
5154
5155   if (unsignedp)
5156     code = unsigned_condition (code);
5157
5158   /* If one operand is constant, make it the second one.  Only do this
5159      if the other operand is not constant as well.  */
5160
5161   if (swap_commutative_operands_p (op0, op1))
5162     {
5163       tem = op0;
5164       op0 = op1;
5165       op1 = tem;
5166       code = swap_condition (code);
5167     }
5168
5169   if (mode == VOIDmode)
5170     mode = GET_MODE (op0);
5171
5172   /* For some comparisons with 1 and -1, we can convert this to
5173      comparisons with zero.  This will often produce more opportunities for
5174      store-flag insns.  */
5175
5176   switch (code)
5177     {
5178     case LT:
5179       if (op1 == const1_rtx)
5180         op1 = const0_rtx, code = LE;
5181       break;
5182     case LE:
5183       if (op1 == constm1_rtx)
5184         op1 = const0_rtx, code = LT;
5185       break;
5186     case GE:
5187       if (op1 == const1_rtx)
5188         op1 = const0_rtx, code = GT;
5189       break;
5190     case GT:
5191       if (op1 == constm1_rtx)
5192         op1 = const0_rtx, code = GE;
5193       break;
5194     case GEU:
5195       if (op1 == const1_rtx)
5196         op1 = const0_rtx, code = NE;
5197       break;
5198     case LTU:
5199       if (op1 == const1_rtx)
5200         op1 = const0_rtx, code = EQ;
5201       break;
5202     default:
5203       break;
5204     }
5205
5206   /* If we are comparing a double-word integer with zero or -1, we can
5207      convert the comparison into one involving a single word.  */
5208   if (GET_MODE_BITSIZE (mode) == BITS_PER_WORD * 2
5209       && GET_MODE_CLASS (mode) == MODE_INT
5210       && (!MEM_P (op0) || ! MEM_VOLATILE_P (op0)))
5211     {
5212       if ((code == EQ || code == NE)
5213           && (op1 == const0_rtx || op1 == constm1_rtx))
5214         {
5215           rtx op00, op01, op0both;
5216
5217           /* Do a logical OR or AND of the two words and compare the
5218              result.  */
5219           op00 = simplify_gen_subreg (word_mode, op0, mode, 0);
5220           op01 = simplify_gen_subreg (word_mode, op0, mode, UNITS_PER_WORD);
5221           op0both = expand_binop (word_mode,
5222                                   op1 == const0_rtx ? ior_optab : and_optab,
5223                                   op00, op01, NULL_RTX, unsignedp,
5224                                   OPTAB_DIRECT);
5225
5226           if (op0both != 0)
5227             return emit_store_flag (target, code, op0both, op1, word_mode,
5228                                     unsignedp, normalizep);
5229         }
5230       else if ((code == LT || code == GE) && op1 == const0_rtx)
5231         {
5232           rtx op0h;
5233
5234           /* If testing the sign bit, can just test on high word.  */
5235           op0h = simplify_gen_subreg (word_mode, op0, mode,
5236                                       subreg_highpart_offset (word_mode,
5237                                                               mode));
5238           return emit_store_flag (target, code, op0h, op1, word_mode,
5239                                   unsignedp, normalizep);
5240         }
5241     }
5242
5243   /* If this is A < 0 or A >= 0, we can do this by taking the ones
5244      complement of A (for GE) and shifting the sign bit to the low bit.  */
5245   if (op1 == const0_rtx && (code == LT || code == GE)
5246       && GET_MODE_CLASS (mode) == MODE_INT
5247       && (normalizep || STORE_FLAG_VALUE == 1
5248           || (GET_MODE_BITSIZE (mode) <= HOST_BITS_PER_WIDE_INT
5249               && ((STORE_FLAG_VALUE & GET_MODE_MASK (mode))
5250                   == ((unsigned HOST_WIDE_INT) 1
5251                       << (GET_MODE_BITSIZE (mode) - 1))))))
5252     {
5253       subtarget = target;
5254
5255       /* If the result is to be wider than OP0, it is best to convert it
5256          first.  If it is to be narrower, it is *incorrect* to convert it
5257          first.  */
5258       if (GET_MODE_SIZE (target_mode) > GET_MODE_SIZE (mode))
5259         {
5260           op0 = convert_modes (target_mode, mode, op0, 0);
5261           mode = target_mode;
5262         }
5263
5264       if (target_mode != mode)
5265         subtarget = 0;
5266
5267       if (code == GE)
5268         op0 = expand_unop (mode, one_cmpl_optab, op0,
5269                            ((STORE_FLAG_VALUE == 1 || normalizep)
5270                             ? 0 : subtarget), 0);
5271
5272       if (STORE_FLAG_VALUE == 1 || normalizep)
5273         /* If we are supposed to produce a 0/1 value, we want to do
5274            a logical shift from the sign bit to the low-order bit; for
5275            a -1/0 value, we do an arithmetic shift.  */
5276         op0 = expand_shift (RSHIFT_EXPR, mode, op0,
5277                             size_int (GET_MODE_BITSIZE (mode) - 1),
5278                             subtarget, normalizep != -1);
5279
5280       if (mode != target_mode)
5281         op0 = convert_modes (target_mode, mode, op0, 0);
5282
5283       return op0;
5284     }
5285
5286   icode = setcc_gen_code[(int) code];
5287
5288   if (icode != CODE_FOR_nothing)
5289     {
5290       insn_operand_predicate_fn pred;
5291
5292       /* We think we may be able to do this with a scc insn.  Emit the
5293          comparison and then the scc insn.  */
5294
5295       do_pending_stack_adjust ();
5296       last = get_last_insn ();
5297
5298       comparison
5299         = compare_from_rtx (op0, op1, code, unsignedp, mode, NULL_RTX);
5300       if (CONSTANT_P (comparison))
5301         {
5302           switch (GET_CODE (comparison))
5303             {
5304             case CONST_INT:
5305               if (comparison == const0_rtx)
5306                 return const0_rtx;
5307               break;
5308               
5309 #ifdef FLOAT_STORE_FLAG_VALUE
5310             case CONST_DOUBLE:
5311               if (comparison == CONST0_RTX (GET_MODE (comparison)))
5312                 return const0_rtx;
5313               break;
5314 #endif
5315             default:
5316               gcc_unreachable ();
5317             }
5318           
5319           if (normalizep == 1)
5320             return const1_rtx;
5321           if (normalizep == -1)
5322             return constm1_rtx;
5323           return const_true_rtx;
5324         }
5325
5326       /* The code of COMPARISON may not match CODE if compare_from_rtx
5327          decided to swap its operands and reverse the original code.
5328
5329          We know that compare_from_rtx returns either a CONST_INT or
5330          a new comparison code, so it is safe to just extract the
5331          code from COMPARISON.  */
5332       code = GET_CODE (comparison);
5333
5334       /* Get a reference to the target in the proper mode for this insn.  */
5335       compare_mode = insn_data[(int) icode].operand[0].mode;
5336       subtarget = target;
5337       pred = insn_data[(int) icode].operand[0].predicate;
5338       if (optimize || ! (*pred) (subtarget, compare_mode))
5339         subtarget = gen_reg_rtx (compare_mode);
5340
5341       pattern = GEN_FCN (icode) (subtarget);
5342       if (pattern)
5343         {
5344           emit_insn (pattern);
5345           return emit_store_flag_1 (target, subtarget, compare_mode,
5346                                     normalizep);
5347         }
5348     }
5349   else
5350     {
5351       /* We don't have an scc insn, so try a cstore insn.  */
5352
5353       for (compare_mode = mode; compare_mode != VOIDmode;
5354            compare_mode = GET_MODE_WIDER_MODE (compare_mode))
5355         {
5356           icode = optab_handler (cstore_optab, compare_mode)->insn_code;
5357           if (icode != CODE_FOR_nothing)
5358             break;
5359         }
5360
5361       if (icode != CODE_FOR_nothing)
5362         {
5363           enum machine_mode result_mode
5364             = insn_data[(int) icode].operand[0].mode;
5365           rtx cstore_op0 = op0;
5366           rtx cstore_op1 = op1;
5367
5368           do_pending_stack_adjust ();
5369           last = get_last_insn ();
5370
5371           if (compare_mode != mode)
5372             {
5373               cstore_op0 = convert_modes (compare_mode, mode, cstore_op0,
5374                                           unsignedp);
5375               cstore_op1 = convert_modes (compare_mode, mode, cstore_op1,
5376                                           unsignedp);
5377             }
5378           
5379           if (!insn_data[(int) icode].operand[2].predicate (cstore_op0,
5380                                                             compare_mode))
5381             cstore_op0 = copy_to_mode_reg (compare_mode, cstore_op0);
5382
5383           if (!insn_data[(int) icode].operand[3].predicate (cstore_op1,
5384                                                             compare_mode))
5385             cstore_op1 = copy_to_mode_reg (compare_mode, cstore_op1);
5386
5387           comparison = gen_rtx_fmt_ee (code, result_mode, cstore_op0,
5388                                        cstore_op1);
5389           subtarget = target;
5390
5391           if (optimize || !(insn_data[(int) icode].operand[0].predicate
5392                             (subtarget, result_mode)))
5393             subtarget = gen_reg_rtx (result_mode);
5394
5395           pattern = GEN_FCN (icode) (subtarget, comparison, cstore_op0,
5396                                      cstore_op1);
5397
5398           if (pattern)
5399             {
5400               emit_insn (pattern);
5401               return emit_store_flag_1 (target, subtarget, result_mode,
5402                                         normalizep);
5403             }
5404         }
5405     }
5406
5407   delete_insns_since (last);
5408
5409   /* If optimizing, use different pseudo registers for each insn, instead
5410      of reusing the same pseudo.  This leads to better CSE, but slows
5411      down the compiler, since there are more pseudos */
5412   subtarget = (!optimize
5413                && (target_mode == mode)) ? target : NULL_RTX;
5414
5415   /* If we reached here, we can't do this with a scc insn.  However, there
5416      are some comparisons that can be done directly.  For example, if
5417      this is an equality comparison of integers, we can try to exclusive-or
5418      (or subtract) the two operands and use a recursive call to try the
5419      comparison with zero.  Don't do any of these cases if branches are
5420      very cheap.  */
5421
5422   if (BRANCH_COST (optimize_insn_for_speed_p (),
5423                    false) > 0
5424       && GET_MODE_CLASS (mode) == MODE_INT && (code == EQ || code == NE)
5425       && op1 != const0_rtx)
5426     {
5427       tem = expand_binop (mode, xor_optab, op0, op1, subtarget, 1,
5428                           OPTAB_WIDEN);
5429
5430       if (tem == 0)
5431         tem = expand_binop (mode, sub_optab, op0, op1, subtarget, 1,
5432                             OPTAB_WIDEN);
5433       if (tem != 0)
5434         tem = emit_store_flag (target, code, tem, const0_rtx,
5435                                mode, unsignedp, normalizep);
5436       if (tem == 0)
5437         delete_insns_since (last);
5438       return tem;
5439     }
5440
5441   /* Some other cases we can do are EQ, NE, LE, and GT comparisons with
5442      the constant zero.  Reject all other comparisons at this point.  Only
5443      do LE and GT if branches are expensive since they are expensive on
5444      2-operand machines.  */
5445
5446   if (BRANCH_COST (optimize_insn_for_speed_p (),
5447                    false) == 0
5448       || GET_MODE_CLASS (mode) != MODE_INT || op1 != const0_rtx
5449       || (code != EQ && code != NE
5450           && (BRANCH_COST (optimize_insn_for_speed_p (),
5451                            false) <= 1 || (code != LE && code != GT))))
5452     return 0;
5453
5454   /* See what we need to return.  We can only return a 1, -1, or the
5455      sign bit.  */
5456
5457   if (normalizep == 0)
5458     {
5459       if (STORE_FLAG_VALUE == 1 || STORE_FLAG_VALUE == -1)
5460         normalizep = STORE_FLAG_VALUE;
5461
5462       else if (GET_MODE_BITSIZE (mode) <= HOST_BITS_PER_WIDE_INT
5463                && ((STORE_FLAG_VALUE & GET_MODE_MASK (mode))
5464                    == (unsigned HOST_WIDE_INT) 1 << (GET_MODE_BITSIZE (mode) - 1)))
5465         ;
5466       else
5467         return 0;
5468     }
5469
5470   /* Try to put the result of the comparison in the sign bit.  Assume we can't
5471      do the necessary operation below.  */
5472
5473   tem = 0;
5474
5475   /* To see if A <= 0, compute (A | (A - 1)).  A <= 0 iff that result has
5476      the sign bit set.  */
5477
5478   if (code == LE)
5479     {
5480       /* This is destructive, so SUBTARGET can't be OP0.  */
5481       if (rtx_equal_p (subtarget, op0))
5482         subtarget = 0;
5483
5484       tem = expand_binop (mode, sub_optab, op0, const1_rtx, subtarget, 0,
5485                           OPTAB_WIDEN);
5486       if (tem)
5487         tem = expand_binop (mode, ior_optab, op0, tem, subtarget, 0,
5488                             OPTAB_WIDEN);
5489     }
5490
5491   /* To see if A > 0, compute (((signed) A) << BITS) - A, where BITS is the
5492      number of bits in the mode of OP0, minus one.  */
5493
5494   if (code == GT)
5495     {
5496       if (rtx_equal_p (subtarget, op0))
5497         subtarget = 0;
5498
5499       tem = expand_shift (RSHIFT_EXPR, mode, op0,
5500                           size_int (GET_MODE_BITSIZE (mode) - 1),
5501                           subtarget, 0);
5502       tem = expand_binop (mode, sub_optab, tem, op0, subtarget, 0,
5503                           OPTAB_WIDEN);
5504     }
5505
5506   if (code == EQ || code == NE)
5507     {
5508       /* For EQ or NE, one way to do the comparison is to apply an operation
5509          that converts the operand into a positive number if it is nonzero
5510          or zero if it was originally zero.  Then, for EQ, we subtract 1 and
5511          for NE we negate.  This puts the result in the sign bit.  Then we
5512          normalize with a shift, if needed.
5513
5514          Two operations that can do the above actions are ABS and FFS, so try
5515          them.  If that doesn't work, and MODE is smaller than a full word,
5516          we can use zero-extension to the wider mode (an unsigned conversion)
5517          as the operation.  */
5518
5519       /* Note that ABS doesn't yield a positive number for INT_MIN, but
5520          that is compensated by the subsequent overflow when subtracting
5521          one / negating.  */
5522
5523       if (optab_handler (abs_optab, mode)->insn_code != CODE_FOR_nothing)
5524         tem = expand_unop (mode, abs_optab, op0, subtarget, 1);
5525       else if (optab_handler (ffs_optab, mode)->insn_code != CODE_FOR_nothing)
5526         tem = expand_unop (mode, ffs_optab, op0, subtarget, 1);
5527       else if (GET_MODE_SIZE (mode) < UNITS_PER_WORD)
5528         {
5529           tem = convert_modes (word_mode, mode, op0, 1);
5530           mode = word_mode;
5531         }
5532
5533       if (tem != 0)
5534         {
5535           if (code == EQ)
5536             tem = expand_binop (mode, sub_optab, tem, const1_rtx, subtarget,
5537                                 0, OPTAB_WIDEN);
5538           else
5539             tem = expand_unop (mode, neg_optab, tem, subtarget, 0);
5540         }
5541
5542       /* If we couldn't do it that way, for NE we can "or" the two's complement
5543          of the value with itself.  For EQ, we take the one's complement of
5544          that "or", which is an extra insn, so we only handle EQ if branches
5545          are expensive.  */
5546
5547       if (tem == 0
5548           && (code == NE
5549               || BRANCH_COST (optimize_insn_for_speed_p (),
5550                               false) > 1))
5551         {
5552           if (rtx_equal_p (subtarget, op0))
5553             subtarget = 0;
5554
5555           tem = expand_unop (mode, neg_optab, op0, subtarget, 0);
5556           tem = expand_binop (mode, ior_optab, tem, op0, subtarget, 0,
5557                               OPTAB_WIDEN);
5558
5559           if (tem && code == EQ)
5560             tem = expand_unop (mode, one_cmpl_optab, tem, subtarget, 0);
5561         }
5562     }
5563
5564   if (tem && normalizep)
5565     tem = expand_shift (RSHIFT_EXPR, mode, tem,
5566                         size_int (GET_MODE_BITSIZE (mode) - 1),
5567                         subtarget, normalizep == 1);
5568
5569   if (tem)
5570     {
5571       if (GET_MODE (tem) != target_mode)
5572         {
5573           convert_move (target, tem, 0);
5574           tem = target;
5575         }
5576       else if (!subtarget)
5577         {
5578           emit_move_insn (target, tem);
5579           tem = target;
5580         }
5581     }
5582   else
5583     delete_insns_since (last);
5584
5585   return tem;
5586 }
5587
5588 /* Like emit_store_flag, but always succeeds.  */
5589
5590 rtx
5591 emit_store_flag_force (rtx target, enum rtx_code code, rtx op0, rtx op1,
5592                        enum machine_mode mode, int unsignedp, int normalizep)
5593 {
5594   rtx tem, label;
5595
5596   /* First see if emit_store_flag can do the job.  */
5597   tem = emit_store_flag (target, code, op0, op1, mode, unsignedp, normalizep);
5598   if (tem != 0)
5599     return tem;
5600
5601   if (normalizep == 0)
5602     normalizep = 1;
5603
5604   /* If this failed, we have to do this with set/compare/jump/set code.  */
5605
5606   if (!REG_P (target)
5607       || reg_mentioned_p (target, op0) || reg_mentioned_p (target, op1))
5608     target = gen_reg_rtx (GET_MODE (target));
5609
5610   emit_move_insn (target, const1_rtx);
5611   label = gen_label_rtx ();
5612   do_compare_rtx_and_jump (op0, op1, code, unsignedp, mode, NULL_RTX,
5613                            NULL_RTX, label, -1);
5614
5615   emit_move_insn (target, const0_rtx);
5616   emit_label (label);
5617
5618   return target;
5619 }
5620 \f
5621 /* Perform possibly multi-word comparison and conditional jump to LABEL
5622    if ARG1 OP ARG2 true where ARG1 and ARG2 are of mode MODE.  This is
5623    now a thin wrapper around do_compare_rtx_and_jump.  */
5624
5625 static void
5626 do_cmp_and_jump (rtx arg1, rtx arg2, enum rtx_code op, enum machine_mode mode,
5627                  rtx label)
5628 {
5629   int unsignedp = (op == LTU || op == LEU || op == GTU || op == GEU);
5630   do_compare_rtx_and_jump (arg1, arg2, op, unsignedp, mode,
5631                            NULL_RTX, NULL_RTX, label, -1);
5632 }