OSDN Git Service

2009-04-09 Paolo Bonzini <bonzini@gnu.org>
[pf3gnuchains/gcc-fork.git] / 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
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           accum = expand_shift (LSHIFT_EXPR, mode, accum,
2935                                 build_int_cst (NULL_TREE, log),
2936                                 NULL_RTX, 0);
2937           val_so_far <<= log;
2938           break;
2939
2940         case alg_add_t_m2:
2941           tem = expand_shift (LSHIFT_EXPR, mode, op0,
2942                               build_int_cst (NULL_TREE, log),
2943                               NULL_RTX, 0);
2944           accum = force_operand (gen_rtx_PLUS (mode, accum, tem),
2945                                  add_target ? add_target : accum_target);
2946           val_so_far += (HOST_WIDE_INT) 1 << log;
2947           break;
2948
2949         case alg_sub_t_m2:
2950           tem = expand_shift (LSHIFT_EXPR, mode, op0,
2951                               build_int_cst (NULL_TREE, log),
2952                               NULL_RTX, 0);
2953           accum = force_operand (gen_rtx_MINUS (mode, accum, tem),
2954                                  add_target ? add_target : accum_target);
2955           val_so_far -= (HOST_WIDE_INT) 1 << log;
2956           break;
2957
2958         case alg_add_t2_m:
2959           accum = expand_shift (LSHIFT_EXPR, mode, accum,
2960                                 build_int_cst (NULL_TREE, log),
2961                                 shift_subtarget,
2962                                 0);
2963           accum = force_operand (gen_rtx_PLUS (mode, accum, op0),
2964                                  add_target ? add_target : accum_target);
2965           val_so_far = (val_so_far << log) + 1;
2966           break;
2967
2968         case alg_sub_t2_m:
2969           accum = expand_shift (LSHIFT_EXPR, mode, accum,
2970                                 build_int_cst (NULL_TREE, log),
2971                                 shift_subtarget, 0);
2972           accum = force_operand (gen_rtx_MINUS (mode, accum, op0),
2973                                  add_target ? add_target : accum_target);
2974           val_so_far = (val_so_far << log) - 1;
2975           break;
2976
2977         case alg_add_factor:
2978           tem = expand_shift (LSHIFT_EXPR, mode, accum,
2979                               build_int_cst (NULL_TREE, log),
2980                               NULL_RTX, 0);
2981           accum = force_operand (gen_rtx_PLUS (mode, accum, tem),
2982                                  add_target ? add_target : accum_target);
2983           val_so_far += val_so_far << log;
2984           break;
2985
2986         case alg_sub_factor:
2987           tem = expand_shift (LSHIFT_EXPR, mode, accum,
2988                               build_int_cst (NULL_TREE, log),
2989                               NULL_RTX, 0);
2990           accum = force_operand (gen_rtx_MINUS (mode, tem, accum),
2991                                  (add_target
2992                                   ? add_target : (optimize ? 0 : tem)));
2993           val_so_far = (val_so_far << log) - val_so_far;
2994           break;
2995
2996         default:
2997           gcc_unreachable ();
2998         }
2999
3000       /* Write a REG_EQUAL note on the last insn so that we can cse
3001          multiplication sequences.  Note that if ACCUM is a SUBREG,
3002          we've set the inner register and must properly indicate
3003          that.  */
3004
3005       tem = op0, nmode = mode;
3006       if (GET_CODE (accum) == SUBREG)
3007         {
3008           nmode = GET_MODE (SUBREG_REG (accum));
3009           tem = gen_lowpart (nmode, op0);
3010         }
3011
3012       insn = get_last_insn ();
3013       set_unique_reg_note (insn, REG_EQUAL,
3014                            gen_rtx_MULT (nmode, tem,
3015                                          GEN_INT (val_so_far)));
3016     }
3017
3018   if (variant == negate_variant)
3019     {
3020       val_so_far = -val_so_far;
3021       accum = expand_unop (mode, neg_optab, accum, target, 0);
3022     }
3023   else if (variant == add_variant)
3024     {
3025       val_so_far = val_so_far + 1;
3026       accum = force_operand (gen_rtx_PLUS (mode, accum, op0), target);
3027     }
3028
3029   /* Compare only the bits of val and val_so_far that are significant
3030      in the result mode, to avoid sign-/zero-extension confusion.  */
3031   val &= GET_MODE_MASK (mode);
3032   val_so_far &= GET_MODE_MASK (mode);
3033   gcc_assert (val == val_so_far);
3034
3035   return accum;
3036 }
3037
3038 /* Perform a multiplication and return an rtx for the result.
3039    MODE is mode of value; OP0 and OP1 are what to multiply (rtx's);
3040    TARGET is a suggestion for where to store the result (an rtx).
3041
3042    We check specially for a constant integer as OP1.
3043    If you want this check for OP0 as well, then before calling
3044    you should swap the two operands if OP0 would be constant.  */
3045
3046 rtx
3047 expand_mult (enum machine_mode mode, rtx op0, rtx op1, rtx target,
3048              int unsignedp)
3049 {
3050   enum mult_variant variant;
3051   struct algorithm algorithm;
3052   int max_cost;
3053   bool speed = optimize_insn_for_speed_p ();
3054
3055   /* Handling const0_rtx here allows us to use zero as a rogue value for
3056      coeff below.  */
3057   if (op1 == const0_rtx)
3058     return const0_rtx;
3059   if (op1 == const1_rtx)
3060     return op0;
3061   if (op1 == constm1_rtx)
3062     return expand_unop (mode,
3063                         GET_MODE_CLASS (mode) == MODE_INT
3064                         && !unsignedp && flag_trapv
3065                         ? negv_optab : neg_optab,
3066                         op0, target, 0);
3067
3068   /* These are the operations that are potentially turned into a sequence
3069      of shifts and additions.  */
3070   if (SCALAR_INT_MODE_P (mode)
3071       && (unsignedp || !flag_trapv))
3072     {
3073       HOST_WIDE_INT coeff = 0;
3074       rtx fake_reg = gen_raw_REG (mode, LAST_VIRTUAL_REGISTER + 1);
3075
3076       /* synth_mult does an `unsigned int' multiply.  As long as the mode is
3077          less than or equal in size to `unsigned int' this doesn't matter.
3078          If the mode is larger than `unsigned int', then synth_mult works
3079          only if the constant value exactly fits in an `unsigned int' without
3080          any truncation.  This means that multiplying by negative values does
3081          not work; results are off by 2^32 on a 32 bit machine.  */
3082
3083       if (GET_CODE (op1) == CONST_INT)
3084         {
3085           /* Attempt to handle multiplication of DImode values by negative
3086              coefficients, by performing the multiplication by a positive
3087              multiplier and then inverting the result.  */
3088           if (INTVAL (op1) < 0
3089               && GET_MODE_BITSIZE (mode) > HOST_BITS_PER_WIDE_INT)
3090             {
3091               /* Its safe to use -INTVAL (op1) even for INT_MIN, as the
3092                  result is interpreted as an unsigned coefficient.
3093                  Exclude cost of op0 from max_cost to match the cost
3094                  calculation of the synth_mult.  */
3095               max_cost = rtx_cost (gen_rtx_MULT (mode, fake_reg, op1), SET, speed)
3096                          - neg_cost[speed][mode];
3097               if (max_cost > 0
3098                   && choose_mult_variant (mode, -INTVAL (op1), &algorithm,
3099                                           &variant, max_cost))
3100                 {
3101                   rtx temp = expand_mult_const (mode, op0, -INTVAL (op1),
3102                                                 NULL_RTX, &algorithm,
3103                                                 variant);
3104                   return expand_unop (mode, neg_optab, temp, target, 0);
3105                 }
3106             }
3107           else coeff = INTVAL (op1);
3108         }
3109       else if (GET_CODE (op1) == CONST_DOUBLE)
3110         {
3111           /* If we are multiplying in DImode, it may still be a win
3112              to try to work with shifts and adds.  */
3113           if (CONST_DOUBLE_HIGH (op1) == 0
3114               && CONST_DOUBLE_LOW (op1) > 0)
3115             coeff = CONST_DOUBLE_LOW (op1);
3116           else if (CONST_DOUBLE_LOW (op1) == 0
3117                    && EXACT_POWER_OF_2_OR_ZERO_P (CONST_DOUBLE_HIGH (op1)))
3118             {
3119               int shift = floor_log2 (CONST_DOUBLE_HIGH (op1))
3120                           + HOST_BITS_PER_WIDE_INT;
3121               return expand_shift (LSHIFT_EXPR, mode, op0,
3122                                    build_int_cst (NULL_TREE, shift),
3123                                    target, unsignedp);
3124             }
3125         }
3126         
3127       /* We used to test optimize here, on the grounds that it's better to
3128          produce a smaller program when -O is not used.  But this causes
3129          such a terrible slowdown sometimes that it seems better to always
3130          use synth_mult.  */
3131       if (coeff != 0)
3132         {
3133           /* Special case powers of two.  */
3134           if (EXACT_POWER_OF_2_OR_ZERO_P (coeff))
3135             return expand_shift (LSHIFT_EXPR, mode, op0,
3136                                  build_int_cst (NULL_TREE, floor_log2 (coeff)),
3137                                  target, unsignedp);
3138
3139           /* Exclude cost of op0 from max_cost to match the cost
3140              calculation of the synth_mult.  */
3141           max_cost = rtx_cost (gen_rtx_MULT (mode, fake_reg, op1), SET, speed);
3142           if (choose_mult_variant (mode, coeff, &algorithm, &variant,
3143                                    max_cost))
3144             return expand_mult_const (mode, op0, coeff, target,
3145                                       &algorithm, variant);
3146         }
3147     }
3148
3149   if (GET_CODE (op0) == CONST_DOUBLE)
3150     {
3151       rtx temp = op0;
3152       op0 = op1;
3153       op1 = temp;
3154     }
3155
3156   /* Expand x*2.0 as x+x.  */
3157   if (GET_CODE (op1) == CONST_DOUBLE
3158       && SCALAR_FLOAT_MODE_P (mode))
3159     {
3160       REAL_VALUE_TYPE d;
3161       REAL_VALUE_FROM_CONST_DOUBLE (d, op1);
3162
3163       if (REAL_VALUES_EQUAL (d, dconst2))
3164         {
3165           op0 = force_reg (GET_MODE (op0), op0);
3166           return expand_binop (mode, add_optab, op0, op0,
3167                                target, unsignedp, OPTAB_LIB_WIDEN);
3168         }
3169     }
3170
3171   /* This used to use umul_optab if unsigned, but for non-widening multiply
3172      there is no difference between signed and unsigned.  */
3173   op0 = expand_binop (mode,
3174                       ! unsignedp
3175                       && flag_trapv && (GET_MODE_CLASS(mode) == MODE_INT)
3176                       ? smulv_optab : smul_optab,
3177                       op0, op1, target, unsignedp, OPTAB_LIB_WIDEN);
3178   gcc_assert (op0);
3179   return op0;
3180 }
3181 \f
3182 /* Return the smallest n such that 2**n >= X.  */
3183
3184 int
3185 ceil_log2 (unsigned HOST_WIDE_INT x)
3186 {
3187   return floor_log2 (x - 1) + 1;
3188 }
3189
3190 /* Choose a minimal N + 1 bit approximation to 1/D that can be used to
3191    replace division by D, and put the least significant N bits of the result
3192    in *MULTIPLIER_PTR and return the most significant bit.
3193
3194    The width of operations is N (should be <= HOST_BITS_PER_WIDE_INT), the
3195    needed precision is in PRECISION (should be <= N).
3196
3197    PRECISION should be as small as possible so this function can choose
3198    multiplier more freely.
3199
3200    The rounded-up logarithm of D is placed in *lgup_ptr.  A shift count that
3201    is to be used for a final right shift is placed in *POST_SHIFT_PTR.
3202
3203    Using this function, x/D will be equal to (x * m) >> (*POST_SHIFT_PTR),
3204    where m is the full HOST_BITS_PER_WIDE_INT + 1 bit multiplier.  */
3205
3206 static
3207 unsigned HOST_WIDE_INT
3208 choose_multiplier (unsigned HOST_WIDE_INT d, int n, int precision,
3209                    rtx *multiplier_ptr, int *post_shift_ptr, int *lgup_ptr)
3210 {
3211   HOST_WIDE_INT mhigh_hi, mlow_hi;
3212   unsigned HOST_WIDE_INT mhigh_lo, mlow_lo;
3213   int lgup, post_shift;
3214   int pow, pow2;
3215   unsigned HOST_WIDE_INT nl, dummy1;
3216   HOST_WIDE_INT nh, dummy2;
3217
3218   /* lgup = ceil(log2(divisor)); */
3219   lgup = ceil_log2 (d);
3220
3221   gcc_assert (lgup <= n);
3222
3223   pow = n + lgup;
3224   pow2 = n + lgup - precision;
3225
3226   /* We could handle this with some effort, but this case is much
3227      better handled directly with a scc insn, so rely on caller using
3228      that.  */
3229   gcc_assert (pow != 2 * HOST_BITS_PER_WIDE_INT);
3230
3231   /* mlow = 2^(N + lgup)/d */
3232  if (pow >= HOST_BITS_PER_WIDE_INT)
3233     {
3234       nh = (HOST_WIDE_INT) 1 << (pow - HOST_BITS_PER_WIDE_INT);
3235       nl = 0;
3236     }
3237   else
3238     {
3239       nh = 0;
3240       nl = (unsigned HOST_WIDE_INT) 1 << pow;
3241     }
3242   div_and_round_double (TRUNC_DIV_EXPR, 1, nl, nh, d, (HOST_WIDE_INT) 0,
3243                         &mlow_lo, &mlow_hi, &dummy1, &dummy2);
3244
3245   /* mhigh = (2^(N + lgup) + 2^N + lgup - precision)/d */
3246   if (pow2 >= HOST_BITS_PER_WIDE_INT)
3247     nh |= (HOST_WIDE_INT) 1 << (pow2 - HOST_BITS_PER_WIDE_INT);
3248   else
3249     nl |= (unsigned HOST_WIDE_INT) 1 << pow2;
3250   div_and_round_double (TRUNC_DIV_EXPR, 1, nl, nh, d, (HOST_WIDE_INT) 0,
3251                         &mhigh_lo, &mhigh_hi, &dummy1, &dummy2);
3252
3253   gcc_assert (!mhigh_hi || nh - d < d);
3254   gcc_assert (mhigh_hi <= 1 && mlow_hi <= 1);
3255   /* Assert that mlow < mhigh.  */
3256   gcc_assert (mlow_hi < mhigh_hi
3257               || (mlow_hi == mhigh_hi && mlow_lo < mhigh_lo));
3258
3259   /* If precision == N, then mlow, mhigh exceed 2^N
3260      (but they do not exceed 2^(N+1)).  */
3261
3262   /* Reduce to lowest terms.  */
3263   for (post_shift = lgup; post_shift > 0; post_shift--)
3264     {
3265       unsigned HOST_WIDE_INT ml_lo = (mlow_hi << (HOST_BITS_PER_WIDE_INT - 1)) | (mlow_lo >> 1);
3266       unsigned HOST_WIDE_INT mh_lo = (mhigh_hi << (HOST_BITS_PER_WIDE_INT - 1)) | (mhigh_lo >> 1);
3267       if (ml_lo >= mh_lo)
3268         break;
3269
3270       mlow_hi = 0;
3271       mlow_lo = ml_lo;
3272       mhigh_hi = 0;
3273       mhigh_lo = mh_lo;
3274     }
3275
3276   *post_shift_ptr = post_shift;
3277   *lgup_ptr = lgup;
3278   if (n < HOST_BITS_PER_WIDE_INT)
3279     {
3280       unsigned HOST_WIDE_INT mask = ((unsigned HOST_WIDE_INT) 1 << n) - 1;
3281       *multiplier_ptr = GEN_INT (mhigh_lo & mask);
3282       return mhigh_lo >= mask;
3283     }
3284   else
3285     {
3286       *multiplier_ptr = GEN_INT (mhigh_lo);
3287       return mhigh_hi;
3288     }
3289 }
3290
3291 /* Compute the inverse of X mod 2**n, i.e., find Y such that X * Y is
3292    congruent to 1 (mod 2**N).  */
3293
3294 static unsigned HOST_WIDE_INT
3295 invert_mod2n (unsigned HOST_WIDE_INT x, int n)
3296 {
3297   /* Solve x*y == 1 (mod 2^n), where x is odd.  Return y.  */
3298
3299   /* The algorithm notes that the choice y = x satisfies
3300      x*y == 1 mod 2^3, since x is assumed odd.
3301      Each iteration doubles the number of bits of significance in y.  */
3302
3303   unsigned HOST_WIDE_INT mask;
3304   unsigned HOST_WIDE_INT y = x;
3305   int nbit = 3;
3306
3307   mask = (n == HOST_BITS_PER_WIDE_INT
3308           ? ~(unsigned HOST_WIDE_INT) 0
3309           : ((unsigned HOST_WIDE_INT) 1 << n) - 1);
3310
3311   while (nbit < n)
3312     {
3313       y = y * (2 - x*y) & mask;         /* Modulo 2^N */
3314       nbit *= 2;
3315     }
3316   return y;
3317 }
3318
3319 /* Emit code to adjust ADJ_OPERAND after multiplication of wrong signedness
3320    flavor of OP0 and OP1.  ADJ_OPERAND is already the high half of the
3321    product OP0 x OP1.  If UNSIGNEDP is nonzero, adjust the signed product
3322    to become unsigned, if UNSIGNEDP is zero, adjust the unsigned product to
3323    become signed.
3324
3325    The result is put in TARGET if that is convenient.
3326
3327    MODE is the mode of operation.  */
3328
3329 rtx
3330 expand_mult_highpart_adjust (enum machine_mode mode, rtx adj_operand, rtx op0,
3331                              rtx op1, rtx target, int unsignedp)
3332 {
3333   rtx tem;
3334   enum rtx_code adj_code = unsignedp ? PLUS : MINUS;
3335
3336   tem = expand_shift (RSHIFT_EXPR, mode, op0,
3337                       build_int_cst (NULL_TREE, GET_MODE_BITSIZE (mode) - 1),
3338                       NULL_RTX, 0);
3339   tem = expand_and (mode, tem, op1, NULL_RTX);
3340   adj_operand
3341     = force_operand (gen_rtx_fmt_ee (adj_code, mode, adj_operand, tem),
3342                      adj_operand);
3343
3344   tem = expand_shift (RSHIFT_EXPR, mode, op1,
3345                       build_int_cst (NULL_TREE, GET_MODE_BITSIZE (mode) - 1),
3346                       NULL_RTX, 0);
3347   tem = expand_and (mode, tem, op0, NULL_RTX);
3348   target = force_operand (gen_rtx_fmt_ee (adj_code, mode, adj_operand, tem),
3349                           target);
3350
3351   return target;
3352 }
3353
3354 /* Subroutine of expand_mult_highpart.  Return the MODE high part of OP.  */
3355
3356 static rtx
3357 extract_high_half (enum machine_mode mode, rtx op)
3358 {
3359   enum machine_mode wider_mode;
3360
3361   if (mode == word_mode)
3362     return gen_highpart (mode, op);
3363
3364   gcc_assert (!SCALAR_FLOAT_MODE_P (mode));
3365
3366   wider_mode = GET_MODE_WIDER_MODE (mode);
3367   op = expand_shift (RSHIFT_EXPR, wider_mode, op,
3368                      build_int_cst (NULL_TREE, GET_MODE_BITSIZE (mode)), 0, 1);
3369   return convert_modes (mode, wider_mode, op, 0);
3370 }
3371
3372 /* Like expand_mult_highpart, but only consider using a multiplication
3373    optab.  OP1 is an rtx for the constant operand.  */
3374
3375 static rtx
3376 expand_mult_highpart_optab (enum machine_mode mode, rtx op0, rtx op1,
3377                             rtx target, int unsignedp, int max_cost)
3378 {
3379   rtx narrow_op1 = gen_int_mode (INTVAL (op1), mode);
3380   enum machine_mode wider_mode;
3381   optab moptab;
3382   rtx tem;
3383   int size;
3384   bool speed = optimize_insn_for_speed_p ();
3385
3386   gcc_assert (!SCALAR_FLOAT_MODE_P (mode));
3387
3388   wider_mode = GET_MODE_WIDER_MODE (mode);
3389   size = GET_MODE_BITSIZE (mode);
3390
3391   /* Firstly, try using a multiplication insn that only generates the needed
3392      high part of the product, and in the sign flavor of unsignedp.  */
3393   if (mul_highpart_cost[speed][mode] < max_cost)
3394     {
3395       moptab = unsignedp ? umul_highpart_optab : smul_highpart_optab;
3396       tem = expand_binop (mode, moptab, op0, narrow_op1, target,
3397                           unsignedp, OPTAB_DIRECT);
3398       if (tem)
3399         return tem;
3400     }
3401
3402   /* Secondly, same as above, but use sign flavor opposite of unsignedp.
3403      Need to adjust the result after the multiplication.  */
3404   if (size - 1 < BITS_PER_WORD
3405       && (mul_highpart_cost[speed][mode] + 2 * shift_cost[speed][mode][size-1]
3406           + 4 * add_cost[speed][mode] < max_cost))
3407     {
3408       moptab = unsignedp ? smul_highpart_optab : umul_highpart_optab;
3409       tem = expand_binop (mode, moptab, op0, narrow_op1, target,
3410                           unsignedp, OPTAB_DIRECT);
3411       if (tem)
3412         /* We used the wrong signedness.  Adjust the result.  */
3413         return expand_mult_highpart_adjust (mode, tem, op0, narrow_op1,
3414                                             tem, unsignedp);
3415     }
3416
3417   /* Try widening multiplication.  */
3418   moptab = unsignedp ? umul_widen_optab : smul_widen_optab;
3419   if (optab_handler (moptab, wider_mode)->insn_code != CODE_FOR_nothing
3420       && mul_widen_cost[speed][wider_mode] < max_cost)
3421     {
3422       tem = expand_binop (wider_mode, moptab, op0, narrow_op1, 0,
3423                           unsignedp, OPTAB_WIDEN);
3424       if (tem)
3425         return extract_high_half (mode, tem);
3426     }
3427
3428   /* Try widening the mode and perform a non-widening multiplication.  */
3429   if (optab_handler (smul_optab, wider_mode)->insn_code != CODE_FOR_nothing
3430       && size - 1 < BITS_PER_WORD
3431       && mul_cost[speed][wider_mode] + shift_cost[speed][mode][size-1] < max_cost)
3432     {
3433       rtx insns, wop0, wop1;
3434
3435       /* We need to widen the operands, for example to ensure the
3436          constant multiplier is correctly sign or zero extended.
3437          Use a sequence to clean-up any instructions emitted by
3438          the conversions if things don't work out.  */
3439       start_sequence ();
3440       wop0 = convert_modes (wider_mode, mode, op0, unsignedp);
3441       wop1 = convert_modes (wider_mode, mode, op1, unsignedp);
3442       tem = expand_binop (wider_mode, smul_optab, wop0, wop1, 0,
3443                           unsignedp, OPTAB_WIDEN);
3444       insns = get_insns ();
3445       end_sequence ();
3446
3447       if (tem)
3448         {
3449           emit_insn (insns);
3450           return extract_high_half (mode, tem);
3451         }
3452     }
3453
3454   /* Try widening multiplication of opposite signedness, and adjust.  */
3455   moptab = unsignedp ? smul_widen_optab : umul_widen_optab;
3456   if (optab_handler (moptab, wider_mode)->insn_code != CODE_FOR_nothing
3457       && size - 1 < BITS_PER_WORD
3458       && (mul_widen_cost[speed][wider_mode] + 2 * shift_cost[speed][mode][size-1]
3459           + 4 * add_cost[speed][mode] < max_cost))
3460     {
3461       tem = expand_binop (wider_mode, moptab, op0, narrow_op1,
3462                           NULL_RTX, ! unsignedp, OPTAB_WIDEN);
3463       if (tem != 0)
3464         {
3465           tem = extract_high_half (mode, tem);
3466           /* We used the wrong signedness.  Adjust the result.  */
3467           return expand_mult_highpart_adjust (mode, tem, op0, narrow_op1,
3468                                               target, unsignedp);
3469         }
3470     }
3471
3472   return 0;
3473 }
3474
3475 /* Emit code to multiply OP0 and OP1 (where OP1 is an integer constant),
3476    putting the high half of the result in TARGET if that is convenient,
3477    and return where the result is.  If the operation can not be performed,
3478    0 is returned.
3479
3480    MODE is the mode of operation and result.
3481
3482    UNSIGNEDP nonzero means unsigned multiply.
3483
3484    MAX_COST is the total allowed cost for the expanded RTL.  */
3485
3486 static rtx
3487 expand_mult_highpart (enum machine_mode mode, rtx op0, rtx op1,
3488                       rtx target, int unsignedp, int max_cost)
3489 {
3490   enum machine_mode wider_mode = GET_MODE_WIDER_MODE (mode);
3491   unsigned HOST_WIDE_INT cnst1;
3492   int extra_cost;
3493   bool sign_adjust = false;
3494   enum mult_variant variant;
3495   struct algorithm alg;
3496   rtx tem;
3497   bool speed = optimize_insn_for_speed_p ();
3498
3499   gcc_assert (!SCALAR_FLOAT_MODE_P (mode));
3500   /* We can't support modes wider than HOST_BITS_PER_INT.  */
3501   gcc_assert (GET_MODE_BITSIZE (mode) <= HOST_BITS_PER_WIDE_INT);
3502
3503   cnst1 = INTVAL (op1) & GET_MODE_MASK (mode);
3504
3505   /* We can't optimize modes wider than BITS_PER_WORD. 
3506      ??? We might be able to perform double-word arithmetic if 
3507      mode == word_mode, however all the cost calculations in
3508      synth_mult etc. assume single-word operations.  */
3509   if (GET_MODE_BITSIZE (wider_mode) > BITS_PER_WORD)
3510     return expand_mult_highpart_optab (mode, op0, op1, target,
3511                                        unsignedp, max_cost);
3512
3513   extra_cost = shift_cost[speed][mode][GET_MODE_BITSIZE (mode) - 1];
3514
3515   /* Check whether we try to multiply by a negative constant.  */
3516   if (!unsignedp && ((cnst1 >> (GET_MODE_BITSIZE (mode) - 1)) & 1))
3517     {
3518       sign_adjust = true;
3519       extra_cost += add_cost[speed][mode];
3520     }
3521
3522   /* See whether shift/add multiplication is cheap enough.  */
3523   if (choose_mult_variant (wider_mode, cnst1, &alg, &variant,
3524                            max_cost - extra_cost))
3525     {
3526       /* See whether the specialized multiplication optabs are
3527          cheaper than the shift/add version.  */
3528       tem = expand_mult_highpart_optab (mode, op0, op1, target, unsignedp,
3529                                         alg.cost.cost + extra_cost);
3530       if (tem)
3531         return tem;
3532
3533       tem = convert_to_mode (wider_mode, op0, unsignedp);
3534       tem = expand_mult_const (wider_mode, tem, cnst1, 0, &alg, variant);
3535       tem = extract_high_half (mode, tem);
3536
3537       /* Adjust result for signedness.  */
3538       if (sign_adjust)
3539         tem = force_operand (gen_rtx_MINUS (mode, tem, op0), tem);
3540
3541       return tem;
3542     }
3543   return expand_mult_highpart_optab (mode, op0, op1, target,
3544                                      unsignedp, max_cost);
3545 }
3546
3547
3548 /* Expand signed modulus of OP0 by a power of two D in mode MODE.  */
3549
3550 static rtx
3551 expand_smod_pow2 (enum machine_mode mode, rtx op0, HOST_WIDE_INT d)
3552 {
3553   unsigned HOST_WIDE_INT masklow, maskhigh;
3554   rtx result, temp, shift, label;
3555   int logd;
3556
3557   logd = floor_log2 (d);
3558   result = gen_reg_rtx (mode);
3559
3560   /* Avoid conditional branches when they're expensive.  */
3561   if (BRANCH_COST (optimize_insn_for_speed_p (), false) >= 2
3562       && optimize_insn_for_speed_p ())
3563     {
3564       rtx signmask = emit_store_flag (result, LT, op0, const0_rtx,
3565                                       mode, 0, -1);
3566       if (signmask)
3567         {
3568           signmask = force_reg (mode, signmask);
3569           masklow = ((HOST_WIDE_INT) 1 << logd) - 1;
3570           shift = GEN_INT (GET_MODE_BITSIZE (mode) - logd);
3571
3572           /* Use the rtx_cost of a LSHIFTRT instruction to determine
3573              which instruction sequence to use.  If logical right shifts
3574              are expensive the use 2 XORs, 2 SUBs and an AND, otherwise
3575              use a LSHIFTRT, 1 ADD, 1 SUB and an AND.  */
3576
3577           temp = gen_rtx_LSHIFTRT (mode, result, shift);
3578           if (optab_handler (lshr_optab, mode)->insn_code == CODE_FOR_nothing
3579               || rtx_cost (temp, SET, optimize_insn_for_speed_p ()) > COSTS_N_INSNS (2))
3580             {
3581               temp = expand_binop (mode, xor_optab, op0, signmask,
3582                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3583               temp = expand_binop (mode, sub_optab, temp, signmask,
3584                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3585               temp = expand_binop (mode, and_optab, temp, GEN_INT (masklow),
3586                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3587               temp = expand_binop (mode, xor_optab, temp, signmask,
3588                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3589               temp = expand_binop (mode, sub_optab, temp, signmask,
3590                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3591             }
3592           else
3593             {
3594               signmask = expand_binop (mode, lshr_optab, signmask, shift,
3595                                        NULL_RTX, 1, OPTAB_LIB_WIDEN);
3596               signmask = force_reg (mode, signmask);
3597
3598               temp = expand_binop (mode, add_optab, op0, signmask,
3599                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3600               temp = expand_binop (mode, and_optab, temp, GEN_INT (masklow),
3601                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3602               temp = expand_binop (mode, sub_optab, temp, signmask,
3603                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
3604             }
3605           return temp;
3606         }
3607     }
3608
3609   /* Mask contains the mode's signbit and the significant bits of the
3610      modulus.  By including the signbit in the operation, many targets
3611      can avoid an explicit compare operation in the following comparison
3612      against zero.  */
3613
3614   masklow = ((HOST_WIDE_INT) 1 << logd) - 1;
3615   if (GET_MODE_BITSIZE (mode) <= HOST_BITS_PER_WIDE_INT)
3616     {
3617       masklow |= (HOST_WIDE_INT) -1 << (GET_MODE_BITSIZE (mode) - 1);
3618       maskhigh = -1;
3619     }
3620   else
3621     maskhigh = (HOST_WIDE_INT) -1
3622                  << (GET_MODE_BITSIZE (mode) - HOST_BITS_PER_WIDE_INT - 1);
3623
3624   temp = expand_binop (mode, and_optab, op0,
3625                        immed_double_const (masklow, maskhigh, mode),
3626                        result, 1, OPTAB_LIB_WIDEN);
3627   if (temp != result)
3628     emit_move_insn (result, temp);
3629
3630   label = gen_label_rtx ();
3631   do_cmp_and_jump (result, const0_rtx, GE, mode, label);
3632
3633   temp = expand_binop (mode, sub_optab, result, const1_rtx, result,
3634                        0, OPTAB_LIB_WIDEN);
3635   masklow = (HOST_WIDE_INT) -1 << logd;
3636   maskhigh = -1;
3637   temp = expand_binop (mode, ior_optab, temp,
3638                        immed_double_const (masklow, maskhigh, mode),
3639                        result, 1, OPTAB_LIB_WIDEN);
3640   temp = expand_binop (mode, add_optab, temp, const1_rtx, result,
3641                        0, OPTAB_LIB_WIDEN);
3642   if (temp != result)
3643     emit_move_insn (result, temp);
3644   emit_label (label);
3645   return result;
3646 }
3647
3648 /* Expand signed division of OP0 by a power of two D in mode MODE.
3649    This routine is only called for positive values of D.  */
3650
3651 static rtx
3652 expand_sdiv_pow2 (enum machine_mode mode, rtx op0, HOST_WIDE_INT d)
3653 {
3654   rtx temp, label;
3655   tree shift;
3656   int logd;
3657
3658   logd = floor_log2 (d);
3659   shift = build_int_cst (NULL_TREE, logd);
3660
3661   if (d == 2
3662       && BRANCH_COST (optimize_insn_for_speed_p (),
3663                       false) >= 1)
3664     {
3665       temp = gen_reg_rtx (mode);
3666       temp = emit_store_flag (temp, LT, op0, const0_rtx, mode, 0, 1);
3667       temp = expand_binop (mode, add_optab, temp, op0, NULL_RTX,
3668                            0, OPTAB_LIB_WIDEN);
3669       return expand_shift (RSHIFT_EXPR, mode, temp, shift, NULL_RTX, 0);
3670     }
3671
3672 #ifdef HAVE_conditional_move
3673   if (BRANCH_COST (optimize_insn_for_speed_p (), false)
3674       >= 2)
3675     {
3676       rtx temp2;
3677
3678       /* ??? emit_conditional_move forces a stack adjustment via
3679          compare_from_rtx so, if the sequence is discarded, it will
3680          be lost.  Do it now instead.  */
3681       do_pending_stack_adjust ();
3682
3683       start_sequence ();
3684       temp2 = copy_to_mode_reg (mode, op0);
3685       temp = expand_binop (mode, add_optab, temp2, GEN_INT (d-1),
3686                            NULL_RTX, 0, OPTAB_LIB_WIDEN);
3687       temp = force_reg (mode, temp);
3688
3689       /* Construct "temp2 = (temp2 < 0) ? temp : temp2".  */
3690       temp2 = emit_conditional_move (temp2, LT, temp2, const0_rtx,
3691                                      mode, temp, temp2, mode, 0);
3692       if (temp2)
3693         {
3694           rtx seq = get_insns ();
3695           end_sequence ();
3696           emit_insn (seq);
3697           return expand_shift (RSHIFT_EXPR, mode, temp2, shift, NULL_RTX, 0);
3698         }
3699       end_sequence ();
3700     }
3701 #endif
3702
3703   if (BRANCH_COST (optimize_insn_for_speed_p (),
3704                    false) >= 2)
3705     {
3706       int ushift = GET_MODE_BITSIZE (mode) - logd;
3707
3708       temp = gen_reg_rtx (mode);
3709       temp = emit_store_flag (temp, LT, op0, const0_rtx, mode, 0, -1);
3710       if (shift_cost[optimize_insn_for_speed_p ()][mode][ushift] > COSTS_N_INSNS (1))
3711         temp = expand_binop (mode, and_optab, temp, GEN_INT (d - 1),
3712                              NULL_RTX, 0, OPTAB_LIB_WIDEN);
3713       else
3714         temp = expand_shift (RSHIFT_EXPR, mode, temp,
3715                              build_int_cst (NULL_TREE, ushift),
3716                              NULL_RTX, 1);
3717       temp = expand_binop (mode, add_optab, temp, op0, NULL_RTX,
3718                            0, OPTAB_LIB_WIDEN);
3719       return expand_shift (RSHIFT_EXPR, mode, temp, shift, NULL_RTX, 0);
3720     }
3721
3722   label = gen_label_rtx ();
3723   temp = copy_to_mode_reg (mode, op0);
3724   do_cmp_and_jump (temp, const0_rtx, GE, mode, label);
3725   expand_inc (temp, GEN_INT (d - 1));
3726   emit_label (label);
3727   return expand_shift (RSHIFT_EXPR, mode, temp, shift, NULL_RTX, 0);
3728 }
3729 \f
3730 /* Emit the code to divide OP0 by OP1, putting the result in TARGET
3731    if that is convenient, and returning where the result is.
3732    You may request either the quotient or the remainder as the result;
3733    specify REM_FLAG nonzero to get the remainder.
3734
3735    CODE is the expression code for which kind of division this is;
3736    it controls how rounding is done.  MODE is the machine mode to use.
3737    UNSIGNEDP nonzero means do unsigned division.  */
3738
3739 /* ??? For CEIL_MOD_EXPR, can compute incorrect remainder with ANDI
3740    and then correct it by or'ing in missing high bits
3741    if result of ANDI is nonzero.
3742    For ROUND_MOD_EXPR, can use ANDI and then sign-extend the result.
3743    This could optimize to a bfexts instruction.
3744    But C doesn't use these operations, so their optimizations are
3745    left for later.  */
3746 /* ??? For modulo, we don't actually need the highpart of the first product,
3747    the low part will do nicely.  And for small divisors, the second multiply
3748    can also be a low-part only multiply or even be completely left out.
3749    E.g. to calculate the remainder of a division by 3 with a 32 bit
3750    multiply, multiply with 0x55555556 and extract the upper two bits;
3751    the result is exact for inputs up to 0x1fffffff.
3752    The input range can be reduced by using cross-sum rules.
3753    For odd divisors >= 3, the following table gives right shift counts
3754    so that if a number is shifted by an integer multiple of the given
3755    amount, the remainder stays the same:
3756    2, 4, 3, 6, 10, 12, 4, 8, 18, 6, 11, 20, 18, 0, 5, 10, 12, 0, 12, 20,
3757    14, 12, 23, 21, 8, 0, 20, 18, 0, 0, 6, 12, 0, 22, 0, 18, 20, 30, 0, 0,
3758    0, 8, 0, 11, 12, 10, 36, 0, 30, 0, 0, 12, 0, 0, 0, 0, 44, 12, 24, 0,
3759    20, 0, 7, 14, 0, 18, 36, 0, 0, 46, 60, 0, 42, 0, 15, 24, 20, 0, 0, 33,
3760    0, 20, 0, 0, 18, 0, 60, 0, 0, 0, 0, 0, 40, 18, 0, 0, 12
3761
3762    Cross-sum rules for even numbers can be derived by leaving as many bits
3763    to the right alone as the divisor has zeros to the right.
3764    E.g. if x is an unsigned 32 bit number:
3765    (x mod 12) == (((x & 1023) + ((x >> 8) & ~3)) * 0x15555558 >> 2 * 3) >> 28
3766    */
3767
3768 rtx
3769 expand_divmod (int rem_flag, enum tree_code code, enum machine_mode mode,
3770                rtx op0, rtx op1, rtx target, int unsignedp)
3771 {
3772   enum machine_mode compute_mode;
3773   rtx tquotient;
3774   rtx quotient = 0, remainder = 0;
3775   rtx last;
3776   int size;
3777   rtx insn, set;
3778   optab optab1, optab2;
3779   int op1_is_constant, op1_is_pow2 = 0;
3780   int max_cost, extra_cost;
3781   static HOST_WIDE_INT last_div_const = 0;
3782   static HOST_WIDE_INT ext_op1;
3783   bool speed = optimize_insn_for_speed_p ();
3784
3785   op1_is_constant = GET_CODE (op1) == CONST_INT;
3786   if (op1_is_constant)
3787     {
3788       ext_op1 = INTVAL (op1);
3789       if (unsignedp)
3790         ext_op1 &= GET_MODE_MASK (mode);
3791       op1_is_pow2 = ((EXACT_POWER_OF_2_OR_ZERO_P (ext_op1)
3792                      || (! unsignedp && EXACT_POWER_OF_2_OR_ZERO_P (-ext_op1))));
3793     }
3794
3795   /*
3796      This is the structure of expand_divmod:
3797
3798      First comes code to fix up the operands so we can perform the operations
3799      correctly and efficiently.
3800
3801      Second comes a switch statement with code specific for each rounding mode.
3802      For some special operands this code emits all RTL for the desired
3803      operation, for other cases, it generates only a quotient and stores it in
3804      QUOTIENT.  The case for trunc division/remainder might leave quotient = 0,
3805      to indicate that it has not done anything.
3806
3807      Last comes code that finishes the operation.  If QUOTIENT is set and
3808      REM_FLAG is set, the remainder is computed as OP0 - QUOTIENT * OP1.  If
3809      QUOTIENT is not set, it is computed using trunc rounding.
3810
3811      We try to generate special code for division and remainder when OP1 is a
3812      constant.  If |OP1| = 2**n we can use shifts and some other fast
3813      operations.  For other values of OP1, we compute a carefully selected
3814      fixed-point approximation m = 1/OP1, and generate code that multiplies OP0
3815      by m.
3816
3817      In all cases but EXACT_DIV_EXPR, this multiplication requires the upper
3818      half of the product.  Different strategies for generating the product are
3819      implemented in expand_mult_highpart.
3820
3821      If what we actually want is the remainder, we generate that by another
3822      by-constant multiplication and a subtraction.  */
3823
3824   /* We shouldn't be called with OP1 == const1_rtx, but some of the
3825      code below will malfunction if we are, so check here and handle
3826      the special case if so.  */
3827   if (op1 == const1_rtx)
3828     return rem_flag ? const0_rtx : op0;
3829
3830     /* When dividing by -1, we could get an overflow.
3831      negv_optab can handle overflows.  */
3832   if (! unsignedp && op1 == constm1_rtx)
3833     {
3834       if (rem_flag)
3835         return const0_rtx;
3836       return expand_unop (mode, flag_trapv && GET_MODE_CLASS(mode) == MODE_INT
3837                           ? negv_optab : neg_optab, op0, target, 0);
3838     }
3839
3840   if (target
3841       /* Don't use the function value register as a target
3842          since we have to read it as well as write it,
3843          and function-inlining gets confused by this.  */
3844       && ((REG_P (target) && REG_FUNCTION_VALUE_P (target))
3845           /* Don't clobber an operand while doing a multi-step calculation.  */
3846           || ((rem_flag || op1_is_constant)
3847               && (reg_mentioned_p (target, op0)
3848                   || (MEM_P (op0) && MEM_P (target))))
3849           || reg_mentioned_p (target, op1)
3850           || (MEM_P (op1) && MEM_P (target))))
3851     target = 0;
3852
3853   /* Get the mode in which to perform this computation.  Normally it will
3854      be MODE, but sometimes we can't do the desired operation in MODE.
3855      If so, pick a wider mode in which we can do the operation.  Convert
3856      to that mode at the start to avoid repeated conversions.
3857
3858      First see what operations we need.  These depend on the expression
3859      we are evaluating.  (We assume that divxx3 insns exist under the
3860      same conditions that modxx3 insns and that these insns don't normally
3861      fail.  If these assumptions are not correct, we may generate less
3862      efficient code in some cases.)
3863
3864      Then see if we find a mode in which we can open-code that operation
3865      (either a division, modulus, or shift).  Finally, check for the smallest
3866      mode for which we can do the operation with a library call.  */
3867
3868   /* We might want to refine this now that we have division-by-constant
3869      optimization.  Since expand_mult_highpart tries so many variants, it is
3870      not straightforward to generalize this.  Maybe we should make an array
3871      of possible modes in init_expmed?  Save this for GCC 2.7.  */
3872
3873   optab1 = ((op1_is_pow2 && op1 != const0_rtx)
3874             ? (unsignedp ? lshr_optab : ashr_optab)
3875             : (unsignedp ? udiv_optab : sdiv_optab));
3876   optab2 = ((op1_is_pow2 && op1 != const0_rtx)
3877             ? optab1
3878             : (unsignedp ? udivmod_optab : sdivmod_optab));
3879
3880   for (compute_mode = mode; compute_mode != VOIDmode;
3881        compute_mode = GET_MODE_WIDER_MODE (compute_mode))
3882     if (optab_handler (optab1, compute_mode)->insn_code != CODE_FOR_nothing
3883         || optab_handler (optab2, compute_mode)->insn_code != CODE_FOR_nothing)
3884       break;
3885
3886   if (compute_mode == VOIDmode)
3887     for (compute_mode = mode; compute_mode != VOIDmode;
3888          compute_mode = GET_MODE_WIDER_MODE (compute_mode))
3889       if (optab_libfunc (optab1, compute_mode)
3890           || optab_libfunc (optab2, compute_mode))
3891         break;
3892
3893   /* If we still couldn't find a mode, use MODE, but expand_binop will
3894      probably die.  */
3895   if (compute_mode == VOIDmode)
3896     compute_mode = mode;
3897
3898   if (target && GET_MODE (target) == compute_mode)
3899     tquotient = target;
3900   else
3901     tquotient = gen_reg_rtx (compute_mode);
3902
3903   size = GET_MODE_BITSIZE (compute_mode);
3904 #if 0
3905   /* It should be possible to restrict the precision to GET_MODE_BITSIZE
3906      (mode), and thereby get better code when OP1 is a constant.  Do that
3907      later.  It will require going over all usages of SIZE below.  */
3908   size = GET_MODE_BITSIZE (mode);
3909 #endif
3910
3911   /* Only deduct something for a REM if the last divide done was
3912      for a different constant.   Then set the constant of the last
3913      divide.  */
3914   max_cost = unsignedp ? udiv_cost[speed][compute_mode] : sdiv_cost[speed][compute_mode];
3915   if (rem_flag && ! (last_div_const != 0 && op1_is_constant
3916                      && INTVAL (op1) == last_div_const))
3917     max_cost -= mul_cost[speed][compute_mode] + add_cost[speed][compute_mode];
3918
3919   last_div_const = ! rem_flag && op1_is_constant ? INTVAL (op1) : 0;
3920
3921   /* Now convert to the best mode to use.  */
3922   if (compute_mode != mode)
3923     {
3924       op0 = convert_modes (compute_mode, mode, op0, unsignedp);
3925       op1 = convert_modes (compute_mode, mode, op1, unsignedp);
3926
3927       /* convert_modes may have placed op1 into a register, so we
3928          must recompute the following.  */
3929       op1_is_constant = GET_CODE (op1) == CONST_INT;
3930       op1_is_pow2 = (op1_is_constant
3931                      && ((EXACT_POWER_OF_2_OR_ZERO_P (INTVAL (op1))
3932                           || (! unsignedp
3933                               && EXACT_POWER_OF_2_OR_ZERO_P (-INTVAL (op1)))))) ;
3934     }
3935
3936   /* If one of the operands is a volatile MEM, copy it into a register.  */
3937
3938   if (MEM_P (op0) && MEM_VOLATILE_P (op0))
3939     op0 = force_reg (compute_mode, op0);
3940   if (MEM_P (op1) && MEM_VOLATILE_P (op1))
3941     op1 = force_reg (compute_mode, op1);
3942
3943   /* If we need the remainder or if OP1 is constant, we need to
3944      put OP0 in a register in case it has any queued subexpressions.  */
3945   if (rem_flag || op1_is_constant)
3946     op0 = force_reg (compute_mode, op0);
3947
3948   last = get_last_insn ();
3949
3950   /* Promote floor rounding to trunc rounding for unsigned operations.  */
3951   if (unsignedp)
3952     {
3953       if (code == FLOOR_DIV_EXPR)
3954         code = TRUNC_DIV_EXPR;
3955       if (code == FLOOR_MOD_EXPR)
3956         code = TRUNC_MOD_EXPR;
3957       if (code == EXACT_DIV_EXPR && op1_is_pow2)
3958         code = TRUNC_DIV_EXPR;
3959     }
3960
3961   if (op1 != const0_rtx)
3962     switch (code)
3963       {
3964       case TRUNC_MOD_EXPR:
3965       case TRUNC_DIV_EXPR:
3966         if (op1_is_constant)
3967           {
3968             if (unsignedp)
3969               {
3970                 unsigned HOST_WIDE_INT mh;
3971                 int pre_shift, post_shift;
3972                 int dummy;
3973                 rtx ml;
3974                 unsigned HOST_WIDE_INT d = (INTVAL (op1)
3975                                             & GET_MODE_MASK (compute_mode));
3976
3977                 if (EXACT_POWER_OF_2_OR_ZERO_P (d))
3978                   {
3979                     pre_shift = floor_log2 (d);
3980                     if (rem_flag)
3981                       {
3982                         remainder
3983                           = expand_binop (compute_mode, and_optab, op0,
3984                                           GEN_INT (((HOST_WIDE_INT) 1 << pre_shift) - 1),
3985                                           remainder, 1,
3986                                           OPTAB_LIB_WIDEN);
3987                         if (remainder)
3988                           return gen_lowpart (mode, remainder);
3989                       }
3990                     quotient = expand_shift (RSHIFT_EXPR, compute_mode, op0,
3991                                              build_int_cst (NULL_TREE,
3992                                                             pre_shift),
3993                                              tquotient, 1);
3994                   }
3995                 else if (size <= HOST_BITS_PER_WIDE_INT)
3996                   {
3997                     if (d >= ((unsigned HOST_WIDE_INT) 1 << (size - 1)))
3998                       {
3999                         /* Most significant bit of divisor is set; emit an scc
4000                            insn.  */
4001                         quotient = emit_store_flag_force (tquotient, GEU, op0, op1,
4002                                                           compute_mode, 1, 1);
4003                       }
4004                     else
4005                       {
4006                         /* Find a suitable multiplier and right shift count
4007                            instead of multiplying with D.  */
4008
4009                         mh = choose_multiplier (d, size, size,
4010                                                 &ml, &post_shift, &dummy);
4011
4012                         /* If the suggested multiplier is more than SIZE bits,
4013                            we can do better for even divisors, using an
4014                            initial right shift.  */
4015                         if (mh != 0 && (d & 1) == 0)
4016                           {
4017                             pre_shift = floor_log2 (d & -d);
4018                             mh = choose_multiplier (d >> pre_shift, size,
4019                                                     size - pre_shift,
4020                                                     &ml, &post_shift, &dummy);
4021                             gcc_assert (!mh);
4022                           }
4023                         else
4024                           pre_shift = 0;
4025
4026                         if (mh != 0)
4027                           {
4028                             rtx t1, t2, t3, t4;
4029
4030                             if (post_shift - 1 >= BITS_PER_WORD)
4031                               goto fail1;
4032
4033                             extra_cost
4034                               = (shift_cost[speed][compute_mode][post_shift - 1]
4035                                  + shift_cost[speed][compute_mode][1]
4036                                  + 2 * add_cost[speed][compute_mode]);
4037                             t1 = expand_mult_highpart (compute_mode, op0, ml,
4038                                                        NULL_RTX, 1,
4039                                                        max_cost - extra_cost);
4040                             if (t1 == 0)
4041                               goto fail1;
4042                             t2 = force_operand (gen_rtx_MINUS (compute_mode,
4043                                                                op0, t1),
4044                                                 NULL_RTX);
4045                             t3 = expand_shift
4046                               (RSHIFT_EXPR, compute_mode, t2,
4047                                build_int_cst (NULL_TREE, 1),
4048                                NULL_RTX,1);
4049                             t4 = force_operand (gen_rtx_PLUS (compute_mode,
4050                                                               t1, t3),
4051                                                 NULL_RTX);
4052                             quotient = expand_shift
4053                               (RSHIFT_EXPR, compute_mode, t4,
4054                                build_int_cst (NULL_TREE, post_shift - 1),
4055                                tquotient, 1);
4056                           }
4057                         else
4058                           {
4059                             rtx t1, t2;
4060
4061                             if (pre_shift >= BITS_PER_WORD
4062                                 || post_shift >= BITS_PER_WORD)
4063                               goto fail1;
4064
4065                             t1 = expand_shift
4066                               (RSHIFT_EXPR, compute_mode, op0,
4067                                build_int_cst (NULL_TREE, pre_shift),
4068                                NULL_RTX, 1);
4069                             extra_cost
4070                               = (shift_cost[speed][compute_mode][pre_shift]
4071                                  + shift_cost[speed][compute_mode][post_shift]);
4072                             t2 = expand_mult_highpart (compute_mode, t1, ml,
4073                                                        NULL_RTX, 1,
4074                                                        max_cost - extra_cost);
4075                             if (t2 == 0)
4076                               goto fail1;
4077                             quotient = expand_shift
4078                               (RSHIFT_EXPR, compute_mode, t2,
4079                                build_int_cst (NULL_TREE, post_shift),
4080                                tquotient, 1);
4081                           }
4082                       }
4083                   }
4084                 else            /* Too wide mode to use tricky code */
4085                   break;
4086
4087                 insn = get_last_insn ();
4088                 if (insn != last
4089                     && (set = single_set (insn)) != 0
4090                     && SET_DEST (set) == quotient)
4091                   set_unique_reg_note (insn,
4092                                        REG_EQUAL,
4093                                        gen_rtx_UDIV (compute_mode, op0, op1));
4094               }
4095             else                /* TRUNC_DIV, signed */
4096               {
4097                 unsigned HOST_WIDE_INT ml;
4098                 int lgup, post_shift;
4099                 rtx mlr;
4100                 HOST_WIDE_INT d = INTVAL (op1);
4101                 unsigned HOST_WIDE_INT abs_d;
4102
4103                 /* Since d might be INT_MIN, we have to cast to
4104                    unsigned HOST_WIDE_INT before negating to avoid
4105                    undefined signed overflow.  */
4106                 abs_d = (d >= 0
4107                          ? (unsigned HOST_WIDE_INT) d
4108                          : - (unsigned HOST_WIDE_INT) d);
4109
4110                 /* n rem d = n rem -d */
4111                 if (rem_flag && d < 0)
4112                   {
4113                     d = abs_d;
4114                     op1 = gen_int_mode (abs_d, compute_mode);
4115                   }
4116
4117                 if (d == 1)
4118                   quotient = op0;
4119                 else if (d == -1)
4120                   quotient = expand_unop (compute_mode, neg_optab, op0,
4121                                           tquotient, 0);
4122                 else if (abs_d == (unsigned HOST_WIDE_INT) 1 << (size - 1))
4123                   {
4124                     /* This case is not handled correctly below.  */
4125                     quotient = emit_store_flag (tquotient, EQ, op0, op1,
4126                                                 compute_mode, 1, 1);
4127                     if (quotient == 0)
4128                       goto fail1;
4129                   }
4130                 else if (EXACT_POWER_OF_2_OR_ZERO_P (d)
4131                          && (rem_flag ? smod_pow2_cheap[speed][compute_mode]
4132                                       : sdiv_pow2_cheap[speed][compute_mode])
4133                          /* We assume that cheap metric is true if the
4134                             optab has an expander for this mode.  */
4135                          && ((optab_handler ((rem_flag ? smod_optab
4136                                               : sdiv_optab),
4137                                               compute_mode)->insn_code
4138                               != CODE_FOR_nothing)
4139                              || (optab_handler(sdivmod_optab,
4140                                                compute_mode)
4141                                  ->insn_code != CODE_FOR_nothing)))
4142                   ;
4143                 else if (EXACT_POWER_OF_2_OR_ZERO_P (abs_d))
4144                   {
4145                     if (rem_flag)
4146                       {
4147                         remainder = expand_smod_pow2 (compute_mode, op0, d);
4148                         if (remainder)
4149                           return gen_lowpart (mode, remainder);
4150                       }
4151
4152                     if (sdiv_pow2_cheap[speed][compute_mode]
4153                         && ((optab_handler (sdiv_optab, compute_mode)->insn_code
4154                              != CODE_FOR_nothing)
4155                             || (optab_handler (sdivmod_optab, compute_mode)->insn_code
4156                                 != CODE_FOR_nothing)))
4157                       quotient = expand_divmod (0, TRUNC_DIV_EXPR,
4158                                                 compute_mode, op0,
4159                                                 gen_int_mode (abs_d,
4160                                                               compute_mode),
4161                                                 NULL_RTX, 0);
4162                     else
4163                       quotient = expand_sdiv_pow2 (compute_mode, op0, abs_d);
4164
4165                     /* We have computed OP0 / abs(OP1).  If OP1 is negative,
4166                        negate the quotient.  */
4167                     if (d < 0)
4168                       {
4169                         insn = get_last_insn ();
4170                         if (insn != last
4171                             && (set = single_set (insn)) != 0
4172                             && SET_DEST (set) == quotient
4173                             && abs_d < ((unsigned HOST_WIDE_INT) 1
4174                                         << (HOST_BITS_PER_WIDE_INT - 1)))
4175                           set_unique_reg_note (insn,
4176                                                REG_EQUAL,
4177                                                gen_rtx_DIV (compute_mode,
4178                                                             op0,
4179                                                             GEN_INT
4180                                                             (trunc_int_for_mode
4181                                                              (abs_d,
4182                                                               compute_mode))));
4183
4184                         quotient = expand_unop (compute_mode, neg_optab,
4185                                                 quotient, quotient, 0);
4186                       }
4187                   }
4188                 else if (size <= HOST_BITS_PER_WIDE_INT)
4189                   {
4190                     choose_multiplier (abs_d, size, size - 1,
4191                                        &mlr, &post_shift, &lgup);
4192                     ml = (unsigned HOST_WIDE_INT) INTVAL (mlr);
4193                     if (ml < (unsigned HOST_WIDE_INT) 1 << (size - 1))
4194                       {
4195                         rtx t1, t2, t3;
4196
4197                         if (post_shift >= BITS_PER_WORD
4198                             || size - 1 >= BITS_PER_WORD)
4199                           goto fail1;
4200
4201                         extra_cost = (shift_cost[speed][compute_mode][post_shift]
4202                                       + shift_cost[speed][compute_mode][size - 1]
4203                                       + add_cost[speed][compute_mode]);
4204                         t1 = expand_mult_highpart (compute_mode, op0, mlr,
4205                                                    NULL_RTX, 0,
4206                                                    max_cost - extra_cost);
4207                         if (t1 == 0)
4208                           goto fail1;
4209                         t2 = expand_shift
4210                           (RSHIFT_EXPR, compute_mode, t1,
4211                            build_int_cst (NULL_TREE, post_shift),
4212                            NULL_RTX, 0);
4213                         t3 = expand_shift
4214                           (RSHIFT_EXPR, compute_mode, op0,
4215                            build_int_cst (NULL_TREE, size - 1),
4216                            NULL_RTX, 0);
4217                         if (d < 0)
4218                           quotient
4219                             = force_operand (gen_rtx_MINUS (compute_mode,
4220                                                             t3, t2),
4221                                              tquotient);
4222                         else
4223                           quotient
4224                             = force_operand (gen_rtx_MINUS (compute_mode,
4225                                                             t2, t3),
4226                                              tquotient);
4227                       }
4228                     else
4229                       {
4230                         rtx t1, t2, t3, t4;
4231
4232                         if (post_shift >= BITS_PER_WORD
4233                             || size - 1 >= BITS_PER_WORD)
4234                           goto fail1;
4235
4236                         ml |= (~(unsigned HOST_WIDE_INT) 0) << (size - 1);
4237                         mlr = gen_int_mode (ml, compute_mode);
4238                         extra_cost = (shift_cost[speed][compute_mode][post_shift]
4239                                       + shift_cost[speed][compute_mode][size - 1]
4240                                       + 2 * add_cost[speed][compute_mode]);
4241                         t1 = expand_mult_highpart (compute_mode, op0, mlr,
4242                                                    NULL_RTX, 0,
4243                                                    max_cost - extra_cost);
4244                         if (t1 == 0)
4245                           goto fail1;
4246                         t2 = force_operand (gen_rtx_PLUS (compute_mode,
4247                                                           t1, op0),
4248                                             NULL_RTX);
4249                         t3 = expand_shift
4250                           (RSHIFT_EXPR, compute_mode, t2,
4251                            build_int_cst (NULL_TREE, post_shift),
4252                            NULL_RTX, 0);
4253                         t4 = expand_shift
4254                           (RSHIFT_EXPR, compute_mode, op0,
4255                            build_int_cst (NULL_TREE, size - 1),
4256                            NULL_RTX, 0);
4257                         if (d < 0)
4258                           quotient
4259                             = force_operand (gen_rtx_MINUS (compute_mode,
4260                                                             t4, t3),
4261                                              tquotient);
4262                         else
4263                           quotient
4264                             = force_operand (gen_rtx_MINUS (compute_mode,
4265                                                             t3, t4),
4266                                              tquotient);
4267                       }
4268                   }
4269                 else            /* Too wide mode to use tricky code */
4270                   break;
4271
4272                 insn = get_last_insn ();
4273                 if (insn != last
4274                     && (set = single_set (insn)) != 0
4275                     && SET_DEST (set) == quotient)
4276                   set_unique_reg_note (insn,
4277                                        REG_EQUAL,
4278                                        gen_rtx_DIV (compute_mode, op0, op1));
4279               }
4280             break;
4281           }
4282       fail1:
4283         delete_insns_since (last);
4284         break;
4285
4286       case FLOOR_DIV_EXPR:
4287       case FLOOR_MOD_EXPR:
4288       /* We will come here only for signed operations.  */
4289         if (op1_is_constant && HOST_BITS_PER_WIDE_INT >= size)
4290           {
4291             unsigned HOST_WIDE_INT mh;
4292             int pre_shift, lgup, post_shift;
4293             HOST_WIDE_INT d = INTVAL (op1);
4294             rtx ml;
4295
4296             if (d > 0)
4297               {
4298                 /* We could just as easily deal with negative constants here,
4299                    but it does not seem worth the trouble for GCC 2.6.  */
4300                 if (EXACT_POWER_OF_2_OR_ZERO_P (d))
4301                   {
4302                     pre_shift = floor_log2 (d);
4303                     if (rem_flag)
4304                       {
4305                         remainder = expand_binop (compute_mode, and_optab, op0,
4306                                                   GEN_INT (((HOST_WIDE_INT) 1 << pre_shift) - 1),
4307                                                   remainder, 0, OPTAB_LIB_WIDEN);
4308                         if (remainder)
4309                           return gen_lowpart (mode, remainder);
4310                       }
4311                     quotient = expand_shift
4312                       (RSHIFT_EXPR, compute_mode, op0,
4313                        build_int_cst (NULL_TREE, pre_shift),
4314                        tquotient, 0);
4315                   }
4316                 else
4317                   {
4318                     rtx t1, t2, t3, t4;
4319
4320                     mh = choose_multiplier (d, size, size - 1,
4321                                             &ml, &post_shift, &lgup);
4322                     gcc_assert (!mh);
4323
4324                     if (post_shift < BITS_PER_WORD
4325                         && size - 1 < BITS_PER_WORD)
4326                       {
4327                         t1 = expand_shift
4328                           (RSHIFT_EXPR, compute_mode, op0,
4329                            build_int_cst (NULL_TREE, size - 1),
4330                            NULL_RTX, 0);
4331                         t2 = expand_binop (compute_mode, xor_optab, op0, t1,
4332                                            NULL_RTX, 0, OPTAB_WIDEN);
4333                         extra_cost = (shift_cost[speed][compute_mode][post_shift]
4334                                       + shift_cost[speed][compute_mode][size - 1]
4335                                       + 2 * add_cost[speed][compute_mode]);
4336                         t3 = expand_mult_highpart (compute_mode, t2, ml,
4337                                                    NULL_RTX, 1,
4338                                                    max_cost - extra_cost);
4339                         if (t3 != 0)
4340                           {
4341                             t4 = expand_shift
4342                               (RSHIFT_EXPR, compute_mode, t3,
4343                                build_int_cst (NULL_TREE, post_shift),
4344                                NULL_RTX, 1);
4345                             quotient = expand_binop (compute_mode, xor_optab,
4346                                                      t4, t1, tquotient, 0,
4347                                                      OPTAB_WIDEN);
4348                           }
4349                       }
4350                   }
4351               }
4352             else
4353               {
4354                 rtx nsign, t1, t2, t3, t4;
4355                 t1 = force_operand (gen_rtx_PLUS (compute_mode,
4356                                                   op0, constm1_rtx), NULL_RTX);
4357                 t2 = expand_binop (compute_mode, ior_optab, op0, t1, NULL_RTX,
4358                                    0, OPTAB_WIDEN);
4359                 nsign = expand_shift
4360                   (RSHIFT_EXPR, compute_mode, t2,
4361                    build_int_cst (NULL_TREE, size - 1),
4362                    NULL_RTX, 0);
4363                 t3 = force_operand (gen_rtx_MINUS (compute_mode, t1, nsign),
4364                                     NULL_RTX);
4365                 t4 = expand_divmod (0, TRUNC_DIV_EXPR, compute_mode, t3, op1,
4366                                     NULL_RTX, 0);
4367                 if (t4)
4368                   {
4369                     rtx t5;
4370                     t5 = expand_unop (compute_mode, one_cmpl_optab, nsign,
4371                                       NULL_RTX, 0);
4372                     quotient = force_operand (gen_rtx_PLUS (compute_mode,
4373                                                             t4, t5),
4374                                               tquotient);
4375                   }
4376               }
4377           }
4378
4379         if (quotient != 0)
4380           break;
4381         delete_insns_since (last);
4382
4383         /* Try using an instruction that produces both the quotient and
4384            remainder, using truncation.  We can easily compensate the quotient
4385            or remainder to get floor rounding, once we have the remainder.
4386            Notice that we compute also the final remainder value here,
4387            and return the result right away.  */
4388         if (target == 0 || GET_MODE (target) != compute_mode)
4389           target = gen_reg_rtx (compute_mode);
4390
4391         if (rem_flag)
4392           {
4393             remainder
4394               = REG_P (target) ? target : gen_reg_rtx (compute_mode);
4395             quotient = gen_reg_rtx (compute_mode);
4396           }
4397         else
4398           {
4399             quotient
4400               = REG_P (target) ? target : gen_reg_rtx (compute_mode);
4401             remainder = gen_reg_rtx (compute_mode);
4402           }
4403
4404         if (expand_twoval_binop (sdivmod_optab, op0, op1,
4405                                  quotient, remainder, 0))
4406           {
4407             /* This could be computed with a branch-less sequence.
4408                Save that for later.  */
4409             rtx tem;
4410             rtx label = gen_label_rtx ();
4411             do_cmp_and_jump (remainder, const0_rtx, EQ, compute_mode, label);
4412             tem = expand_binop (compute_mode, xor_optab, op0, op1,
4413                                 NULL_RTX, 0, OPTAB_WIDEN);
4414             do_cmp_and_jump (tem, const0_rtx, GE, compute_mode, label);
4415             expand_dec (quotient, const1_rtx);
4416             expand_inc (remainder, op1);
4417             emit_label (label);
4418             return gen_lowpart (mode, rem_flag ? remainder : quotient);
4419           }
4420
4421         /* No luck with division elimination or divmod.  Have to do it
4422            by conditionally adjusting op0 *and* the result.  */
4423         {
4424           rtx label1, label2, label3, label4, label5;
4425           rtx adjusted_op0;
4426           rtx tem;
4427
4428           quotient = gen_reg_rtx (compute_mode);
4429           adjusted_op0 = copy_to_mode_reg (compute_mode, op0);
4430           label1 = gen_label_rtx ();
4431           label2 = gen_label_rtx ();
4432           label3 = gen_label_rtx ();
4433           label4 = gen_label_rtx ();
4434           label5 = gen_label_rtx ();
4435           do_cmp_and_jump (op1, const0_rtx, LT, compute_mode, label2);
4436           do_cmp_and_jump (adjusted_op0, const0_rtx, LT, compute_mode, label1);
4437           tem = expand_binop (compute_mode, sdiv_optab, adjusted_op0, op1,
4438                               quotient, 0, OPTAB_LIB_WIDEN);
4439           if (tem != quotient)
4440             emit_move_insn (quotient, tem);
4441           emit_jump_insn (gen_jump (label5));
4442           emit_barrier ();
4443           emit_label (label1);
4444           expand_inc (adjusted_op0, const1_rtx);
4445           emit_jump_insn (gen_jump (label4));
4446           emit_barrier ();
4447           emit_label (label2);
4448           do_cmp_and_jump (adjusted_op0, const0_rtx, GT, compute_mode, label3);
4449           tem = expand_binop (compute_mode, sdiv_optab, adjusted_op0, op1,
4450                               quotient, 0, OPTAB_LIB_WIDEN);
4451           if (tem != quotient)
4452             emit_move_insn (quotient, tem);
4453           emit_jump_insn (gen_jump (label5));
4454           emit_barrier ();
4455           emit_label (label3);
4456           expand_dec (adjusted_op0, const1_rtx);
4457           emit_label (label4);
4458           tem = expand_binop (compute_mode, sdiv_optab, adjusted_op0, op1,
4459                               quotient, 0, OPTAB_LIB_WIDEN);
4460           if (tem != quotient)
4461             emit_move_insn (quotient, tem);
4462           expand_dec (quotient, const1_rtx);
4463           emit_label (label5);
4464         }
4465         break;
4466
4467       case CEIL_DIV_EXPR:
4468       case CEIL_MOD_EXPR:
4469         if (unsignedp)
4470           {
4471             if (op1_is_constant && EXACT_POWER_OF_2_OR_ZERO_P (INTVAL (op1)))
4472               {
4473                 rtx t1, t2, t3;
4474                 unsigned HOST_WIDE_INT d = INTVAL (op1);
4475                 t1 = expand_shift (RSHIFT_EXPR, compute_mode, op0,
4476                                    build_int_cst (NULL_TREE, floor_log2 (d)),
4477                                    tquotient, 1);
4478                 t2 = expand_binop (compute_mode, and_optab, op0,
4479                                    GEN_INT (d - 1),
4480                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
4481                 t3 = gen_reg_rtx (compute_mode);
4482                 t3 = emit_store_flag (t3, NE, t2, const0_rtx,
4483                                       compute_mode, 1, 1);
4484                 if (t3 == 0)
4485                   {
4486                     rtx lab;
4487                     lab = gen_label_rtx ();
4488                     do_cmp_and_jump (t2, const0_rtx, EQ, compute_mode, lab);
4489                     expand_inc (t1, const1_rtx);
4490                     emit_label (lab);
4491                     quotient = t1;
4492                   }
4493                 else
4494                   quotient = force_operand (gen_rtx_PLUS (compute_mode,
4495                                                           t1, t3),
4496                                             tquotient);
4497                 break;
4498               }
4499
4500             /* Try using an instruction that produces both the quotient and
4501                remainder, using truncation.  We can easily compensate the
4502                quotient or remainder to get ceiling rounding, once we have the
4503                remainder.  Notice that we compute also the final remainder
4504                value here, and return the result right away.  */
4505             if (target == 0 || GET_MODE (target) != compute_mode)
4506               target = gen_reg_rtx (compute_mode);
4507
4508             if (rem_flag)
4509               {
4510                 remainder = (REG_P (target)
4511                              ? target : gen_reg_rtx (compute_mode));
4512                 quotient = gen_reg_rtx (compute_mode);
4513               }
4514             else
4515               {
4516                 quotient = (REG_P (target)
4517                             ? target : gen_reg_rtx (compute_mode));
4518                 remainder = gen_reg_rtx (compute_mode);
4519               }
4520
4521             if (expand_twoval_binop (udivmod_optab, op0, op1, quotient,
4522                                      remainder, 1))
4523               {
4524                 /* This could be computed with a branch-less sequence.
4525                    Save that for later.  */
4526                 rtx label = gen_label_rtx ();
4527                 do_cmp_and_jump (remainder, const0_rtx, EQ,
4528                                  compute_mode, label);
4529                 expand_inc (quotient, const1_rtx);
4530                 expand_dec (remainder, op1);
4531                 emit_label (label);
4532                 return gen_lowpart (mode, rem_flag ? remainder : quotient);
4533               }
4534
4535             /* No luck with division elimination or divmod.  Have to do it
4536                by conditionally adjusting op0 *and* the result.  */
4537             {
4538               rtx label1, label2;
4539               rtx adjusted_op0, tem;
4540
4541               quotient = gen_reg_rtx (compute_mode);
4542               adjusted_op0 = copy_to_mode_reg (compute_mode, op0);
4543               label1 = gen_label_rtx ();
4544               label2 = gen_label_rtx ();
4545               do_cmp_and_jump (adjusted_op0, const0_rtx, NE,
4546                                compute_mode, label1);
4547               emit_move_insn  (quotient, const0_rtx);
4548               emit_jump_insn (gen_jump (label2));
4549               emit_barrier ();
4550               emit_label (label1);
4551               expand_dec (adjusted_op0, const1_rtx);
4552               tem = expand_binop (compute_mode, udiv_optab, adjusted_op0, op1,
4553                                   quotient, 1, OPTAB_LIB_WIDEN);
4554               if (tem != quotient)
4555                 emit_move_insn (quotient, tem);
4556               expand_inc (quotient, const1_rtx);
4557               emit_label (label2);
4558             }
4559           }
4560         else /* signed */
4561           {
4562             if (op1_is_constant && EXACT_POWER_OF_2_OR_ZERO_P (INTVAL (op1))
4563                 && INTVAL (op1) >= 0)
4564               {
4565                 /* This is extremely similar to the code for the unsigned case
4566                    above.  For 2.7 we should merge these variants, but for
4567                    2.6.1 I don't want to touch the code for unsigned since that
4568                    get used in C.  The signed case will only be used by other
4569                    languages (Ada).  */
4570
4571                 rtx t1, t2, t3;
4572                 unsigned HOST_WIDE_INT d = INTVAL (op1);
4573                 t1 = expand_shift (RSHIFT_EXPR, compute_mode, op0,
4574                                    build_int_cst (NULL_TREE, floor_log2 (d)),
4575                                    tquotient, 0);
4576                 t2 = expand_binop (compute_mode, and_optab, op0,
4577                                    GEN_INT (d - 1),
4578                                    NULL_RTX, 1, OPTAB_LIB_WIDEN);
4579                 t3 = gen_reg_rtx (compute_mode);
4580                 t3 = emit_store_flag (t3, NE, t2, const0_rtx,
4581                                       compute_mode, 1, 1);
4582                 if (t3 == 0)
4583                   {
4584                     rtx lab;
4585                     lab = gen_label_rtx ();
4586                     do_cmp_and_jump (t2, const0_rtx, EQ, compute_mode, lab);
4587                     expand_inc (t1, const1_rtx);
4588                     emit_label (lab);
4589                     quotient = t1;
4590                   }
4591                 else
4592                   quotient = force_operand (gen_rtx_PLUS (compute_mode,
4593                                                           t1, t3),
4594                                             tquotient);
4595                 break;
4596               }
4597
4598             /* Try using an instruction that produces both the quotient and
4599                remainder, using truncation.  We can easily compensate the
4600                quotient or remainder to get ceiling rounding, once we have the
4601                remainder.  Notice that we compute also the final remainder
4602                value here, and return the result right away.  */
4603             if (target == 0 || GET_MODE (target) != compute_mode)
4604               target = gen_reg_rtx (compute_mode);
4605             if (rem_flag)
4606               {
4607                 remainder= (REG_P (target)
4608                             ? target : gen_reg_rtx (compute_mode));
4609                 quotient = gen_reg_rtx (compute_mode);
4610               }
4611             else
4612               {
4613                 quotient = (REG_P (target)
4614                             ? target : gen_reg_rtx (compute_mode));
4615                 remainder = gen_reg_rtx (compute_mode);
4616               }
4617
4618             if (expand_twoval_binop (sdivmod_optab, op0, op1, quotient,
4619                                      remainder, 0))
4620               {
4621                 /* This could be computed with a branch-less sequence.
4622                    Save that for later.  */
4623                 rtx tem;
4624                 rtx label = gen_label_rtx ();
4625                 do_cmp_and_jump (remainder, const0_rtx, EQ,
4626                                  compute_mode, label);
4627                 tem = expand_binop (compute_mode, xor_optab, op0, op1,
4628                                     NULL_RTX, 0, OPTAB_WIDEN);
4629                 do_cmp_and_jump (tem, const0_rtx, LT, compute_mode, label);
4630                 expand_inc (quotient, const1_rtx);
4631                 expand_dec (remainder, op1);
4632                 emit_label (label);
4633                 return gen_lowpart (mode, rem_flag ? remainder : quotient);
4634               }
4635
4636             /* No luck with division elimination or divmod.  Have to do it
4637                by conditionally adjusting op0 *and* the result.  */
4638             {
4639               rtx label1, label2, label3, label4, label5;
4640               rtx adjusted_op0;
4641               rtx tem;
4642
4643               quotient = gen_reg_rtx (compute_mode);
4644               adjusted_op0 = copy_to_mode_reg (compute_mode, op0);
4645               label1 = gen_label_rtx ();
4646               label2 = gen_label_rtx ();
4647               label3 = gen_label_rtx ();
4648               label4 = gen_label_rtx ();
4649               label5 = gen_label_rtx ();
4650               do_cmp_and_jump (op1, const0_rtx, LT, compute_mode, label2);
4651               do_cmp_and_jump (adjusted_op0, const0_rtx, GT,
4652                                compute_mode, label1);
4653               tem = expand_binop (compute_mode, sdiv_optab, adjusted_op0, op1,
4654                                   quotient, 0, OPTAB_LIB_WIDEN);
4655               if (tem != quotient)
4656                 emit_move_insn (quotient, tem);
4657               emit_jump_insn (gen_jump (label5));
4658               emit_barrier ();
4659               emit_label (label1);
4660               expand_dec (adjusted_op0, const1_rtx);
4661               emit_jump_insn (gen_jump (label4));
4662               emit_barrier ();
4663               emit_label (label2);
4664               do_cmp_and_jump (adjusted_op0, const0_rtx, LT,
4665                                compute_mode, label3);
4666               tem = expand_binop (compute_mode, sdiv_optab, adjusted_op0, op1,
4667                                   quotient, 0, OPTAB_LIB_WIDEN);
4668               if (tem != quotient)
4669                 emit_move_insn (quotient, tem);
4670               emit_jump_insn (gen_jump (label5));
4671               emit_barrier ();
4672               emit_label (label3);
4673               expand_inc (adjusted_op0, const1_rtx);
4674               emit_label (label4);
4675               tem = expand_binop (compute_mode, sdiv_optab, adjusted_op0, op1,
4676                                   quotient, 0, OPTAB_LIB_WIDEN);
4677               if (tem != quotient)
4678                 emit_move_insn (quotient, tem);
4679               expand_inc (quotient, const1_rtx);
4680               emit_label (label5);
4681             }
4682           }
4683         break;
4684
4685       case EXACT_DIV_EXPR:
4686         if (op1_is_constant && HOST_BITS_PER_WIDE_INT >= size)
4687           {
4688             HOST_WIDE_INT d = INTVAL (op1);
4689             unsigned HOST_WIDE_INT ml;
4690             int pre_shift;
4691             rtx t1;
4692
4693             pre_shift = floor_log2 (d & -d);
4694             ml = invert_mod2n (d >> pre_shift, size);
4695             t1 = expand_shift (RSHIFT_EXPR, compute_mode, op0,
4696                                build_int_cst (NULL_TREE, pre_shift),
4697                                NULL_RTX, unsignedp);
4698             quotient = expand_mult (compute_mode, t1,
4699                                     gen_int_mode (ml, compute_mode),
4700                                     NULL_RTX, 1);
4701
4702             insn = get_last_insn ();
4703             set_unique_reg_note (insn,
4704                                  REG_EQUAL,
4705                                  gen_rtx_fmt_ee (unsignedp ? UDIV : DIV,
4706                                                  compute_mode,
4707                                                  op0, op1));
4708           }
4709         break;
4710
4711       case ROUND_DIV_EXPR:
4712       case ROUND_MOD_EXPR:
4713         if (unsignedp)
4714           {
4715             rtx tem;
4716             rtx label;
4717             label = gen_label_rtx ();
4718             quotient = gen_reg_rtx (compute_mode);
4719             remainder = gen_reg_rtx (compute_mode);
4720             if (expand_twoval_binop (udivmod_optab, op0, op1, quotient, remainder, 1) == 0)
4721               {
4722                 rtx tem;
4723                 quotient = expand_binop (compute_mode, udiv_optab, op0, op1,
4724                                          quotient, 1, OPTAB_LIB_WIDEN);
4725                 tem = expand_mult (compute_mode, quotient, op1, NULL_RTX, 1);
4726                 remainder = expand_binop (compute_mode, sub_optab, op0, tem,
4727                                           remainder, 1, OPTAB_LIB_WIDEN);
4728               }
4729             tem = plus_constant (op1, -1);
4730             tem = expand_shift (RSHIFT_EXPR, compute_mode, tem,
4731                                 build_int_cst (NULL_TREE, 1),
4732                                 NULL_RTX, 1);
4733             do_cmp_and_jump (remainder, tem, LEU, compute_mode, label);
4734             expand_inc (quotient, const1_rtx);
4735             expand_dec (remainder, op1);
4736             emit_label (label);
4737           }
4738         else
4739           {
4740             rtx abs_rem, abs_op1, tem, mask;
4741             rtx label;
4742             label = gen_label_rtx ();
4743             quotient = gen_reg_rtx (compute_mode);
4744             remainder = gen_reg_rtx (compute_mode);
4745             if (expand_twoval_binop (sdivmod_optab, op0, op1, quotient, remainder, 0) == 0)
4746               {
4747                 rtx tem;
4748                 quotient = expand_binop (compute_mode, sdiv_optab, op0, op1,
4749                                          quotient, 0, OPTAB_LIB_WIDEN);
4750                 tem = expand_mult (compute_mode, quotient, op1, NULL_RTX, 0);
4751                 remainder = expand_binop (compute_mode, sub_optab, op0, tem,
4752                                           remainder, 0, OPTAB_LIB_WIDEN);
4753               }
4754             abs_rem = expand_abs (compute_mode, remainder, NULL_RTX, 1, 0);
4755             abs_op1 = expand_abs (compute_mode, op1, NULL_RTX, 1, 0);
4756             tem = expand_shift (LSHIFT_EXPR, compute_mode, abs_rem,
4757                                 build_int_cst (NULL_TREE, 1),
4758                                 NULL_RTX, 1);
4759             do_cmp_and_jump (tem, abs_op1, LTU, compute_mode, label);
4760             tem = expand_binop (compute_mode, xor_optab, op0, op1,
4761                                 NULL_RTX, 0, OPTAB_WIDEN);
4762             mask = expand_shift (RSHIFT_EXPR, compute_mode, tem,
4763                                  build_int_cst (NULL_TREE, size - 1),
4764                                  NULL_RTX, 0);
4765             tem = expand_binop (compute_mode, xor_optab, mask, const1_rtx,
4766                                 NULL_RTX, 0, OPTAB_WIDEN);
4767             tem = expand_binop (compute_mode, sub_optab, tem, mask,
4768                                 NULL_RTX, 0, OPTAB_WIDEN);
4769             expand_inc (quotient, tem);
4770             tem = expand_binop (compute_mode, xor_optab, mask, op1,
4771                                 NULL_RTX, 0, OPTAB_WIDEN);
4772             tem = expand_binop (compute_mode, sub_optab, tem, mask,
4773                                 NULL_RTX, 0, OPTAB_WIDEN);
4774             expand_dec (remainder, tem);
4775             emit_label (label);
4776           }
4777         return gen_lowpart (mode, rem_flag ? remainder : quotient);
4778
4779       default:
4780         gcc_unreachable ();
4781       }
4782
4783   if (quotient == 0)
4784     {
4785       if (target && GET_MODE (target) != compute_mode)
4786         target = 0;
4787
4788       if (rem_flag)
4789         {
4790           /* Try to produce the remainder without producing the quotient.
4791              If we seem to have a divmod pattern that does not require widening,
4792              don't try widening here.  We should really have a WIDEN argument
4793              to expand_twoval_binop, since what we'd really like to do here is
4794              1) try a mod insn in compute_mode
4795              2) try a divmod insn in compute_mode
4796              3) try a div insn in compute_mode and multiply-subtract to get
4797                 remainder
4798              4) try the same things with widening allowed.  */
4799           remainder
4800             = sign_expand_binop (compute_mode, umod_optab, smod_optab,
4801                                  op0, op1, target,
4802                                  unsignedp,
4803                                  ((optab_handler (optab2, compute_mode)->insn_code
4804                                    != CODE_FOR_nothing)
4805                                   ? OPTAB_DIRECT : OPTAB_WIDEN));
4806           if (remainder == 0)
4807             {
4808               /* No luck there.  Can we do remainder and divide at once
4809                  without a library call?  */
4810               remainder = gen_reg_rtx (compute_mode);
4811               if (! expand_twoval_binop ((unsignedp
4812                                           ? udivmod_optab
4813                                           : sdivmod_optab),
4814                                          op0, op1,
4815                                          NULL_RTX, remainder, unsignedp))
4816                 remainder = 0;
4817             }
4818
4819           if (remainder)
4820             return gen_lowpart (mode, remainder);
4821         }
4822
4823       /* Produce the quotient.  Try a quotient insn, but not a library call.
4824          If we have a divmod in this mode, use it in preference to widening
4825          the div (for this test we assume it will not fail). Note that optab2
4826          is set to the one of the two optabs that the call below will use.  */
4827       quotient
4828         = sign_expand_binop (compute_mode, udiv_optab, sdiv_optab,
4829                              op0, op1, rem_flag ? NULL_RTX : target,
4830                              unsignedp,
4831                              ((optab_handler (optab2, compute_mode)->insn_code
4832                                != CODE_FOR_nothing)
4833                               ? OPTAB_DIRECT : OPTAB_WIDEN));
4834
4835       if (quotient == 0)
4836         {
4837           /* No luck there.  Try a quotient-and-remainder insn,
4838              keeping the quotient alone.  */
4839           quotient = gen_reg_rtx (compute_mode);
4840           if (! expand_twoval_binop (unsignedp ? udivmod_optab : sdivmod_optab,
4841                                      op0, op1,
4842                                      quotient, NULL_RTX, unsignedp))
4843             {
4844               quotient = 0;
4845               if (! rem_flag)
4846                 /* Still no luck.  If we are not computing the remainder,
4847                    use a library call for the quotient.  */
4848                 quotient = sign_expand_binop (compute_mode,
4849                                               udiv_optab, sdiv_optab,
4850                                               op0, op1, target,
4851                                               unsignedp, OPTAB_LIB_WIDEN);
4852             }
4853         }
4854     }
4855
4856   if (rem_flag)
4857     {
4858       if (target && GET_MODE (target) != compute_mode)
4859         target = 0;
4860
4861       if (quotient == 0)
4862         {
4863           /* No divide instruction either.  Use library for remainder.  */
4864           remainder = sign_expand_binop (compute_mode, umod_optab, smod_optab,
4865                                          op0, op1, target,
4866                                          unsignedp, OPTAB_LIB_WIDEN);
4867           /* No remainder function.  Try a quotient-and-remainder
4868              function, keeping the remainder.  */
4869           if (!remainder)
4870             {
4871               remainder = gen_reg_rtx (compute_mode);
4872               if (!expand_twoval_binop_libfunc 
4873                   (unsignedp ? udivmod_optab : sdivmod_optab,
4874                    op0, op1,
4875                    NULL_RTX, remainder,
4876                    unsignedp ? UMOD : MOD))
4877                 remainder = NULL_RTX;
4878             }
4879         }
4880       else
4881         {
4882           /* We divided.  Now finish doing X - Y * (X / Y).  */
4883           remainder = expand_mult (compute_mode, quotient, op1,
4884                                    NULL_RTX, unsignedp);
4885           remainder = expand_binop (compute_mode, sub_optab, op0,
4886                                     remainder, target, unsignedp,
4887                                     OPTAB_LIB_WIDEN);
4888         }
4889     }
4890
4891   return gen_lowpart (mode, rem_flag ? remainder : quotient);
4892 }
4893 \f
4894 /* Return a tree node with data type TYPE, describing the value of X.
4895    Usually this is an VAR_DECL, if there is no obvious better choice.
4896    X may be an expression, however we only support those expressions
4897    generated by loop.c.  */
4898
4899 tree
4900 make_tree (tree type, rtx x)
4901 {
4902   tree t;
4903
4904   switch (GET_CODE (x))
4905     {
4906     case CONST_INT:
4907       {
4908         HOST_WIDE_INT hi = 0;
4909
4910         if (INTVAL (x) < 0
4911             && !(TYPE_UNSIGNED (type)
4912                  && (GET_MODE_BITSIZE (TYPE_MODE (type))
4913                      < HOST_BITS_PER_WIDE_INT)))
4914           hi = -1;
4915       
4916         t = build_int_cst_wide (type, INTVAL (x), hi);
4917         
4918         return t;
4919       }
4920       
4921     case CONST_DOUBLE:
4922       if (GET_MODE (x) == VOIDmode)
4923         t = build_int_cst_wide (type,
4924                                 CONST_DOUBLE_LOW (x), CONST_DOUBLE_HIGH (x));
4925       else
4926         {
4927           REAL_VALUE_TYPE d;
4928
4929           REAL_VALUE_FROM_CONST_DOUBLE (d, x);
4930           t = build_real (type, d);
4931         }
4932
4933       return t;
4934
4935     case CONST_VECTOR:
4936       {
4937         int units = CONST_VECTOR_NUNITS (x);
4938         tree itype = TREE_TYPE (type);
4939         tree t = NULL_TREE;
4940         int i;
4941
4942
4943         /* Build a tree with vector elements.  */
4944         for (i = units - 1; i >= 0; --i)
4945           {
4946             rtx elt = CONST_VECTOR_ELT (x, i);
4947             t = tree_cons (NULL_TREE, make_tree (itype, elt), t);
4948           }
4949
4950         return build_vector (type, t);
4951       }
4952
4953     case PLUS:
4954       return fold_build2 (PLUS_EXPR, type, make_tree (type, XEXP (x, 0)),
4955                           make_tree (type, XEXP (x, 1)));
4956
4957     case MINUS:
4958       return fold_build2 (MINUS_EXPR, type, make_tree (type, XEXP (x, 0)),
4959                           make_tree (type, XEXP (x, 1)));
4960
4961     case NEG:
4962       return fold_build1 (NEGATE_EXPR, type, make_tree (type, XEXP (x, 0)));
4963
4964     case MULT:
4965       return fold_build2 (MULT_EXPR, type, make_tree (type, XEXP (x, 0)),
4966                           make_tree (type, XEXP (x, 1)));
4967
4968     case ASHIFT:
4969       return fold_build2 (LSHIFT_EXPR, type, make_tree (type, XEXP (x, 0)),
4970                           make_tree (type, XEXP (x, 1)));
4971
4972     case LSHIFTRT:
4973       t = unsigned_type_for (type);
4974       return fold_convert (type, build2 (RSHIFT_EXPR, t,
4975                                          make_tree (t, XEXP (x, 0)),
4976                                          make_tree (type, XEXP (x, 1))));
4977
4978     case ASHIFTRT:
4979       t = signed_type_for (type);
4980       return fold_convert (type, build2 (RSHIFT_EXPR, t,
4981                                          make_tree (t, XEXP (x, 0)),
4982                                          make_tree (type, XEXP (x, 1))));
4983
4984     case DIV:
4985       if (TREE_CODE (type) != REAL_TYPE)
4986         t = signed_type_for (type);
4987       else
4988         t = type;
4989
4990       return fold_convert (type, build2 (TRUNC_DIV_EXPR, t,
4991                                          make_tree (t, XEXP (x, 0)),
4992                                          make_tree (t, XEXP (x, 1))));
4993     case UDIV:
4994       t = unsigned_type_for (type);
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
4999     case SIGN_EXTEND:
5000     case ZERO_EXTEND:
5001       t = lang_hooks.types.type_for_mode (GET_MODE (XEXP (x, 0)),
5002                                           GET_CODE (x) == ZERO_EXTEND);
5003       return fold_convert (type, make_tree (t, XEXP (x, 0)));
5004
5005     case CONST:
5006       return make_tree (type, XEXP (x, 0));
5007
5008     case SYMBOL_REF:
5009       t = SYMBOL_REF_DECL (x);
5010       if (t)
5011         return fold_convert (type, build_fold_addr_expr (t));
5012       /* else fall through.  */
5013
5014     default:
5015       t = build_decl (VAR_DECL, NULL_TREE, type);
5016
5017       /* If TYPE is a POINTER_TYPE, X might be Pmode with TYPE_MODE being
5018          ptr_mode.  So convert.  */
5019       if (POINTER_TYPE_P (type))
5020         x = convert_memory_address (TYPE_MODE (type), x);
5021
5022       /* Note that we do *not* use SET_DECL_RTL here, because we do not
5023          want set_decl_rtl to go adjusting REG_ATTRS for this temporary.  */
5024       t->decl_with_rtl.rtl = x;
5025
5026       return t;
5027     }
5028 }
5029 \f
5030 /* Compute the logical-and of OP0 and OP1, storing it in TARGET
5031    and returning TARGET.
5032
5033    If TARGET is 0, a pseudo-register or constant is returned.  */
5034
5035 rtx
5036 expand_and (enum machine_mode mode, rtx op0, rtx op1, rtx target)
5037 {
5038   rtx tem = 0;
5039
5040   if (GET_MODE (op0) == VOIDmode && GET_MODE (op1) == VOIDmode)
5041     tem = simplify_binary_operation (AND, mode, op0, op1);
5042   if (tem == 0)
5043     tem = expand_binop (mode, and_optab, op0, op1, target, 0, OPTAB_LIB_WIDEN);
5044
5045   if (target == 0)
5046     target = tem;
5047   else if (tem != target)
5048     emit_move_insn (target, tem);
5049   return target;
5050 }
5051 \f
5052 /* Helper function for emit_store_flag.  */
5053 static rtx
5054 emit_store_flag_1 (rtx target, rtx subtarget, enum machine_mode mode,
5055                    int normalizep)
5056 {
5057   rtx op0;
5058   enum machine_mode target_mode = GET_MODE (target);
5059   
5060   /* If we are converting to a wider mode, first convert to
5061      TARGET_MODE, then normalize.  This produces better combining
5062      opportunities on machines that have a SIGN_EXTRACT when we are
5063      testing a single bit.  This mostly benefits the 68k.
5064
5065      If STORE_FLAG_VALUE does not have the sign bit set when
5066      interpreted in MODE, we can do this conversion as unsigned, which
5067      is usually more efficient.  */
5068   if (GET_MODE_SIZE (target_mode) > GET_MODE_SIZE (mode))
5069     {
5070       convert_move (target, subtarget,
5071                     (GET_MODE_BITSIZE (mode) <= HOST_BITS_PER_WIDE_INT)
5072                     && 0 == (STORE_FLAG_VALUE
5073                              & ((HOST_WIDE_INT) 1
5074                                 << (GET_MODE_BITSIZE (mode) -1))));
5075       op0 = target;
5076       mode = target_mode;
5077     }
5078   else
5079     op0 = subtarget;
5080
5081   /* If we want to keep subexpressions around, don't reuse our last
5082      target.  */
5083   if (optimize)
5084     subtarget = 0;
5085
5086   /* Now normalize to the proper value in MODE.  Sometimes we don't
5087      have to do anything.  */
5088   if (normalizep == 0 || normalizep == STORE_FLAG_VALUE)
5089     ;
5090   /* STORE_FLAG_VALUE might be the most negative number, so write
5091      the comparison this way to avoid a compiler-time warning.  */
5092   else if (- normalizep == STORE_FLAG_VALUE)
5093     op0 = expand_unop (mode, neg_optab, op0, subtarget, 0);
5094
5095   /* We don't want to use STORE_FLAG_VALUE < 0 below since this makes
5096      it hard to use a value of just the sign bit due to ANSI integer
5097      constant typing rules.  */
5098   else if (GET_MODE_BITSIZE (mode) <= HOST_BITS_PER_WIDE_INT
5099            && (STORE_FLAG_VALUE
5100                & ((HOST_WIDE_INT) 1 << (GET_MODE_BITSIZE (mode) - 1))))
5101     op0 = expand_shift (RSHIFT_EXPR, mode, op0,
5102                         size_int (GET_MODE_BITSIZE (mode) - 1), subtarget,
5103                         normalizep == 1);
5104   else
5105     {
5106       gcc_assert (STORE_FLAG_VALUE & 1);
5107
5108       op0 = expand_and (mode, op0, const1_rtx, subtarget);
5109       if (normalizep == -1)
5110         op0 = expand_unop (mode, neg_optab, op0, op0, 0);
5111     }
5112
5113   /* If we were converting to a smaller mode, do the conversion now.  */
5114   if (target_mode != mode)
5115     {
5116       convert_move (target, op0, 0);
5117       return target;
5118     }
5119   else
5120     return op0;
5121 }
5122
5123 /* Emit a store-flags instruction for comparison CODE on OP0 and OP1
5124    and storing in TARGET.  Normally return TARGET.
5125    Return 0 if that cannot be done.
5126
5127    MODE is the mode to use for OP0 and OP1 should they be CONST_INTs.  If
5128    it is VOIDmode, they cannot both be CONST_INT.
5129
5130    UNSIGNEDP is for the case where we have to widen the operands
5131    to perform the operation.  It says to use zero-extension.
5132
5133    NORMALIZEP is 1 if we should convert the result to be either zero
5134    or one.  Normalize is -1 if we should convert the result to be
5135    either zero or -1.  If NORMALIZEP is zero, the result will be left
5136    "raw" out of the scc insn.  */
5137
5138 rtx
5139 emit_store_flag (rtx target, enum rtx_code code, rtx op0, rtx op1,
5140                  enum machine_mode mode, int unsignedp, int normalizep)
5141 {
5142   rtx subtarget;
5143   enum insn_code icode;
5144   enum machine_mode compare_mode;
5145   enum machine_mode target_mode = GET_MODE (target);
5146   rtx tem;
5147   rtx last = get_last_insn ();
5148   rtx pattern, comparison;
5149
5150   if (unsignedp)
5151     code = unsigned_condition (code);
5152
5153   /* If one operand is constant, make it the second one.  Only do this
5154      if the other operand is not constant as well.  */
5155
5156   if (swap_commutative_operands_p (op0, op1))
5157     {
5158       tem = op0;
5159       op0 = op1;
5160       op1 = tem;
5161       code = swap_condition (code);
5162     }
5163
5164   if (mode == VOIDmode)
5165     mode = GET_MODE (op0);
5166
5167   /* For some comparisons with 1 and -1, we can convert this to
5168      comparisons with zero.  This will often produce more opportunities for
5169      store-flag insns.  */
5170
5171   switch (code)
5172     {
5173     case LT:
5174       if (op1 == const1_rtx)
5175         op1 = const0_rtx, code = LE;
5176       break;
5177     case LE:
5178       if (op1 == constm1_rtx)
5179         op1 = const0_rtx, code = LT;
5180       break;
5181     case GE:
5182       if (op1 == const1_rtx)
5183         op1 = const0_rtx, code = GT;
5184       break;
5185     case GT:
5186       if (op1 == constm1_rtx)
5187         op1 = const0_rtx, code = GE;
5188       break;
5189     case GEU:
5190       if (op1 == const1_rtx)
5191         op1 = const0_rtx, code = NE;
5192       break;
5193     case LTU:
5194       if (op1 == const1_rtx)
5195         op1 = const0_rtx, code = EQ;
5196       break;
5197     default:
5198       break;
5199     }
5200
5201   /* If we are comparing a double-word integer with zero or -1, we can
5202      convert the comparison into one involving a single word.  */
5203   if (GET_MODE_BITSIZE (mode) == BITS_PER_WORD * 2
5204       && GET_MODE_CLASS (mode) == MODE_INT
5205       && (!MEM_P (op0) || ! MEM_VOLATILE_P (op0)))
5206     {
5207       if ((code == EQ || code == NE)
5208           && (op1 == const0_rtx || op1 == constm1_rtx))
5209         {
5210           rtx op00, op01, op0both;
5211
5212           /* Do a logical OR or AND of the two words and compare the
5213              result.  */
5214           op00 = simplify_gen_subreg (word_mode, op0, mode, 0);
5215           op01 = simplify_gen_subreg (word_mode, op0, mode, UNITS_PER_WORD);
5216           op0both = expand_binop (word_mode,
5217                                   op1 == const0_rtx ? ior_optab : and_optab,
5218                                   op00, op01, NULL_RTX, unsignedp,
5219                                   OPTAB_DIRECT);
5220
5221           if (op0both != 0)
5222             return emit_store_flag (target, code, op0both, op1, word_mode,
5223                                     unsignedp, normalizep);
5224         }
5225       else if ((code == LT || code == GE) && op1 == const0_rtx)
5226         {
5227           rtx op0h;
5228
5229           /* If testing the sign bit, can just test on high word.  */
5230           op0h = simplify_gen_subreg (word_mode, op0, mode,
5231                                       subreg_highpart_offset (word_mode,
5232                                                               mode));
5233           return emit_store_flag (target, code, op0h, op1, word_mode,
5234                                   unsignedp, normalizep);
5235         }
5236     }
5237
5238   /* If this is A < 0 or A >= 0, we can do this by taking the ones
5239      complement of A (for GE) and shifting the sign bit to the low bit.  */
5240   if (op1 == const0_rtx && (code == LT || code == GE)
5241       && GET_MODE_CLASS (mode) == MODE_INT
5242       && (normalizep || STORE_FLAG_VALUE == 1
5243           || (GET_MODE_BITSIZE (mode) <= HOST_BITS_PER_WIDE_INT
5244               && ((STORE_FLAG_VALUE & GET_MODE_MASK (mode))
5245                   == ((unsigned HOST_WIDE_INT) 1
5246                       << (GET_MODE_BITSIZE (mode) - 1))))))
5247     {
5248       subtarget = target;
5249
5250       /* If the result is to be wider than OP0, it is best to convert it
5251          first.  If it is to be narrower, it is *incorrect* to convert it
5252          first.  */
5253       if (GET_MODE_SIZE (target_mode) > GET_MODE_SIZE (mode))
5254         {
5255           op0 = convert_modes (target_mode, mode, op0, 0);
5256           mode = target_mode;
5257         }
5258
5259       if (target_mode != mode)
5260         subtarget = 0;
5261
5262       if (code == GE)
5263         op0 = expand_unop (mode, one_cmpl_optab, op0,
5264                            ((STORE_FLAG_VALUE == 1 || normalizep)
5265                             ? 0 : subtarget), 0);
5266
5267       if (STORE_FLAG_VALUE == 1 || normalizep)
5268         /* If we are supposed to produce a 0/1 value, we want to do
5269            a logical shift from the sign bit to the low-order bit; for
5270            a -1/0 value, we do an arithmetic shift.  */
5271         op0 = expand_shift (RSHIFT_EXPR, mode, op0,
5272                             size_int (GET_MODE_BITSIZE (mode) - 1),
5273                             subtarget, normalizep != -1);
5274
5275       if (mode != target_mode)
5276         op0 = convert_modes (target_mode, mode, op0, 0);
5277
5278       return op0;
5279     }
5280
5281   icode = setcc_gen_code[(int) code];
5282
5283   if (icode != CODE_FOR_nothing)
5284     {
5285       insn_operand_predicate_fn pred;
5286
5287       /* We think we may be able to do this with a scc insn.  Emit the
5288          comparison and then the scc insn.  */
5289
5290       do_pending_stack_adjust ();
5291       last = get_last_insn ();
5292
5293       comparison
5294         = compare_from_rtx (op0, op1, code, unsignedp, mode, NULL_RTX);
5295       if (CONSTANT_P (comparison))
5296         {
5297           switch (GET_CODE (comparison))
5298             {
5299             case CONST_INT:
5300               if (comparison == const0_rtx)
5301                 return const0_rtx;
5302               break;
5303               
5304 #ifdef FLOAT_STORE_FLAG_VALUE
5305             case CONST_DOUBLE:
5306               if (comparison == CONST0_RTX (GET_MODE (comparison)))
5307                 return const0_rtx;
5308               break;
5309 #endif
5310             default:
5311               gcc_unreachable ();
5312             }
5313           
5314           if (normalizep == 1)
5315             return const1_rtx;
5316           if (normalizep == -1)
5317             return constm1_rtx;
5318           return const_true_rtx;
5319         }
5320
5321       /* The code of COMPARISON may not match CODE if compare_from_rtx
5322          decided to swap its operands and reverse the original code.
5323
5324          We know that compare_from_rtx returns either a CONST_INT or
5325          a new comparison code, so it is safe to just extract the
5326          code from COMPARISON.  */
5327       code = GET_CODE (comparison);
5328
5329       /* Get a reference to the target in the proper mode for this insn.  */
5330       compare_mode = insn_data[(int) icode].operand[0].mode;
5331       subtarget = target;
5332       pred = insn_data[(int) icode].operand[0].predicate;
5333       if (optimize || ! (*pred) (subtarget, compare_mode))
5334         subtarget = gen_reg_rtx (compare_mode);
5335
5336       pattern = GEN_FCN (icode) (subtarget);
5337       if (pattern)
5338         {
5339           emit_insn (pattern);
5340           return emit_store_flag_1 (target, subtarget, compare_mode,
5341                                     normalizep);
5342         }
5343     }
5344   else
5345     {
5346       /* We don't have an scc insn, so try a cstore insn.  */
5347
5348       for (compare_mode = mode; compare_mode != VOIDmode;
5349            compare_mode = GET_MODE_WIDER_MODE (compare_mode))
5350         {
5351           icode = optab_handler (cstore_optab, compare_mode)->insn_code;
5352           if (icode != CODE_FOR_nothing)
5353             break;
5354         }
5355
5356       if (icode != CODE_FOR_nothing)
5357         {
5358           enum machine_mode result_mode
5359             = insn_data[(int) icode].operand[0].mode;
5360           rtx cstore_op0 = op0;
5361           rtx cstore_op1 = op1;
5362
5363           do_pending_stack_adjust ();
5364           last = get_last_insn ();
5365
5366           if (compare_mode != mode)
5367             {
5368               cstore_op0 = convert_modes (compare_mode, mode, cstore_op0,
5369                                           unsignedp);
5370               cstore_op1 = convert_modes (compare_mode, mode, cstore_op1,
5371                                           unsignedp);
5372             }
5373           
5374           if (!insn_data[(int) icode].operand[2].predicate (cstore_op0,
5375                                                             compare_mode))
5376             cstore_op0 = copy_to_mode_reg (compare_mode, cstore_op0);
5377
5378           if (!insn_data[(int) icode].operand[3].predicate (cstore_op1,
5379                                                             compare_mode))
5380             cstore_op1 = copy_to_mode_reg (compare_mode, cstore_op1);
5381
5382           comparison = gen_rtx_fmt_ee (code, result_mode, cstore_op0,
5383                                        cstore_op1);
5384           subtarget = target;
5385
5386           if (optimize || !(insn_data[(int) icode].operand[0].predicate
5387                             (subtarget, result_mode)))
5388             subtarget = gen_reg_rtx (result_mode);
5389
5390           pattern = GEN_FCN (icode) (subtarget, comparison, cstore_op0,
5391                                      cstore_op1);
5392
5393           if (pattern)
5394             {
5395               emit_insn (pattern);
5396               return emit_store_flag_1 (target, subtarget, result_mode,
5397                                         normalizep);
5398             }
5399         }
5400     }
5401
5402   delete_insns_since (last);
5403
5404   /* If optimizing, use different pseudo registers for each insn, instead
5405      of reusing the same pseudo.  This leads to better CSE, but slows
5406      down the compiler, since there are more pseudos */
5407   subtarget = (!optimize
5408                && (target_mode == mode)) ? target : NULL_RTX;
5409
5410   /* If we reached here, we can't do this with a scc insn.  However, there
5411      are some comparisons that can be done directly.  For example, if
5412      this is an equality comparison of integers, we can try to exclusive-or
5413      (or subtract) the two operands and use a recursive call to try the
5414      comparison with zero.  Don't do any of these cases if branches are
5415      very cheap.  */
5416
5417   if (BRANCH_COST (optimize_insn_for_speed_p (),
5418                    false) > 0
5419       && GET_MODE_CLASS (mode) == MODE_INT && (code == EQ || code == NE)
5420       && op1 != const0_rtx)
5421     {
5422       tem = expand_binop (mode, xor_optab, op0, op1, subtarget, 1,
5423                           OPTAB_WIDEN);
5424
5425       if (tem == 0)
5426         tem = expand_binop (mode, sub_optab, op0, op1, subtarget, 1,
5427                             OPTAB_WIDEN);
5428       if (tem != 0)
5429         tem = emit_store_flag (target, code, tem, const0_rtx,
5430                                mode, unsignedp, normalizep);
5431       if (tem == 0)
5432         delete_insns_since (last);
5433       return tem;
5434     }
5435
5436   /* Some other cases we can do are EQ, NE, LE, and GT comparisons with
5437      the constant zero.  Reject all other comparisons at this point.  Only
5438      do LE and GT if branches are expensive since they are expensive on
5439      2-operand machines.  */
5440
5441   if (BRANCH_COST (optimize_insn_for_speed_p (),
5442                    false) == 0
5443       || GET_MODE_CLASS (mode) != MODE_INT || op1 != const0_rtx
5444       || (code != EQ && code != NE
5445           && (BRANCH_COST (optimize_insn_for_speed_p (),
5446                            false) <= 1 || (code != LE && code != GT))))
5447     return 0;
5448
5449   /* See what we need to return.  We can only return a 1, -1, or the
5450      sign bit.  */
5451
5452   if (normalizep == 0)
5453     {
5454       if (STORE_FLAG_VALUE == 1 || STORE_FLAG_VALUE == -1)
5455         normalizep = STORE_FLAG_VALUE;
5456
5457       else if (GET_MODE_BITSIZE (mode) <= HOST_BITS_PER_WIDE_INT
5458                && ((STORE_FLAG_VALUE & GET_MODE_MASK (mode))
5459                    == (unsigned HOST_WIDE_INT) 1 << (GET_MODE_BITSIZE (mode) - 1)))
5460         ;
5461       else
5462         return 0;
5463     }
5464
5465   /* Try to put the result of the comparison in the sign bit.  Assume we can't
5466      do the necessary operation below.  */
5467
5468   tem = 0;
5469
5470   /* To see if A <= 0, compute (A | (A - 1)).  A <= 0 iff that result has
5471      the sign bit set.  */
5472
5473   if (code == LE)
5474     {
5475       /* This is destructive, so SUBTARGET can't be OP0.  */
5476       if (rtx_equal_p (subtarget, op0))
5477         subtarget = 0;
5478
5479       tem = expand_binop (mode, sub_optab, op0, const1_rtx, subtarget, 0,
5480                           OPTAB_WIDEN);
5481       if (tem)
5482         tem = expand_binop (mode, ior_optab, op0, tem, subtarget, 0,
5483                             OPTAB_WIDEN);
5484     }
5485
5486   /* To see if A > 0, compute (((signed) A) << BITS) - A, where BITS is the
5487      number of bits in the mode of OP0, minus one.  */
5488
5489   if (code == GT)
5490     {
5491       if (rtx_equal_p (subtarget, op0))
5492         subtarget = 0;
5493
5494       tem = expand_shift (RSHIFT_EXPR, mode, op0,
5495                           size_int (GET_MODE_BITSIZE (mode) - 1),
5496                           subtarget, 0);
5497       tem = expand_binop (mode, sub_optab, tem, op0, subtarget, 0,
5498                           OPTAB_WIDEN);
5499     }
5500
5501   if (code == EQ || code == NE)
5502     {
5503       /* For EQ or NE, one way to do the comparison is to apply an operation
5504          that converts the operand into a positive number if it is nonzero
5505          or zero if it was originally zero.  Then, for EQ, we subtract 1 and
5506          for NE we negate.  This puts the result in the sign bit.  Then we
5507          normalize with a shift, if needed.
5508
5509          Two operations that can do the above actions are ABS and FFS, so try
5510          them.  If that doesn't work, and MODE is smaller than a full word,
5511          we can use zero-extension to the wider mode (an unsigned conversion)
5512          as the operation.  */
5513
5514       /* Note that ABS doesn't yield a positive number for INT_MIN, but
5515          that is compensated by the subsequent overflow when subtracting
5516          one / negating.  */
5517
5518       if (optab_handler (abs_optab, mode)->insn_code != CODE_FOR_nothing)
5519         tem = expand_unop (mode, abs_optab, op0, subtarget, 1);
5520       else if (optab_handler (ffs_optab, mode)->insn_code != CODE_FOR_nothing)
5521         tem = expand_unop (mode, ffs_optab, op0, subtarget, 1);
5522       else if (GET_MODE_SIZE (mode) < UNITS_PER_WORD)
5523         {
5524           tem = convert_modes (word_mode, mode, op0, 1);
5525           mode = word_mode;
5526         }
5527
5528       if (tem != 0)
5529         {
5530           if (code == EQ)
5531             tem = expand_binop (mode, sub_optab, tem, const1_rtx, subtarget,
5532                                 0, OPTAB_WIDEN);
5533           else
5534             tem = expand_unop (mode, neg_optab, tem, subtarget, 0);
5535         }
5536
5537       /* If we couldn't do it that way, for NE we can "or" the two's complement
5538          of the value with itself.  For EQ, we take the one's complement of
5539          that "or", which is an extra insn, so we only handle EQ if branches
5540          are expensive.  */
5541
5542       if (tem == 0
5543           && (code == NE
5544               || BRANCH_COST (optimize_insn_for_speed_p (),
5545                               false) > 1))
5546         {
5547           if (rtx_equal_p (subtarget, op0))
5548             subtarget = 0;
5549
5550           tem = expand_unop (mode, neg_optab, op0, subtarget, 0);
5551           tem = expand_binop (mode, ior_optab, tem, op0, subtarget, 0,
5552                               OPTAB_WIDEN);
5553
5554           if (tem && code == EQ)
5555             tem = expand_unop (mode, one_cmpl_optab, tem, subtarget, 0);
5556         }
5557     }
5558
5559   if (tem && normalizep)
5560     tem = expand_shift (RSHIFT_EXPR, mode, tem,
5561                         size_int (GET_MODE_BITSIZE (mode) - 1),
5562                         subtarget, normalizep == 1);
5563
5564   if (tem)
5565     {
5566       if (GET_MODE (tem) != target_mode)
5567         {
5568           convert_move (target, tem, 0);
5569           tem = target;
5570         }
5571       else if (!subtarget)
5572         {
5573           emit_move_insn (target, tem);
5574           tem = target;
5575         }
5576     }
5577   else
5578     delete_insns_since (last);
5579
5580   return tem;
5581 }
5582
5583 /* Like emit_store_flag, but always succeeds.  */
5584
5585 rtx
5586 emit_store_flag_force (rtx target, enum rtx_code code, rtx op0, rtx op1,
5587                        enum machine_mode mode, int unsignedp, int normalizep)
5588 {
5589   rtx tem, label;
5590
5591   /* First see if emit_store_flag can do the job.  */
5592   tem = emit_store_flag (target, code, op0, op1, mode, unsignedp, normalizep);
5593   if (tem != 0)
5594     return tem;
5595
5596   if (normalizep == 0)
5597     normalizep = 1;
5598
5599   /* If this failed, we have to do this with set/compare/jump/set code.  */
5600
5601   if (!REG_P (target)
5602       || reg_mentioned_p (target, op0) || reg_mentioned_p (target, op1))
5603     target = gen_reg_rtx (GET_MODE (target));
5604
5605   emit_move_insn (target, const1_rtx);
5606   label = gen_label_rtx ();
5607   do_compare_rtx_and_jump (op0, op1, code, unsignedp, mode, NULL_RTX,
5608                            NULL_RTX, label);
5609
5610   emit_move_insn (target, const0_rtx);
5611   emit_label (label);
5612
5613   return target;
5614 }
5615 \f
5616 /* Perform possibly multi-word comparison and conditional jump to LABEL
5617    if ARG1 OP ARG2 true where ARG1 and ARG2 are of mode MODE.  This is
5618    now a thin wrapper around do_compare_rtx_and_jump.  */
5619
5620 static void
5621 do_cmp_and_jump (rtx arg1, rtx arg2, enum rtx_code op, enum machine_mode mode,
5622                  rtx label)
5623 {
5624   int unsignedp = (op == LTU || op == LEU || op == GTU || op == GEU);
5625   do_compare_rtx_and_jump (arg1, arg2, op, unsignedp, mode,
5626                            NULL_RTX, NULL_RTX, label);
5627 }