i960 cgen simulator support.
[platform/upstream/binutils.git] / gdb / ax-gdb.c
1 /* GDB-specific functions for operating on agent expressions
2    Copyright 1998 Free Software Foundation, Inc.
3
4 This file is part of GDB.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
19
20 /* $Id$ */
21
22 #include "defs.h"
23 #include "symtab.h"
24 #include "symfile.h"
25 #include "gdbtypes.h"
26 #include "value.h"
27 #include "expression.h"
28 #include "command.h"
29 #include "gdbcmd.h"
30 #include "frame.h"
31 #include "ax.h"
32 #include "ax-gdb.h"
33
34 /* Probably the best way to read this file is to start with the types
35    and enums in ax-gdb.h, and then look at gen_expr, towards the
36    bottom; that's the main function that looks at the GDB expressions
37    and calls everything else to generate code.
38
39    I'm beginning to wonder whether it wouldn't be nicer to internally
40    generate trees, with types, and then spit out the bytecode in
41    linear form afterwards; we could generate fewer `swap', `ext', and
42    `zero_ext' bytecodes that way; it would make good constant folding
43    easier, too.  But at the moment, I think we should be willing to
44    pay for the simplicity of this code with less-than-optimal bytecode
45    strings.
46
47    Remember, "GBD" stands for "Great Britain, Dammit!"  So be careful.  */ 
48
49
50 \f
51 /* Prototypes for local functions. */
52
53 /* There's a standard order to the arguments of these functions:
54    union exp_element ** --- pointer into expression
55    struct agent_expr * --- agent expression buffer to generate code into
56    struct axs_value * --- describes value left on top of stack  */
57    
58 static struct value *const_var_ref PARAMS ((struct symbol *var));
59 static struct value *const_expr PARAMS ((union exp_element **pc));
60 static struct value *maybe_const_expr PARAMS ((union exp_element **pc));
61
62 static void gen_traced_pop PARAMS ((struct agent_expr *, struct axs_value *));
63
64 static void gen_sign_extend PARAMS ((struct agent_expr *, struct type *));
65 static void gen_extend PARAMS ((struct agent_expr *, struct type *));
66 static void gen_fetch PARAMS ((struct agent_expr *, struct type *));
67 static void gen_left_shift PARAMS ((struct agent_expr *, int));
68
69
70 static void gen_frame_args_address   PARAMS ((struct agent_expr *));
71 static void gen_frame_locals_address PARAMS ((struct agent_expr *));
72 static void gen_offset PARAMS ((struct agent_expr *ax, int offset));
73 static void gen_sym_offset PARAMS ((struct agent_expr *, struct symbol *));
74 static void gen_var_ref PARAMS ((struct agent_expr *ax,
75                                  struct axs_value *value,
76                                  struct symbol *var));
77
78
79 static void gen_int_literal PARAMS ((struct agent_expr *ax,
80                                      struct axs_value *value,
81                                      LONGEST k, struct type *type));
82
83
84 static void require_rvalue PARAMS ((struct agent_expr *ax,
85                                     struct axs_value *value));
86 static void gen_usual_unary PARAMS ((struct agent_expr *ax,
87                                      struct axs_value *value));
88 static int type_wider_than PARAMS ((struct type *type1,
89                                     struct type *type2));
90 static struct type *max_type PARAMS ((struct type *type1, 
91                                       struct type *type2));
92 static void gen_conversion PARAMS ((struct agent_expr *ax,
93                                     struct type *from,
94                                     struct type *to));
95 static int is_nontrivial_conversion PARAMS ((struct type *from,
96                                              struct type *to));
97 static void gen_usual_arithmetic PARAMS ((struct agent_expr *ax,
98                                           struct axs_value *value1,
99                                           struct axs_value *value2));
100 static void gen_integral_promotions PARAMS ((struct agent_expr *ax,
101                                              struct axs_value *value));
102 static void gen_cast PARAMS ((struct agent_expr *ax,
103                               struct axs_value *value,
104                               struct type *type));
105 static void gen_scale PARAMS ((struct agent_expr *ax,
106                                enum agent_op op,
107                                struct type *type));
108 static void gen_add PARAMS ((struct agent_expr *ax,
109                              struct axs_value *value, 
110                              struct axs_value *value1,
111                              struct axs_value *value2,
112                              char *name));
113 static void gen_sub PARAMS ((struct agent_expr *ax,
114                              struct axs_value *value, 
115                              struct axs_value *value1,
116                              struct axs_value *value2));
117 static void gen_binop PARAMS ((struct agent_expr *ax,
118                                struct axs_value *value,
119                                struct axs_value *value1,
120                                struct axs_value *value2,
121                                enum agent_op op,
122                                enum agent_op op_unsigned,
123                                int may_carry,
124                                char *name));
125 static void gen_logical_not PARAMS ((struct agent_expr *ax,
126                                      struct axs_value *value));
127 static void gen_complement PARAMS ((struct agent_expr *ax,
128                                     struct axs_value *value));
129 static void gen_deref PARAMS ((struct agent_expr *, struct axs_value *));
130 static void gen_address_of PARAMS ((struct agent_expr *, struct axs_value *));
131 static int find_field PARAMS ((struct type *type, char *name));
132 static void gen_bitfield_ref PARAMS ((struct agent_expr *ax,
133                                       struct axs_value *value,
134                                       struct type *type,
135                                       int start, int end));
136 static void gen_struct_ref PARAMS ((struct agent_expr *ax,
137                                     struct axs_value *value,
138                                     char *field,
139                                     char *operator_name,
140                                     char *operand_name));
141 static void gen_repeat PARAMS ((union exp_element **pc,
142                                 struct agent_expr *ax,
143                                 struct axs_value *value));
144 static void gen_sizeof PARAMS ((union exp_element **pc,
145                                 struct agent_expr *ax,
146                                 struct axs_value *value));
147 static void gen_expr PARAMS ((union exp_element **pc,
148                               struct agent_expr *ax,
149                               struct axs_value *value));
150
151 static void print_axs_value PARAMS ((GDB_FILE *f, struct axs_value *value));
152 static void agent_command PARAMS ((char *exp, int from_tty));
153
154 \f
155 /* Detecting constant expressions.  */
156
157 /* If the variable reference at *PC is a constant, return its value.
158    Otherwise, return zero.
159
160    Hey, Wally!  How can a variable reference be a constant?
161
162    Well, Beav, this function really handles the OP_VAR_VALUE operator,
163    not specifically variable references.  GDB uses OP_VAR_VALUE to
164    refer to any kind of symbolic reference: function names, enum
165    elements, and goto labels are all handled through the OP_VAR_VALUE
166    operator, even though they're constants.  It makes sense given the
167    situation.
168
169    Gee, Wally, don'cha wonder sometimes if data representations that
170    subvert commonly accepted definitions of terms in favor of heavily
171    context-specific interpretations are really just a tool of the
172    programming hegemony to preserve their power and exclude the
173    proletariat?  */
174
175 static struct value *
176 const_var_ref (var)
177      struct symbol *var;
178 {
179   struct type *type = SYMBOL_TYPE (var);
180
181   switch (SYMBOL_CLASS (var))
182     {
183     case LOC_CONST:
184       return value_from_longest (type, (LONGEST) SYMBOL_VALUE (var));
185
186     case LOC_LABEL:
187       return value_from_longest (type, (LONGEST) SYMBOL_VALUE_ADDRESS (var));
188
189     default:
190       return 0;
191     }
192 }
193
194
195 /* If the expression starting at *PC has a constant value, return it.
196    Otherwise, return zero.  If we return a value, then *PC will be
197    advanced to the end of it.  If we return zero, *PC could be
198    anywhere.  */
199 static struct value *
200 const_expr (pc)
201      union exp_element **pc;
202 {
203   enum exp_opcode op = (*pc)->opcode;
204   struct value *v1;
205
206   switch (op)
207     {
208     case OP_LONG:
209       {
210         struct type *type = (*pc)[1].type;
211         LONGEST k = (*pc)[2].longconst;
212         (*pc) += 4;
213         return value_from_longest (type, k);
214       }
215
216     case OP_VAR_VALUE:
217       {
218         struct value *v = const_var_ref ((*pc)[2].symbol);
219         (*pc) += 4;
220         return v;
221       }
222
223     /* We could add more operators in here.  */
224
225     case UNOP_NEG:
226       (*pc)++;
227       v1 = const_expr (pc);
228       if (v1)
229         return value_neg (v1);
230       else
231         return 0;
232
233     default:
234       return 0;
235     }
236 }
237
238
239 /* Like const_expr, but guarantee also that *PC is undisturbed if the
240    expression is not constant.  */
241 static struct value *
242 maybe_const_expr (pc)
243      union exp_element **pc;
244 {
245   union exp_element *tentative_pc = *pc;
246   struct value *v = const_expr (&tentative_pc);
247
248   /* If we got a value, then update the real PC.  */
249   if (v)
250     *pc = tentative_pc;
251  
252   return v;
253 }
254
255 \f
256 /* Generating bytecode from GDB expressions: general assumptions */
257
258 /* Here are a few general assumptions made throughout the code; if you
259    want to make a change that contradicts one of these, then you'd
260    better scan things pretty thoroughly.
261
262    - We assume that all values occupy one stack element.  For example,
263      sometimes we'll swap to get at the left argument to a binary
264      operator.  If we decide that void values should occupy no stack
265      elements, or that synthetic arrays (whose size is determined at
266      run time, created by the `@' operator) should occupy two stack
267      elements (address and length), then this will cause trouble.
268
269    - We assume the stack elements are infinitely wide, and that we
270      don't have to worry what happens if the user requests an
271      operation that is wider than the actual interpreter's stack.
272      That is, it's up to the interpreter to handle directly all the
273      integer widths the user has access to.  (Woe betide the language
274      with bignums!)
275
276    - We don't support side effects.  Thus, we don't have to worry about
277      GCC's generalized lvalues, function calls, etc.
278
279    - We don't support floating point.  Many places where we switch on
280      some type don't bother to include cases for floating point; there
281      may be even more subtle ways this assumption exists.  For
282      example, the arguments to % must be integers.
283
284    - We assume all subexpressions have a static, unchanging type.  If
285      we tried to support convenience variables, this would be a
286      problem.
287
288    - All values on the stack should always be fully zero- or
289      sign-extended.
290
291      (I wasn't sure whether to choose this or its opposite --- that
292      only addresses are assumed extended --- but it turns out that
293      neither convention completely eliminates spurious extend
294      operations (if everything is always extended, then you have to
295      extend after add, because it could overflow; if nothing is
296      extended, then you end up producing extends whenever you change
297      sizes), and this is simpler.)  */
298
299 \f
300 /* Generating bytecode from GDB expressions: the `trace' kludge  */
301
302 /* The compiler in this file is a general-purpose mechanism for
303    translating GDB expressions into bytecode.  One ought to be able to
304    find a million and one uses for it.
305
306    However, at the moment it is HOPELESSLY BRAIN-DAMAGED for the sake
307    of expediency.  Let he who is without sin cast the first stone.
308
309    For the data tracing facility, we need to insert `trace' bytecodes
310    before each data fetch; this records all the memory that the
311    expression touches in the course of evaluation, so that memory will
312    be available when the user later tries to evaluate the expression
313    in GDB.
314
315    This should be done (I think) in a post-processing pass, that walks
316    an arbitrary agent expression and inserts `trace' operations at the
317    appropriate points.  But it's much faster to just hack them
318    directly into the code.  And since we're in a crunch, that's what
319    I've done.
320
321    Setting the flag trace_kludge to non-zero enables the code that
322    emits the trace bytecodes at the appropriate points.  */
323 static int trace_kludge;
324
325 /* Trace the lvalue on the stack, if it needs it.  In either case, pop
326    the value.  Useful on the left side of a comma, and at the end of
327    an expression being used for tracing.  */
328 static void
329 gen_traced_pop (ax, value)
330      struct agent_expr *ax;
331      struct axs_value *value;
332 {
333   if (trace_kludge)
334     switch (value->kind)
335       {
336       case axs_rvalue:
337         /* We don't trace rvalues, just the lvalues necessary to
338            produce them.  So just dispose of this value.  */
339         ax_simple (ax, aop_pop);
340         break;
341
342       case axs_lvalue_memory:
343         {
344           int length = TYPE_LENGTH (value->type);
345
346           /* There's no point in trying to use a trace_quick bytecode
347              here, since "trace_quick SIZE pop" is three bytes, whereas
348              "const8 SIZE trace" is also three bytes, does the same
349              thing, and the simplest code which generates that will also
350              work correctly for objects with large sizes.  */
351           ax_const_l (ax, length);
352           ax_simple (ax, aop_trace);
353         }
354       break;
355
356       case axs_lvalue_register:
357         /* We need to mention the register somewhere in the bytecode,
358            so ax_reqs will pick it up and add it to the mask of
359            registers used.  */
360         ax_reg (ax, value->u.reg);
361         ax_simple (ax, aop_pop);
362         break;
363       }
364   else
365     /* If we're not tracing, just pop the value.  */
366     ax_simple (ax, aop_pop);
367 }
368
369
370 \f
371 /* Generating bytecode from GDB expressions: helper functions */
372
373 /* Assume that the lower bits of the top of the stack is a value of
374    type TYPE, and the upper bits are zero.  Sign-extend if necessary.  */
375 static void
376 gen_sign_extend (ax, type)
377      struct agent_expr *ax;
378      struct type *type;
379 {
380   /* Do we need to sign-extend this?  */
381   if (! TYPE_UNSIGNED (type))
382     ax_ext (ax, type->length * TARGET_CHAR_BIT);
383 }
384
385
386 /* Assume the lower bits of the top of the stack hold a value of type
387    TYPE, and the upper bits are garbage.  Sign-extend or truncate as
388    needed.  */
389 static void
390 gen_extend (ax, type)
391      struct agent_expr *ax;
392      struct type *type;
393 {
394   int bits = type->length * TARGET_CHAR_BIT;
395   /* I just had to.  */
396   ((TYPE_UNSIGNED (type) ? ax_zero_ext : ax_ext) (ax, bits));
397 }
398
399
400 /* Assume that the top of the stack contains a value of type "pointer
401    to TYPE"; generate code to fetch its value.  Note that TYPE is the
402    target type, not the pointer type.  */
403 static void
404 gen_fetch (ax, type)
405      struct agent_expr *ax;
406      struct type *type;
407 {
408   if (trace_kludge)
409     {
410       /* Record the area of memory we're about to fetch.  */
411       ax_trace_quick (ax, TYPE_LENGTH (type));
412     }
413
414   switch (type->code)
415     {
416     case TYPE_CODE_PTR:
417     case TYPE_CODE_ENUM:
418     case TYPE_CODE_INT:
419     case TYPE_CODE_CHAR:
420       /* It's a scalar value, so we know how to dereference it.  How
421          many bytes long is it?  */
422       switch (type->length)
423         {
424         case 8  / TARGET_CHAR_BIT: ax_simple (ax, aop_ref8 ); break;
425         case 16 / TARGET_CHAR_BIT: ax_simple (ax, aop_ref16); break;
426         case 32 / TARGET_CHAR_BIT: ax_simple (ax, aop_ref32); break;
427         case 64 / TARGET_CHAR_BIT: ax_simple (ax, aop_ref64); break;
428
429           /* Either our caller shouldn't have asked us to dereference
430              that pointer (other code's fault), or we're not
431              implementing something we should be (this code's fault).
432              In any case, it's a bug the user shouldn't see.  */
433         default:
434           error ("GDB bug: ax-gdb.c (gen_fetch): strange size");
435         }
436
437       gen_sign_extend (ax, type);
438       break;
439
440     default:
441       /* Either our caller shouldn't have asked us to dereference that
442          pointer (other code's fault), or we're not implementing
443          something we should be (this code's fault).  In any case,
444          it's a bug the user shouldn't see.  */
445       error ("GDB bug: ax-gdb.c (gen_fetch): bad type code");
446     }
447 }
448
449
450 /* Generate code to left shift the top of the stack by DISTANCE bits, or
451    right shift it by -DISTANCE bits if DISTANCE < 0.  This generates
452    unsigned (logical) right shifts.  */
453 static void
454 gen_left_shift (ax, distance)
455      struct agent_expr *ax;
456      int distance;
457 {
458   if (distance > 0)
459     {
460       ax_const_l (ax, distance);
461       ax_simple (ax, aop_lsh);
462     }
463   else if (distance < 0)
464     {
465       ax_const_l (ax, -distance);
466       ax_simple (ax, aop_rsh_unsigned);
467     }
468 }
469
470
471 \f
472 /* Generating bytecode from GDB expressions: symbol references */
473
474 /* Generate code to push the base address of the argument portion of
475    the top stack frame.  */
476 static void
477 gen_frame_args_address (ax)
478      struct agent_expr *ax;
479 {
480   long frame_reg, frame_offset;
481
482   TARGET_VIRTUAL_FRAME_POINTER (ax->scope, &frame_reg, &frame_offset);
483   ax_reg     (ax, frame_reg);
484   gen_offset (ax, frame_offset);
485 }
486
487
488 /* Generate code to push the base address of the locals portion of the
489    top stack frame.  */
490 static void
491 gen_frame_locals_address (ax)
492      struct agent_expr *ax;
493 {
494   long frame_reg, frame_offset;
495
496   TARGET_VIRTUAL_FRAME_POINTER (ax->scope, &frame_reg, &frame_offset);
497   ax_reg     (ax, frame_reg);
498   gen_offset (ax, frame_offset);
499 }
500
501
502 /* Generate code to add OFFSET to the top of the stack.  Try to
503    generate short and readable code.  We use this for getting to
504    variables on the stack, and structure members.  If we were
505    programming in ML, it would be clearer why these are the same
506    thing.  */
507 static void
508 gen_offset (ax, offset)
509      struct agent_expr *ax;
510      int offset;
511 {
512   /* It would suffice to simply push the offset and add it, but this
513      makes it easier to read positive and negative offsets in the
514      bytecode.  */
515   if (offset > 0)
516     {
517       ax_const_l (ax, offset);
518       ax_simple (ax, aop_add);
519     }
520   else if (offset < 0)
521     {
522       ax_const_l (ax, -offset);
523       ax_simple (ax, aop_sub);
524     }
525 }
526
527
528 /* In many cases, a symbol's value is the offset from some other
529    address (stack frame, base register, etc.)  Generate code to add
530    VAR's value to the top of the stack.  */
531 static void
532 gen_sym_offset (ax, var)
533      struct agent_expr *ax;
534      struct symbol *var;
535 {
536   gen_offset (ax, SYMBOL_VALUE (var));
537 }
538
539
540 /* Generate code for a variable reference to AX.  The variable is the
541    symbol VAR.  Set VALUE to describe the result.  */
542
543 static void
544 gen_var_ref (ax, value, var)
545      struct agent_expr *ax;
546      struct axs_value *value;
547      struct symbol *var;
548 {
549   /* Dereference any typedefs. */
550   value->type = check_typedef (SYMBOL_TYPE (var));
551
552   /* I'm imitating the code in read_var_value.  */
553   switch (SYMBOL_CLASS (var))
554     {
555     case LOC_CONST:             /* A constant, like an enum value.  */
556       ax_const_l (ax, (LONGEST) SYMBOL_VALUE (var));
557       value->kind = axs_rvalue;
558       break;
559
560     case LOC_LABEL:             /* A goto label, being used as a value.  */
561       ax_const_l (ax, (LONGEST) SYMBOL_VALUE_ADDRESS (var));
562       value->kind = axs_rvalue;
563       break;
564
565     case LOC_CONST_BYTES:
566       error ("GDB bug: ax-gdb.c (gen_var_ref): LOC_CONST_BYTES symbols are not supported");
567
568       /* Variable at a fixed location in memory.  Easy.  */
569     case LOC_STATIC:
570       /* Push the address of the variable.  */
571       ax_const_l (ax, SYMBOL_VALUE_ADDRESS (var));
572       value->kind = axs_lvalue_memory;
573       break;
574
575     case LOC_ARG:               /* var lives in argument area of frame */
576       gen_frame_args_address (ax);
577       gen_sym_offset (ax, var);
578       value->kind = axs_lvalue_memory;
579       break;
580
581     case LOC_REF_ARG:           /* As above, but the frame slot really
582                                    holds the address of the variable.  */
583       gen_frame_args_address (ax);
584       gen_sym_offset (ax, var);
585       /* Don't assume any particular pointer size.  */
586       gen_fetch (ax, lookup_pointer_type (builtin_type_void));
587       value->kind = axs_lvalue_memory;
588       break;
589
590     case LOC_LOCAL:             /* var lives in locals area of frame */
591     case LOC_LOCAL_ARG:
592       gen_frame_locals_address (ax);
593       gen_sym_offset (ax, var);
594       value->kind = axs_lvalue_memory;
595       break;
596
597     case LOC_BASEREG:           /* relative to some base register */
598     case LOC_BASEREG_ARG:
599       ax_reg (ax, SYMBOL_BASEREG (var));
600       gen_sym_offset (ax, var);
601       value->kind = axs_lvalue_memory;
602       break;
603
604     case LOC_TYPEDEF:
605       error ("Cannot compute value of typedef `%s'.",
606              SYMBOL_SOURCE_NAME (var));
607       break;
608
609     case LOC_BLOCK:
610       ax_const_l (ax, BLOCK_START (SYMBOL_BLOCK_VALUE (var)));
611       value->kind = axs_rvalue;
612       break;
613
614     case LOC_REGISTER:
615     case LOC_REGPARM:
616       /* Don't generate any code at all; in the process of treating
617          this as an lvalue or rvalue, the caller will generate the
618          right code.  */
619       value->kind = axs_lvalue_register;
620       value->u.reg = SYMBOL_VALUE (var);
621       break;
622
623       /* A lot like LOC_REF_ARG, but the pointer lives directly in a
624          register, not on the stack.  Simpler than LOC_REGISTER and
625          LOC_REGPARM, because it's just like any other case where the
626          thing has a real address.  */
627     case LOC_REGPARM_ADDR:
628       ax_reg (ax, SYMBOL_VALUE (var));
629       value->kind = axs_lvalue_memory;
630       break;
631
632     case LOC_UNRESOLVED:
633       {
634         struct minimal_symbol *msym 
635           = lookup_minimal_symbol (SYMBOL_NAME (var), NULL, NULL);
636         if (! msym)
637           error ("Couldn't resolve symbol `%s'.", SYMBOL_SOURCE_NAME (var));
638         
639         /* Push the address of the variable.  */
640         ax_const_l (ax, SYMBOL_VALUE_ADDRESS (msym));
641         value->kind = axs_lvalue_memory;
642       }
643     break;
644
645     case LOC_OPTIMIZED_OUT:
646       error ("The variable `%s' has been optimized out.",
647              SYMBOL_SOURCE_NAME (var));
648       break;
649
650     default:
651       error ("Cannot find value of botched symbol `%s'.",
652              SYMBOL_SOURCE_NAME (var));
653       break;
654     }
655 }
656
657
658 \f
659 /* Generating bytecode from GDB expressions: literals */
660
661 static void
662 gen_int_literal (ax, value, k, type)
663      struct agent_expr *ax;
664      struct axs_value *value;
665      LONGEST k;
666      struct type *type;
667 {
668   ax_const_l (ax, k);
669   value->kind = axs_rvalue;
670   value->type = type;
671 }
672
673
674 \f
675 /* Generating bytecode from GDB expressions: unary conversions, casts */
676
677 /* Take what's on the top of the stack (as described by VALUE), and
678    try to make an rvalue out of it.  Signal an error if we can't do
679    that.  */
680 static void
681 require_rvalue (ax, value)
682      struct agent_expr *ax;
683      struct axs_value *value;
684 {
685   switch (value->kind)
686     {
687     case axs_rvalue:
688       /* It's already an rvalue.  */
689       break;
690
691     case axs_lvalue_memory:
692       /* The top of stack is the address of the object.  Dereference.  */
693       gen_fetch (ax, value->type);
694       break;
695
696     case axs_lvalue_register:
697       /* There's nothing on the stack, but value->u.reg is the
698          register number containing the value.
699
700          When we add floating-point support, this is going to have to
701          change.  What about SPARC register pairs, for example?  */
702       ax_reg (ax, value->u.reg);
703       gen_extend (ax, value->type);
704       break;
705     }
706
707   value->kind = axs_rvalue;
708 }
709
710
711 /* Assume the top of the stack is described by VALUE, and perform the
712    usual unary conversions.  This is motivated by ANSI 6.2.2, but of
713    course GDB expressions are not ANSI; they're the mishmash union of
714    a bunch of languages.  Rah.
715
716    NOTE!  This function promises to produce an rvalue only when the
717    incoming value is of an appropriate type.  In other words, the
718    consumer of the value this function produces may assume the value
719    is an rvalue only after checking its type.
720
721    The immediate issue is that if the user tries to use a structure or
722    union as an operand of, say, the `+' operator, we don't want to try
723    to convert that structure to an rvalue; require_rvalue will bomb on
724    structs and unions.  Rather, we want to simply pass the struct
725    lvalue through unchanged, and let `+' raise an error.  */
726
727 static void
728 gen_usual_unary (ax, value)
729      struct agent_expr *ax;
730      struct axs_value *value;
731 {
732   /* We don't have to generate any code for the usual integral
733      conversions, since values are always represented as full-width on
734      the stack.  Should we tweak the type?  */
735
736   /* Some types require special handling.  */
737   switch (value->type->code)
738     {
739       /* Functions get converted to a pointer to the function.  */
740     case TYPE_CODE_FUNC:
741       value->type = lookup_pointer_type (value->type);
742       value->kind = axs_rvalue; /* Should always be true, but just in case.  */
743       break;
744
745       /* Arrays get converted to a pointer to their first element, and
746          are no longer an lvalue.  */
747     case TYPE_CODE_ARRAY:
748       {
749         struct type *elements = TYPE_TARGET_TYPE (value->type);
750         value->type = lookup_pointer_type (elements);
751         value->kind = axs_rvalue;
752         /* We don't need to generate any code; the address of the array
753            is also the address of its first element.  */
754       }
755     break;
756
757     /* Don't try to convert structures and unions to rvalues.  Let the
758        consumer signal an error.  */
759     case TYPE_CODE_STRUCT:
760     case TYPE_CODE_UNION:
761       return;
762
763       /* If the value is an enum, call it an integer.  */
764     case TYPE_CODE_ENUM:
765       value->type = builtin_type_int;
766       break;
767     }
768
769   /* If the value is an lvalue, dereference it.  */
770   require_rvalue (ax, value);
771 }
772
773
774 /* Return non-zero iff the type TYPE1 is considered "wider" than the
775    type TYPE2, according to the rules described in gen_usual_arithmetic.  */
776 static int
777 type_wider_than (type1, type2)
778      struct type *type1, *type2;
779 {
780   return (TYPE_LENGTH (type1) > TYPE_LENGTH (type2)
781           || (TYPE_LENGTH (type1) == TYPE_LENGTH (type2)
782               && TYPE_UNSIGNED (type1)
783               && ! TYPE_UNSIGNED (type2)));
784 }
785
786
787 /* Return the "wider" of the two types TYPE1 and TYPE2.  */
788 static struct type *
789 max_type (type1, type2)
790      struct type *type1, *type2;
791 {
792   return type_wider_than (type1, type2) ? type1 : type2;
793 }
794
795
796 /* Generate code to convert a scalar value of type FROM to type TO.  */
797 static void
798 gen_conversion (ax, from, to)
799      struct agent_expr *ax;
800      struct type *from, *to;
801 {
802   /* Perhaps there is a more graceful way to state these rules.  */
803
804   /* If we're converting to a narrower type, then we need to clear out
805      the upper bits.  */
806   if (TYPE_LENGTH (to) < TYPE_LENGTH (from))
807     gen_extend (ax, from);
808
809   /* If the two values have equal width, but different signednesses,
810      then we need to extend.  */
811   else if (TYPE_LENGTH (to) == TYPE_LENGTH (from))
812     {
813       if (TYPE_UNSIGNED (from) != TYPE_UNSIGNED (to))
814         gen_extend (ax, to);
815     }
816
817   /* If we're converting to a wider type, and becoming unsigned, then
818      we need to zero out any possible sign bits.  */
819   else if (TYPE_LENGTH (to) > TYPE_LENGTH (from))
820     {
821       if (TYPE_UNSIGNED (to))
822         gen_extend (ax, to);
823     }
824 }
825
826
827 /* Return non-zero iff the type FROM will require any bytecodes to be
828    emitted to be converted to the type TO.  */
829 static int
830 is_nontrivial_conversion (from, to)
831      struct type *from, *to;
832 {
833   struct agent_expr *ax = new_agent_expr (0);
834   int nontrivial;
835
836   /* Actually generate the code, and see if anything came out.  At the
837      moment, it would be trivial to replicate the code in
838      gen_conversion here, but in the future, when we're supporting
839      floating point and the like, it may not be.  Doing things this
840      way allows this function to be independent of the logic in
841      gen_conversion.  */
842   gen_conversion (ax, from, to);
843   nontrivial = ax->len > 0;
844   free_agent_expr (ax);
845   return nontrivial;
846 }
847
848
849 /* Generate code to perform the "usual arithmetic conversions" (ANSI C
850    6.2.1.5) for the two operands of an arithmetic operator.  This
851    effectively finds a "least upper bound" type for the two arguments,
852    and promotes each argument to that type.  *VALUE1 and *VALUE2
853    describe the values as they are passed in, and as they are left.  */
854 static void
855 gen_usual_arithmetic (ax, value1, value2)
856      struct agent_expr *ax;
857      struct axs_value *value1, *value2;
858 {
859   /* Do the usual binary conversions.  */
860   if (TYPE_CODE (value1->type) == TYPE_CODE_INT
861       && TYPE_CODE (value2->type) == TYPE_CODE_INT)
862     {
863       /* The ANSI integral promotions seem to work this way: Order the
864          integer types by size, and then by signedness: an n-bit
865          unsigned type is considered "wider" than an n-bit signed
866          type.  Promote to the "wider" of the two types, and always
867          promote at least to int.  */
868       struct type *target = max_type (builtin_type_int,
869                                       max_type (value1->type, value2->type));
870
871       /* Deal with value2, on the top of the stack.  */
872       gen_conversion (ax, value2->type, target);
873
874       /* Deal with value1, not on the top of the stack.  Don't
875          generate the `swap' instructions if we're not actually going
876          to do anything.  */
877       if (is_nontrivial_conversion (value1->type, target))
878         {
879           ax_simple (ax, aop_swap);
880           gen_conversion (ax, value1->type, target);
881           ax_simple (ax, aop_swap);
882         }
883
884       value1->type = value2->type = target;
885     }
886 }
887
888
889 /* Generate code to perform the integral promotions (ANSI 6.2.1.1) on
890    the value on the top of the stack, as described by VALUE.  Assume
891    the value has integral type.  */
892 static void
893 gen_integral_promotions (ax, value)
894      struct agent_expr *ax;
895      struct axs_value *value;
896 {
897   if (! type_wider_than (value->type, builtin_type_int))
898     {
899       gen_conversion (ax, value->type, builtin_type_int);
900       value->type = builtin_type_int;
901     }
902   else if (! type_wider_than (value->type, builtin_type_unsigned_int))
903     {
904       gen_conversion (ax, value->type, builtin_type_unsigned_int);
905       value->type = builtin_type_unsigned_int;
906     }
907 }
908
909
910 /* Generate code for a cast to TYPE.  */
911 static void
912 gen_cast (ax, value, type)
913      struct agent_expr *ax;
914      struct axs_value *value;
915      struct type *type;
916 {
917   /* GCC does allow casts to yield lvalues, so this should be fixed
918      before merging these changes into the trunk.  */
919   require_rvalue (ax, value);
920   /* Dereference typedefs. */
921   type = check_typedef (type);
922
923   switch (type->code)
924     {
925     case TYPE_CODE_PTR:
926       /* It's implementation-defined, and I'll bet this is what GCC
927          does.  */
928       break;
929
930     case TYPE_CODE_ARRAY:
931     case TYPE_CODE_STRUCT:
932     case TYPE_CODE_UNION:
933     case TYPE_CODE_FUNC:
934       error ("Illegal type cast: intended type must be scalar.");
935
936     case TYPE_CODE_ENUM:
937       /* We don't have to worry about the size of the value, because
938          all our integral values are fully sign-extended, and when
939          casting pointers we can do anything we like.  Is there any
940          way for us to actually know what GCC actually does with a
941          cast like this?  */
942       value->type = type;
943       break;
944       
945     case TYPE_CODE_INT:
946       gen_conversion (ax, value->type, type);
947       break;
948
949     case TYPE_CODE_VOID:
950       /* We could pop the value, and rely on everyone else to check
951          the type and notice that this value doesn't occupy a stack
952          slot.  But for now, leave the value on the stack, and
953          preserve the "value == stack element" assumption.  */
954       break;
955
956     default:
957       error ("Casts to requested type are not yet implemented.");
958     }
959
960   value->type = type;
961 }
962
963
964 \f
965 /* Generating bytecode from GDB expressions: arithmetic */
966
967 /* Scale the integer on the top of the stack by the size of the target
968    of the pointer type TYPE.  */
969 static void
970 gen_scale (ax, op, type)
971      struct agent_expr *ax;
972      enum agent_op op;
973      struct type *type;
974 {
975   struct type *element = TYPE_TARGET_TYPE (type);
976
977   if (element->length != 1)
978     {
979       ax_const_l (ax, element->length);
980       ax_simple (ax, op);
981     }
982 }
983
984
985 /* Generate code for an addition; non-trivial because we deal with
986    pointer arithmetic.  We set VALUE to describe the result value; we
987    assume VALUE1 and VALUE2 describe the two operands, and that
988    they've undergone the usual binary conversions.  Used by both
989    BINOP_ADD and BINOP_SUBSCRIPT.  NAME is used in error messages.  */
990 static void
991 gen_add (ax, value, value1, value2, name)
992      struct agent_expr *ax;
993      struct axs_value *value, *value1, *value2;
994      char *name;
995 {
996   /* Is it INT+PTR?  */
997   if (value1->type->code == TYPE_CODE_INT
998       && value2->type->code == TYPE_CODE_PTR)
999     {
1000       /* Swap the values and proceed normally.  */
1001       ax_simple (ax, aop_swap);
1002       gen_scale (ax, aop_mul, value2->type);
1003       ax_simple (ax, aop_add);
1004       gen_extend (ax, value2->type); /* Catch overflow.  */
1005       value->type = value2->type;
1006     }
1007
1008   /* Is it PTR+INT?  */
1009   else if (value1->type->code == TYPE_CODE_PTR
1010            && value2->type->code == TYPE_CODE_INT)
1011     {
1012       gen_scale (ax, aop_mul, value1->type);
1013       ax_simple (ax, aop_add);
1014       gen_extend (ax, value1->type); /* Catch overflow.  */
1015       value->type = value1->type;
1016     }
1017
1018   /* Must be number + number; the usual binary conversions will have
1019      brought them both to the same width.  */
1020   else if (value1->type->code == TYPE_CODE_INT
1021            && value2->type->code == TYPE_CODE_INT)
1022     {
1023       ax_simple (ax, aop_add);
1024       gen_extend (ax, value1->type); /* Catch overflow.  */
1025       value->type = value1->type;
1026     }
1027
1028   else
1029     error ("Illegal combination of types in %s.", name);
1030
1031   value->kind = axs_rvalue;
1032 }
1033
1034
1035 /* Generate code for an addition; non-trivial because we have to deal
1036    with pointer arithmetic.  We set VALUE to describe the result
1037    value; we assume VALUE1 and VALUE2 describe the two operands, and
1038    that they've undergone the usual binary conversions.  */
1039 static void
1040 gen_sub (ax, value, value1, value2)
1041      struct agent_expr *ax;
1042      struct axs_value *value, *value1, *value2;
1043 {
1044   struct type *element;
1045
1046   if (value1->type->code == TYPE_CODE_PTR)
1047     {
1048       /* Is it PTR - INT?  */
1049       if (value2->type->code == TYPE_CODE_INT)
1050         {
1051           gen_scale (ax, aop_mul, value1->type);
1052           ax_simple (ax, aop_sub);
1053           gen_extend (ax, value1->type); /* Catch overflow.  */
1054           value->type = value1->type;
1055         }
1056
1057       /* Is it PTR - PTR?  Strictly speaking, the types ought to
1058          match, but this is what the normal GDB expression evaluator
1059          tests for.  */
1060       else if (value2->type->code == TYPE_CODE_PTR
1061                && (TYPE_LENGTH (TYPE_TARGET_TYPE (value1->type))
1062                    == TYPE_LENGTH (TYPE_TARGET_TYPE (value2->type))))
1063         {
1064           ax_simple (ax, aop_sub);
1065           gen_scale (ax, aop_div_unsigned, value1->type);
1066           value->type = builtin_type_long; /* FIXME --- should be ptrdiff_t */
1067         }
1068       else
1069         error ("\
1070 First argument of `-' is a pointer, but second argument is neither\n\
1071 an integer nor a pointer of the same type.");
1072     }
1073
1074   /* Must be number + number.  */
1075   else if (value1->type->code == TYPE_CODE_INT
1076            && value2->type->code == TYPE_CODE_INT)
1077     {
1078       ax_simple (ax, aop_sub);
1079       gen_extend (ax, value1->type); /* Catch overflow.  */
1080       value->type = value1->type;
1081     }
1082   
1083   else
1084     error ("Illegal combination of types in subtraction.");
1085
1086   value->kind = axs_rvalue;
1087 }
1088
1089 /* Generate code for a binary operator that doesn't do pointer magic.
1090    We set VALUE to describe the result value; we assume VALUE1 and
1091    VALUE2 describe the two operands, and that they've undergone the
1092    usual binary conversions.  MAY_CARRY should be non-zero iff the
1093    result needs to be extended.  NAME is the English name of the
1094    operator, used in error messages */
1095 static void
1096 gen_binop (ax, value, value1, value2, op, op_unsigned, may_carry, name)
1097      struct agent_expr *ax;
1098      struct axs_value *value, *value1, *value2;
1099      enum agent_op op, op_unsigned;
1100      int may_carry;
1101      char *name;
1102 {
1103   /* We only handle INT op INT.  */
1104   if ((value1->type->code != TYPE_CODE_INT)
1105       || (value2->type->code != TYPE_CODE_INT))
1106     error ("Illegal combination of types in %s.", name);
1107   
1108   ax_simple (ax,
1109              TYPE_UNSIGNED (value1->type) ? op_unsigned : op);
1110   if (may_carry)
1111     gen_extend (ax, value1->type); /* catch overflow */
1112   value->type = value1->type;
1113   value->kind = axs_rvalue;
1114 }
1115
1116
1117 static void
1118 gen_logical_not (ax, value)
1119      struct agent_expr *ax;
1120      struct axs_value *value;
1121 {
1122   if (TYPE_CODE (value->type) != TYPE_CODE_INT
1123       && TYPE_CODE (value->type) != TYPE_CODE_PTR)
1124     error ("Illegal type of operand to `!'.");
1125
1126   gen_usual_unary (ax, value);
1127   ax_simple (ax, aop_log_not);
1128   value->type = builtin_type_int;
1129 }
1130
1131
1132 static void
1133 gen_complement (ax, value)
1134      struct agent_expr *ax;
1135      struct axs_value *value;
1136 {
1137   if (TYPE_CODE (value->type) != TYPE_CODE_INT)
1138     error ("Illegal type of operand to `~'.");
1139
1140   gen_usual_unary (ax, value);
1141   gen_integral_promotions (ax, value);
1142   ax_simple (ax, aop_bit_not);
1143   gen_extend (ax, value->type);
1144 }
1145
1146
1147 \f
1148 /* Generating bytecode from GDB expressions: * & . -> @ sizeof */
1149
1150 /* Dereference the value on the top of the stack.  */
1151 static void
1152 gen_deref (ax, value)
1153      struct agent_expr *ax;
1154      struct axs_value *value;
1155 {
1156   /* The caller should check the type, because several operators use
1157      this, and we don't know what error message to generate.  */
1158   if (value->type->code != TYPE_CODE_PTR)
1159     error ("GDB bug: ax-gdb.c (gen_deref): expected a pointer");
1160
1161   /* We've got an rvalue now, which is a pointer.  We want to yield an
1162      lvalue, whose address is exactly that pointer.  So we don't
1163      actually emit any code; we just change the type from "Pointer to
1164      T" to "T", and mark the value as an lvalue in memory.  Leave it
1165      to the consumer to actually dereference it.  */
1166   value->type = check_typedef (TYPE_TARGET_TYPE (value->type));
1167   value->kind = ((value->type->code == TYPE_CODE_FUNC)
1168                  ? axs_rvalue : axs_lvalue_memory);
1169 }
1170
1171
1172 /* Produce the address of the lvalue on the top of the stack.  */
1173 static void
1174 gen_address_of (ax, value)
1175      struct agent_expr *ax;
1176      struct axs_value *value;
1177 {
1178   /* Special case for taking the address of a function.  The ANSI
1179      standard describes this as a special case, too, so this
1180      arrangement is not without motivation.  */
1181   if (value->type->code == TYPE_CODE_FUNC)
1182     /* The value's already an rvalue on the stack, so we just need to
1183        change the type.  */
1184     value->type = lookup_pointer_type (value->type);
1185   else
1186     switch (value->kind)
1187       {
1188       case axs_rvalue:
1189         error ("Operand of `&' is an rvalue, which has no address.");
1190
1191       case axs_lvalue_register:
1192         error ("Operand of `&' is in a register, and has no address.");
1193
1194       case axs_lvalue_memory:
1195         value->kind = axs_rvalue;
1196         value->type = lookup_pointer_type (value->type);
1197         break;
1198       }
1199 }
1200
1201
1202 /* A lot of this stuff will have to change to support C++.  But we're
1203    not going to deal with that at the moment.  */
1204
1205 /* Find the field in the structure type TYPE named NAME, and return
1206    its index in TYPE's field array.  */
1207 static int
1208 find_field (type, name)
1209      struct type *type;
1210      char *name;
1211 {
1212   int i;
1213
1214   CHECK_TYPEDEF (type);
1215
1216   /* Make sure this isn't C++.  */
1217   if (TYPE_N_BASECLASSES (type) != 0)
1218     error ("GDB bug: ax-gdb.c (find_field): derived classes supported");
1219
1220   for (i = 0; i < TYPE_NFIELDS (type); i++)
1221     {
1222       char *this_name = TYPE_FIELD_NAME (type, i);
1223
1224       if (this_name && STREQ (name, this_name))
1225         return i;
1226
1227       if (this_name[0] == '\0')
1228         error ("GDB bug: ax-gdb.c (find_field): anonymous unions not supported");
1229     }
1230
1231   error ("Couldn't find member named `%s' in struct/union `%s'",
1232          name, type->tag_name);
1233
1234   return 0;
1235 }
1236
1237
1238 /* Generate code to push the value of a bitfield of a structure whose
1239    address is on the top of the stack.  START and END give the
1240    starting and one-past-ending *bit* numbers of the field within the
1241    structure.  */
1242 static void
1243 gen_bitfield_ref (ax, value, type, start, end)
1244      struct agent_expr *ax;
1245      struct axs_value *value;
1246      struct type *type;
1247      int start, end;
1248 {
1249   /* Note that ops[i] fetches 8 << i bits.  */
1250   static enum agent_op ops[]
1251     = { aop_ref8, aop_ref16, aop_ref32, aop_ref64 };
1252   static int num_ops = (sizeof (ops) / sizeof (ops[0]));
1253
1254   /* We don't want to touch any byte that the bitfield doesn't
1255      actually occupy; we shouldn't make any accesses we're not
1256      explicitly permitted to.  We rely here on the fact that the
1257      bytecode `ref' operators work on unaligned addresses.
1258
1259      It takes some fancy footwork to get the stack to work the way
1260      we'd like.  Say we're retrieving a bitfield that requires three
1261      fetches.  Initially, the stack just contains the address:
1262                 addr
1263      For the first fetch, we duplicate the address
1264                 addr addr
1265      then add the byte offset, do the fetch, and shift and mask as
1266      needed, yielding a fragment of the value, properly aligned for
1267      the final bitwise or:
1268                 addr frag1
1269      then we swap, and repeat the process:
1270                 frag1 addr                    --- address on top
1271                 frag1 addr addr               --- duplicate it
1272                 frag1 addr frag2              --- get second fragment
1273                 frag1 frag2 addr              --- swap again
1274                 frag1 frag2 frag3             --- get third fragment
1275      Notice that, since the third fragment is the last one, we don't
1276      bother duplicating the address this time.  Now we have all the
1277      fragments on the stack, and we can simply `or' them together,
1278      yielding the final value of the bitfield.  */
1279
1280   /* The first and one-after-last bits in the field, but rounded down
1281      and up to byte boundaries.  */
1282   int bound_start = (start / TARGET_CHAR_BIT) * TARGET_CHAR_BIT;
1283   int bound_end   = (((end + TARGET_CHAR_BIT - 1)
1284                       / TARGET_CHAR_BIT)
1285                      * TARGET_CHAR_BIT);
1286
1287   /* current bit offset within the structure */
1288   int offset;
1289
1290   /* The index in ops of the opcode we're considering.  */
1291   int op;
1292
1293   /* The number of fragments we generated in the process.  Probably
1294      equal to the number of `one' bits in bytesize, but who cares?  */
1295   int fragment_count;
1296
1297   /* Dereference any typedefs. */
1298   type = check_typedef (type);
1299
1300   /* Can we fetch the number of bits requested at all?  */
1301   if ((end - start) > ((1 << num_ops) * 8))
1302     error ("GDB bug: ax-gdb.c (gen_bitfield_ref): bitfield too wide");
1303
1304   /* Note that we know here that we only need to try each opcode once.
1305      That may not be true on machines with weird byte sizes.  */
1306   offset = bound_start;
1307   fragment_count = 0;
1308   for (op = num_ops - 1; op >= 0; op--)
1309     {
1310       /* number of bits that ops[op] would fetch */
1311       int op_size = 8 << op;
1312
1313       /* The stack at this point, from bottom to top, contains zero or
1314          more fragments, then the address.  */
1315       
1316       /* Does this fetch fit within the bitfield?  */
1317       if (offset + op_size <= bound_end)
1318         {
1319           /* Is this the last fragment?  */
1320           int last_frag = (offset + op_size == bound_end);
1321
1322           if (! last_frag)
1323             ax_simple (ax, aop_dup); /* keep a copy of the address */
1324           
1325           /* Add the offset.  */
1326           gen_offset (ax, offset / TARGET_CHAR_BIT);
1327
1328           if (trace_kludge)
1329             {
1330               /* Record the area of memory we're about to fetch.  */
1331               ax_trace_quick (ax, op_size / TARGET_CHAR_BIT);
1332             }
1333
1334           /* Perform the fetch.  */
1335           ax_simple (ax, ops[op]);
1336         
1337           /* Shift the bits we have to their proper position.
1338              gen_left_shift will generate right shifts when the operand
1339              is negative.
1340
1341              A big-endian field diagram to ponder:
1342               byte 0  byte 1  byte 2  byte 3  byte 4  byte 5  byte 6  byte 7
1343              +------++------++------++------++------++------++------++------+
1344              xxxxAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBCCCCCxxxxxxxxxxx
1345                              ^               ^               ^    ^
1346              bit number      16              32              48   53
1347              These are bit numbers as supplied by GDB.  Note that the
1348              bit numbers run from right to left once you've fetched the
1349              value!
1350
1351              A little-endian field diagram to ponder:
1352               byte 7  byte 6  byte 5  byte 4  byte 3  byte 2  byte 1  byte 0
1353              +------++------++------++------++------++------++------++------+
1354              xxxxxxxxxxxAAAAABBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCxxxx
1355                             ^               ^               ^           ^   ^
1356              bit number     48              32              16          4   0
1357
1358              In both cases, the most significant end is on the left
1359              (i.e. normal numeric writing order), which means that you
1360              don't go crazy thinking about `left' and `right' shifts.
1361
1362              We don't have to worry about masking yet:
1363              - If they contain garbage off the least significant end, then we
1364                must be looking at the low end of the field, and the right
1365                shift will wipe them out.
1366              - If they contain garbage off the most significant end, then we
1367                must be looking at the most significant end of the word, and
1368                the sign/zero extension will wipe them out.
1369              - If we're in the interior of the word, then there is no garbage
1370                on either end, because the ref operators zero-extend.  */
1371           if (TARGET_BYTE_ORDER == BIG_ENDIAN)
1372             gen_left_shift (ax, end - (offset + op_size));
1373           else 
1374             gen_left_shift (ax, offset - start);
1375
1376           if (! last_frag)
1377             /* Bring the copy of the address up to the top.  */
1378             ax_simple (ax, aop_swap);
1379
1380           offset += op_size;
1381           fragment_count++;
1382         }
1383     }
1384
1385   /* Generate enough bitwise `or' operations to combine all the
1386      fragments we left on the stack.  */
1387   while (fragment_count-- > 1)
1388     ax_simple (ax, aop_bit_or);
1389
1390   /* Sign- or zero-extend the value as appropriate.  */
1391   ((TYPE_UNSIGNED (type) ? ax_zero_ext : ax_ext) (ax, end - start));
1392
1393   /* This is *not* an lvalue.  Ugh.  */
1394   value->kind = axs_rvalue;
1395   value->type = type;
1396 }
1397
1398
1399 /* Generate code to reference the member named FIELD of a structure or
1400    union.  The top of the stack, as described by VALUE, should have
1401    type (pointer to a)* struct/union.  OPERATOR_NAME is the name of
1402    the operator being compiled, and OPERAND_NAME is the kind of thing
1403    it operates on; we use them in error messages.  */
1404 static void
1405 gen_struct_ref (ax, value, field, operator_name, operand_name)
1406      struct agent_expr *ax;
1407      struct axs_value *value;
1408      char *field;
1409      char *operator_name;
1410      char *operand_name;
1411 {
1412   struct type *type;
1413   int i;
1414
1415   /* Follow pointers until we reach a non-pointer.  These aren't the C
1416      semantics, but they're what the normal GDB evaluator does, so we
1417      should at least be consistent.  */
1418   while (value->type->code == TYPE_CODE_PTR)
1419     {
1420       gen_usual_unary (ax, value);
1421       gen_deref (ax, value);
1422     }
1423   type = value->type;
1424
1425   /* This must yield a structure or a union.  */
1426   if (TYPE_CODE (type) != TYPE_CODE_STRUCT
1427       && TYPE_CODE (type) != TYPE_CODE_UNION)
1428     error ("The left operand of `%s' is not a %s.",
1429            operator_name, operand_name);
1430
1431   /* And it must be in memory; we don't deal with structure rvalues,
1432      or structures living in registers.  */
1433   if (value->kind != axs_lvalue_memory)
1434     error ("Structure does not live in memory.");
1435
1436   i = find_field (type, field);
1437   
1438   /* Is this a bitfield?  */
1439   if (TYPE_FIELD_PACKED (type, i))
1440     gen_bitfield_ref (ax, value, TYPE_FIELD_TYPE (type, i),
1441                       TYPE_FIELD_BITPOS (type, i),
1442                       (TYPE_FIELD_BITPOS (type, i)
1443                        + TYPE_FIELD_BITSIZE (type, i)));
1444   else
1445     {
1446       gen_offset (ax, TYPE_FIELD_BITPOS (type, i) / TARGET_CHAR_BIT);
1447       value->kind = axs_lvalue_memory;
1448       value->type = TYPE_FIELD_TYPE (type, i);
1449     }
1450 }
1451
1452
1453 /* Generate code for GDB's magical `repeat' operator.  
1454    LVALUE @ INT creates an array INT elements long, and whose elements
1455    have the same type as LVALUE, located in memory so that LVALUE is
1456    its first element.  For example, argv[0]@argc gives you the array
1457    of command-line arguments.
1458
1459    Unfortunately, because we have to know the types before we actually
1460    have a value for the expression, we can't implement this perfectly
1461    without changing the type system, having values that occupy two
1462    stack slots, doing weird things with sizeof, etc.  So we require
1463    the right operand to be a constant expression.  */
1464 static void
1465 gen_repeat (pc, ax, value)
1466      union exp_element **pc;
1467      struct agent_expr *ax;
1468      struct axs_value *value;
1469 {
1470   struct axs_value value1;
1471   /* We don't want to turn this into an rvalue, so no conversions
1472      here.  */
1473   gen_expr (pc, ax, &value1);
1474   if (value1.kind != axs_lvalue_memory)
1475     error ("Left operand of `@' must be an object in memory.");
1476
1477   /* Evaluate the length; it had better be a constant.  */
1478   {
1479     struct value *v = const_expr (pc);
1480     int length;
1481
1482     if (! v)
1483       error ("Right operand of `@' must be a constant, in agent expressions.");
1484     if (v->type->code != TYPE_CODE_INT)
1485       error ("Right operand of `@' must be an integer.");
1486     length = value_as_long (v);
1487     if (length <= 0)
1488       error ("Right operand of `@' must be positive.");
1489
1490     /* The top of the stack is already the address of the object, so
1491        all we need to do is frob the type of the lvalue.  */
1492     {
1493       /* FIXME-type-allocation: need a way to free this type when we are
1494          done with it.  */
1495       struct type *range
1496         = create_range_type (0, builtin_type_int, 0, length - 1);
1497       struct type *array = create_array_type (0, value1.type, range);
1498
1499       value->kind = axs_lvalue_memory;
1500       value->type = array;
1501     }
1502   }
1503 }
1504
1505
1506 /* Emit code for the `sizeof' operator.
1507    *PC should point at the start of the operand expression; we advance it
1508    to the first instruction after the operand.  */
1509 static void
1510 gen_sizeof (pc, ax, value)
1511      union exp_element **pc;
1512      struct agent_expr *ax;
1513      struct axs_value *value;
1514 {
1515   /* We don't care about the value of the operand expression; we only
1516      care about its type.  However, in the current arrangement, the
1517      only way to find an expression's type is to generate code for it.
1518      So we generate code for the operand, and then throw it away,
1519      replacing it with code that simply pushes its size.  */
1520   int start = ax->len;
1521   gen_expr (pc, ax, value);
1522
1523   /* Throw away the code we just generated.  */
1524   ax->len = start;
1525   
1526   ax_const_l (ax, TYPE_LENGTH (value->type));
1527   value->kind = axs_rvalue;
1528   value->type = builtin_type_int;
1529 }
1530
1531 \f
1532 /* Generating bytecode from GDB expressions: general recursive thingy  */
1533
1534 /* A gen_expr function written by a Gen-X'er guy.
1535    Append code for the subexpression of EXPR starting at *POS_P to AX.  */
1536 static void
1537 gen_expr (pc, ax, value)
1538      union exp_element **pc;
1539      struct agent_expr *ax;
1540      struct axs_value *value;
1541 {
1542   /* Used to hold the descriptions of operand expressions.  */
1543   struct axs_value value1, value2;
1544   enum exp_opcode op = (*pc)[0].opcode;
1545
1546   /* If we're looking at a constant expression, just push its value.  */
1547   {
1548     struct value *v = maybe_const_expr (pc);
1549     
1550     if (v)
1551       {
1552         ax_const_l (ax, value_as_long (v));
1553         value->kind = axs_rvalue;
1554         value->type = check_typedef (VALUE_TYPE (v));
1555         return;
1556       }
1557   }
1558
1559   /* Otherwise, go ahead and generate code for it.  */
1560   switch (op)
1561     {
1562       /* Binary arithmetic operators.  */
1563     case BINOP_ADD:
1564     case BINOP_SUB:
1565     case BINOP_MUL:
1566     case BINOP_DIV:
1567     case BINOP_REM:
1568     case BINOP_SUBSCRIPT:
1569     case BINOP_BITWISE_AND:
1570     case BINOP_BITWISE_IOR:
1571     case BINOP_BITWISE_XOR:
1572       (*pc)++;
1573       gen_expr (pc, ax, &value1);
1574       gen_usual_unary (ax, &value1);
1575       gen_expr (pc, ax, &value2);
1576       gen_usual_unary (ax, &value2);
1577       gen_usual_arithmetic (ax, &value1, &value2);
1578       switch (op)
1579         {
1580         case BINOP_ADD:
1581           gen_add (ax, value, &value1, &value2, "addition");
1582           break;
1583         case BINOP_SUB:
1584           gen_sub (ax, value, &value1, &value2);
1585           break;
1586         case BINOP_MUL:
1587           gen_binop (ax, value, &value1, &value2,
1588                      aop_mul, aop_mul, 1, "multiplication");
1589           break;
1590         case BINOP_DIV:
1591           gen_binop (ax, value, &value1, &value2,
1592                      aop_div_signed, aop_div_unsigned, 1, "division");
1593           break;
1594         case BINOP_REM:
1595           gen_binop (ax, value, &value1, &value2,
1596                      aop_rem_signed, aop_rem_unsigned, 1, "remainder");
1597           break;
1598         case BINOP_SUBSCRIPT:
1599           gen_add (ax, value, &value1, &value2, "array subscripting");
1600           if (TYPE_CODE (value->type) != TYPE_CODE_PTR)
1601             error ("Illegal combination of types in array subscripting.");
1602           gen_deref (ax, value);
1603           break;
1604         case BINOP_BITWISE_AND:
1605           gen_binop (ax, value, &value1, &value2,
1606                      aop_bit_and, aop_bit_and, 0, "bitwise and");
1607           break;
1608
1609         case BINOP_BITWISE_IOR:
1610           gen_binop (ax, value, &value1, &value2,
1611                      aop_bit_or, aop_bit_or, 0, "bitwise or");
1612           break;
1613
1614         case BINOP_BITWISE_XOR:
1615           gen_binop (ax, value, &value1, &value2,
1616                      aop_bit_xor, aop_bit_xor, 0, "bitwise exclusive-or");
1617           break;
1618
1619         default:
1620           /* We should only list operators in the outer case statement
1621              that we actually handle in the inner case statement.  */
1622           error ("GDB bug: ax-gdb.c (gen_expr): op case sets don't match");
1623         }
1624       break;
1625
1626       /* Note that we need to be a little subtle about generating code
1627          for comma.  In C, we can do some optimizations here because
1628          we know the left operand is only being evaluated for effect.
1629          However, if the tracing kludge is in effect, then we always
1630          need to evaluate the left hand side fully, so that all the
1631          variables it mentions get traced.  */
1632     case BINOP_COMMA:
1633       (*pc)++;
1634       gen_expr (pc, ax, &value1);
1635       /* Don't just dispose of the left operand.  We might be tracing,
1636          in which case we want to emit code to trace it if it's an
1637          lvalue.  */
1638       gen_traced_pop (ax, &value1);
1639       gen_expr (pc, ax, value);
1640       /* It's the consumer's responsibility to trace the right operand.  */
1641       break;
1642       
1643     case OP_LONG:               /* some integer constant */
1644       {
1645         struct type *type = (*pc)[1].type;
1646         LONGEST k = (*pc)[2].longconst;
1647         (*pc) += 4;
1648         gen_int_literal (ax, value, k, type);
1649       }
1650     break;
1651
1652     case OP_VAR_VALUE:
1653       gen_var_ref (ax, value, (*pc)[2].symbol);
1654       (*pc) += 4;
1655       break;
1656
1657     case OP_REGISTER:
1658       {
1659         int reg = (int) (*pc)[1].longconst;
1660         (*pc) += 3;
1661         value->kind = axs_lvalue_register;
1662         value->u.reg = reg;
1663         value->type = REGISTER_VIRTUAL_TYPE (reg);
1664       }
1665     break;
1666
1667     case OP_INTERNALVAR:
1668       error ("GDB agent expressions cannot use convenience variables.");
1669
1670     /* Weirdo operator: see comments for gen_repeat for details.  */
1671     case BINOP_REPEAT:
1672       /* Note that gen_repeat handles its own argument evaluation.  */
1673       (*pc)++;
1674       gen_repeat (pc, ax, value);
1675       break;
1676
1677     case UNOP_CAST:
1678       {
1679         struct type *type = (*pc)[1].type;
1680         (*pc) += 3;
1681         gen_expr (pc, ax, value);
1682         gen_cast (ax, value, type);
1683       }
1684     break;
1685
1686     case UNOP_MEMVAL:
1687       {
1688         struct type *type = check_typedef ((*pc)[1].type);
1689         (*pc) += 3;
1690         gen_expr (pc, ax, value);
1691         /* I'm not sure I understand UNOP_MEMVAL entirely.  I think
1692            it's just a hack for dealing with minsyms; you take some
1693            integer constant, pretend it's the address of an lvalue of
1694            the given type, and dereference it.  */
1695         if (value->kind != axs_rvalue)
1696           /* This would be weird.  */
1697           error ("GDB bug: ax-gdb.c (gen_expr): OP_MEMVAL operand isn't an rvalue???");
1698         value->type = type;
1699         value->kind = axs_lvalue_memory;
1700       }
1701     break;
1702
1703     case UNOP_NEG:
1704       (*pc)++;
1705       /* -FOO is equivalent to 0 - FOO.  */
1706       gen_int_literal (ax, &value1, (LONGEST) 0, builtin_type_int);
1707       gen_usual_unary (ax, &value1); /* shouldn't do much */
1708       gen_expr (pc, ax, &value2);
1709       gen_usual_unary (ax, &value2);
1710       gen_usual_arithmetic (ax, &value1, &value2);
1711       gen_sub (ax, value, &value1, &value2);
1712       break;
1713
1714     case UNOP_LOGICAL_NOT:
1715       (*pc)++;
1716       gen_expr (pc, ax, value);
1717       gen_logical_not (ax, value);
1718       break;
1719
1720     case UNOP_COMPLEMENT:
1721       (*pc)++;
1722       gen_expr (pc, ax, value);
1723       gen_complement (ax, value);
1724       break;
1725
1726     case UNOP_IND:
1727       (*pc)++;
1728       gen_expr (pc, ax, value);
1729       gen_usual_unary (ax, value);
1730       if (TYPE_CODE (value->type) != TYPE_CODE_PTR)
1731         error ("Argument of unary `*' is not a pointer.");
1732       gen_deref (ax, value);
1733       break;
1734
1735     case UNOP_ADDR:
1736       (*pc)++;
1737       gen_expr (pc, ax, value);
1738       gen_address_of (ax, value);
1739       break;
1740
1741     case UNOP_SIZEOF:
1742       (*pc)++;
1743       /* Notice that gen_sizeof handles its own operand, unlike most
1744          of the other unary operator functions.  This is because we
1745          have to throw away the code we generate.  */
1746       gen_sizeof (pc, ax, value);
1747       break;
1748
1749     case STRUCTOP_STRUCT:
1750     case STRUCTOP_PTR:
1751       {
1752         int length = (*pc)[1].longconst;
1753         char *name = &(*pc)[2].string;
1754
1755         (*pc) += 4 + BYTES_TO_EXP_ELEM (length + 1);
1756         gen_expr (pc, ax, value);
1757         if (op == STRUCTOP_STRUCT)
1758           gen_struct_ref (ax, value, name, ".", "structure or union");
1759         else if (op == STRUCTOP_PTR)
1760           gen_struct_ref (ax, value, name, "->",
1761                           "pointer to a structure or union");
1762         else
1763           /* If this `if' chain doesn't handle it, then the case list
1764              shouldn't mention it, and we shouldn't be here.  */
1765           error ("GDB bug: ax-gdb.c (gen_expr): unhandled struct case");
1766       }
1767     break;
1768
1769     case OP_TYPE:
1770       error ("Attempt to use a type name as an expression.");
1771
1772     default:
1773       error ("Unsupported operator in expression.");
1774     }
1775 }
1776      
1777
1778 \f
1779 #if 0  /* not used */
1780 /* Generating bytecode from GDB expressions: driver */
1781
1782 /* Given a GDB expression EXPR, produce a string of agent bytecode
1783    which computes its value.  Return the agent expression, and set
1784    *VALUE to describe its type, and whether it's an lvalue or rvalue.  */
1785 struct agent_expr *
1786 expr_to_agent (expr, value)
1787      struct expression *expr;
1788      struct axs_value *value;
1789 {
1790   struct cleanup *old_chain = 0;
1791   struct agent_expr *ax = new_agent_expr ();
1792   union exp_element *pc;
1793
1794   old_chain = make_cleanup ((make_cleanup_func) free_agent_expr, ax);
1795
1796   pc = expr->elts;
1797   trace_kludge = 0;
1798   gen_expr (&pc, ax, value);
1799
1800   /* We have successfully built the agent expr, so cancel the cleanup
1801      request.  If we add more cleanups that we always want done, this
1802      will have to get more complicated.  */
1803   discard_cleanups (old_chain);
1804   return ax;
1805 }
1806
1807
1808 /* Given a GDB expression EXPR denoting an lvalue in memory, produce a
1809    string of agent bytecode which will leave its address and size on
1810    the top of stack.  Return the agent expression.
1811
1812    Not sure this function is useful at all.  */
1813 struct agent_expr *
1814 expr_to_address_and_size (expr)
1815      struct expression *expr;
1816 {
1817   struct axs_value value;
1818   struct agent_expr *ax = expr_to_agent (expr, &value);
1819
1820   /* Complain if the result is not a memory lvalue.  */
1821   if (value.kind != axs_lvalue_memory)
1822     {
1823       free_agent_expr (ax);
1824       error ("Expression does not denote an object in memory.");
1825     }
1826
1827   /* Push the object's size on the stack.  */
1828   ax_const_l (ax, TYPE_LENGTH (value.type));
1829
1830   return ax;
1831 }
1832 #endif /* 0 */
1833
1834 /* Given a GDB expression EXPR, return bytecode to trace its value.
1835    The result will use the `trace' and `trace_quick' bytecodes to
1836    record the value of all memory touched by the expression.  The
1837    caller can then use the ax_reqs function to discover which
1838    registers it relies upon.  */
1839 struct agent_expr *
1840 gen_trace_for_expr (scope, expr)
1841      CORE_ADDR scope;
1842      struct expression *expr;
1843 {
1844   struct cleanup *old_chain = 0;
1845   struct agent_expr *ax = new_agent_expr (scope);
1846   union exp_element *pc;
1847   struct axs_value value;
1848
1849   old_chain = make_cleanup ((make_cleanup_func) free_agent_expr, ax);
1850
1851   pc = expr->elts;
1852   trace_kludge = 1;
1853   gen_expr (&pc, ax, &value);
1854
1855   /* Make sure we record the final object, and get rid of it.  */
1856   gen_traced_pop (ax, &value);
1857
1858   /* Oh, and terminate.  */
1859   ax_simple (ax, aop_end);
1860
1861   /* We have successfully built the agent expr, so cancel the cleanup
1862      request.  If we add more cleanups that we always want done, this
1863      will have to get more complicated.  */
1864   discard_cleanups (old_chain);
1865   return ax;
1866 }
1867
1868
1869 \f
1870 /* The "agent" command, for testing: compile and disassemble an expression.  */
1871
1872 static void
1873 print_axs_value (f, value)
1874      GDB_FILE *f;
1875      struct axs_value *value;
1876 {
1877   switch (value->kind)
1878     {
1879     case axs_rvalue:
1880       fputs_filtered ("rvalue", f);
1881       break;
1882
1883     case axs_lvalue_memory:
1884       fputs_filtered ("memory lvalue", f);
1885       break;
1886
1887     case axs_lvalue_register:
1888       fprintf_filtered (f, "register %d lvalue", value->u.reg);
1889       break;
1890     }
1891
1892   fputs_filtered (" : ", f);
1893   type_print (value->type, "", f, -1);
1894 }
1895
1896
1897 static void
1898 agent_command (exp, from_tty)
1899      char *exp;
1900      int from_tty;
1901 {
1902   struct cleanup *old_chain = 0;
1903   struct expression *expr;
1904   struct agent_expr *agent;
1905   struct agent_reqs reqs;
1906   struct frame_info *fi = get_current_frame (); /* need current scope */
1907
1908   /* We don't deal with overlay debugging at the moment.  We need to
1909      think more carefully about this.  If you copy this code into
1910      another command, change the error message; the user shouldn't
1911      have to know anything about agent expressions.  */
1912   if (overlay_debugging)
1913     error ("GDB can't do agent expression translation with overlays.");
1914
1915   if (exp == 0)
1916     error_no_arg ("expression to translate");
1917   
1918   expr = parse_expression (exp);
1919   old_chain = make_cleanup ((make_cleanup_func) free_current_contents, &expr);
1920   agent = gen_trace_for_expr (fi->pc, expr);
1921   make_cleanup ((make_cleanup_func) free_agent_expr, agent);
1922   ax_print (gdb_stdout, agent);
1923   ax_reqs (agent, &reqs);
1924
1925   do_cleanups (old_chain);
1926   dont_repeat ();
1927 }
1928
1929 \f
1930 /* Initialization code.  */
1931
1932 _initialize_ax_gdb ()
1933 {
1934   struct cmd_list_element *c;
1935
1936   add_cmd ("agent", class_maintenance, agent_command,
1937            "Translate an expression into remote agent bytecode.",
1938            &maintenancelist);
1939 }