ax-gdb: Do not treat enums and bools as integers.
[external/binutils.git] / gdb / ax-gdb.c
1 /* GDB-specific functions for operating on agent expressions.
2
3    Copyright (C) 1998-2001, 2003, 2007-2012 Free Software Foundation,
4    Inc.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21 #include "defs.h"
22 #include "symtab.h"
23 #include "symfile.h"
24 #include "gdbtypes.h"
25 #include "language.h"
26 #include "value.h"
27 #include "expression.h"
28 #include "command.h"
29 #include "gdbcmd.h"
30 #include "frame.h"
31 #include "target.h"
32 #include "ax.h"
33 #include "ax-gdb.h"
34 #include "gdb_string.h"
35 #include "block.h"
36 #include "regcache.h"
37 #include "user-regs.h"
38 #include "language.h"
39 #include "dictionary.h"
40 #include "breakpoint.h"
41 #include "tracepoint.h"
42 #include "cp-support.h"
43 #include "arch-utils.h"
44
45 #include "valprint.h"
46 #include "c-lang.h"
47
48 /* To make sense of this file, you should read doc/agentexpr.texi.
49    Then look at the types and enums in ax-gdb.h.  For the code itself,
50    look at gen_expr, towards the bottom; that's the main function that
51    looks at the GDB expressions and calls everything else to generate
52    code.
53
54    I'm beginning to wonder whether it wouldn't be nicer to internally
55    generate trees, with types, and then spit out the bytecode in
56    linear form afterwards; we could generate fewer `swap', `ext', and
57    `zero_ext' bytecodes that way; it would make good constant folding
58    easier, too.  But at the moment, I think we should be willing to
59    pay for the simplicity of this code with less-than-optimal bytecode
60    strings.
61
62    Remember, "GBD" stands for "Great Britain, Dammit!"  So be careful.  */
63 \f
64
65
66 /* Prototypes for local functions.  */
67
68 /* There's a standard order to the arguments of these functions:
69    union exp_element ** --- pointer into expression
70    struct agent_expr * --- agent expression buffer to generate code into
71    struct axs_value * --- describes value left on top of stack  */
72
73 static struct value *const_var_ref (struct symbol *var);
74 static struct value *const_expr (union exp_element **pc);
75 static struct value *maybe_const_expr (union exp_element **pc);
76
77 static void gen_traced_pop (struct gdbarch *, struct agent_expr *,
78                             struct axs_value *);
79
80 static void gen_sign_extend (struct agent_expr *, struct type *);
81 static void gen_extend (struct agent_expr *, struct type *);
82 static void gen_fetch (struct agent_expr *, struct type *);
83 static void gen_left_shift (struct agent_expr *, int);
84
85
86 static void gen_frame_args_address (struct gdbarch *, struct agent_expr *);
87 static void gen_frame_locals_address (struct gdbarch *, struct agent_expr *);
88 static void gen_offset (struct agent_expr *ax, int offset);
89 static void gen_sym_offset (struct agent_expr *, struct symbol *);
90 static void gen_var_ref (struct gdbarch *, struct agent_expr *ax,
91                          struct axs_value *value, struct symbol *var);
92
93
94 static void gen_int_literal (struct agent_expr *ax,
95                              struct axs_value *value,
96                              LONGEST k, struct type *type);
97
98
99 static void require_rvalue (struct agent_expr *ax, struct axs_value *value);
100 static void gen_usual_unary (struct expression *exp, struct agent_expr *ax,
101                              struct axs_value *value);
102 static int type_wider_than (struct type *type1, struct type *type2);
103 static struct type *max_type (struct type *type1, struct type *type2);
104 static void gen_conversion (struct agent_expr *ax,
105                             struct type *from, struct type *to);
106 static int is_nontrivial_conversion (struct type *from, struct type *to);
107 static void gen_usual_arithmetic (struct expression *exp,
108                                   struct agent_expr *ax,
109                                   struct axs_value *value1,
110                                   struct axs_value *value2);
111 static void gen_integral_promotions (struct expression *exp,
112                                      struct agent_expr *ax,
113                                      struct axs_value *value);
114 static void gen_cast (struct agent_expr *ax,
115                       struct axs_value *value, struct type *type);
116 static void gen_scale (struct agent_expr *ax,
117                        enum agent_op op, struct type *type);
118 static void gen_ptradd (struct agent_expr *ax, struct axs_value *value,
119                         struct axs_value *value1, struct axs_value *value2);
120 static void gen_ptrsub (struct agent_expr *ax, struct axs_value *value,
121                         struct axs_value *value1, struct axs_value *value2);
122 static void gen_ptrdiff (struct agent_expr *ax, struct axs_value *value,
123                          struct axs_value *value1, struct axs_value *value2,
124                          struct type *result_type);
125 static void gen_binop (struct agent_expr *ax,
126                        struct axs_value *value,
127                        struct axs_value *value1,
128                        struct axs_value *value2,
129                        enum agent_op op,
130                        enum agent_op op_unsigned, int may_carry, char *name);
131 static void gen_logical_not (struct agent_expr *ax, struct axs_value *value,
132                              struct type *result_type);
133 static void gen_complement (struct agent_expr *ax, struct axs_value *value);
134 static void gen_deref (struct agent_expr *, struct axs_value *);
135 static void gen_address_of (struct agent_expr *, struct axs_value *);
136 static void gen_bitfield_ref (struct expression *exp, struct agent_expr *ax,
137                               struct axs_value *value,
138                               struct type *type, int start, int end);
139 static void gen_primitive_field (struct expression *exp,
140                                  struct agent_expr *ax,
141                                  struct axs_value *value,
142                                  int offset, int fieldno, struct type *type);
143 static int gen_struct_ref_recursive (struct expression *exp,
144                                      struct agent_expr *ax,
145                                      struct axs_value *value,
146                                      char *field, int offset,
147                                      struct type *type);
148 static void gen_struct_ref (struct expression *exp, struct agent_expr *ax,
149                             struct axs_value *value,
150                             char *field,
151                             char *operator_name, char *operand_name);
152 static void gen_static_field (struct gdbarch *gdbarch,
153                               struct agent_expr *ax, struct axs_value *value,
154                               struct type *type, int fieldno);
155 static void gen_repeat (struct expression *exp, union exp_element **pc,
156                         struct agent_expr *ax, struct axs_value *value);
157 static void gen_sizeof (struct expression *exp, union exp_element **pc,
158                         struct agent_expr *ax, struct axs_value *value,
159                         struct type *size_type);
160 static void gen_expr (struct expression *exp, union exp_element **pc,
161                       struct agent_expr *ax, struct axs_value *value);
162 static void gen_expr_binop_rest (struct expression *exp,
163                                  enum exp_opcode op, union exp_element **pc,
164                                  struct agent_expr *ax,
165                                  struct axs_value *value,
166                                  struct axs_value *value1,
167                                  struct axs_value *value2);
168
169 static void agent_command (char *exp, int from_tty);
170 \f
171
172 /* Detecting constant expressions.  */
173
174 /* If the variable reference at *PC is a constant, return its value.
175    Otherwise, return zero.
176
177    Hey, Wally!  How can a variable reference be a constant?
178
179    Well, Beav, this function really handles the OP_VAR_VALUE operator,
180    not specifically variable references.  GDB uses OP_VAR_VALUE to
181    refer to any kind of symbolic reference: function names, enum
182    elements, and goto labels are all handled through the OP_VAR_VALUE
183    operator, even though they're constants.  It makes sense given the
184    situation.
185
186    Gee, Wally, don'cha wonder sometimes if data representations that
187    subvert commonly accepted definitions of terms in favor of heavily
188    context-specific interpretations are really just a tool of the
189    programming hegemony to preserve their power and exclude the
190    proletariat?  */
191
192 static struct value *
193 const_var_ref (struct symbol *var)
194 {
195   struct type *type = SYMBOL_TYPE (var);
196
197   switch (SYMBOL_CLASS (var))
198     {
199     case LOC_CONST:
200       return value_from_longest (type, (LONGEST) SYMBOL_VALUE (var));
201
202     case LOC_LABEL:
203       return value_from_pointer (type, (CORE_ADDR) SYMBOL_VALUE_ADDRESS (var));
204
205     default:
206       return 0;
207     }
208 }
209
210
211 /* If the expression starting at *PC has a constant value, return it.
212    Otherwise, return zero.  If we return a value, then *PC will be
213    advanced to the end of it.  If we return zero, *PC could be
214    anywhere.  */
215 static struct value *
216 const_expr (union exp_element **pc)
217 {
218   enum exp_opcode op = (*pc)->opcode;
219   struct value *v1;
220
221   switch (op)
222     {
223     case OP_LONG:
224       {
225         struct type *type = (*pc)[1].type;
226         LONGEST k = (*pc)[2].longconst;
227
228         (*pc) += 4;
229         return value_from_longest (type, k);
230       }
231
232     case OP_VAR_VALUE:
233       {
234         struct value *v = const_var_ref ((*pc)[2].symbol);
235
236         (*pc) += 4;
237         return v;
238       }
239
240       /* We could add more operators in here.  */
241
242     case UNOP_NEG:
243       (*pc)++;
244       v1 = const_expr (pc);
245       if (v1)
246         return value_neg (v1);
247       else
248         return 0;
249
250     default:
251       return 0;
252     }
253 }
254
255
256 /* Like const_expr, but guarantee also that *PC is undisturbed if the
257    expression is not constant.  */
258 static struct value *
259 maybe_const_expr (union exp_element **pc)
260 {
261   union exp_element *tentative_pc = *pc;
262   struct value *v = const_expr (&tentative_pc);
263
264   /* If we got a value, then update the real PC.  */
265   if (v)
266     *pc = tentative_pc;
267
268   return v;
269 }
270 \f
271
272 /* Generating bytecode from GDB expressions: general assumptions */
273
274 /* Here are a few general assumptions made throughout the code; if you
275    want to make a change that contradicts one of these, then you'd
276    better scan things pretty thoroughly.
277
278    - We assume that all values occupy one stack element.  For example,
279    sometimes we'll swap to get at the left argument to a binary
280    operator.  If we decide that void values should occupy no stack
281    elements, or that synthetic arrays (whose size is determined at
282    run time, created by the `@' operator) should occupy two stack
283    elements (address and length), then this will cause trouble.
284
285    - We assume the stack elements are infinitely wide, and that we
286    don't have to worry what happens if the user requests an
287    operation that is wider than the actual interpreter's stack.
288    That is, it's up to the interpreter to handle directly all the
289    integer widths the user has access to.  (Woe betide the language
290    with bignums!)
291
292    - We don't support side effects.  Thus, we don't have to worry about
293    GCC's generalized lvalues, function calls, etc.
294
295    - We don't support floating point.  Many places where we switch on
296    some type don't bother to include cases for floating point; there
297    may be even more subtle ways this assumption exists.  For
298    example, the arguments to % must be integers.
299
300    - We assume all subexpressions have a static, unchanging type.  If
301    we tried to support convenience variables, this would be a
302    problem.
303
304    - All values on the stack should always be fully zero- or
305    sign-extended.
306
307    (I wasn't sure whether to choose this or its opposite --- that
308    only addresses are assumed extended --- but it turns out that
309    neither convention completely eliminates spurious extend
310    operations (if everything is always extended, then you have to
311    extend after add, because it could overflow; if nothing is
312    extended, then you end up producing extends whenever you change
313    sizes), and this is simpler.)  */
314 \f
315
316 /* Generating bytecode from GDB expressions: the `trace' kludge  */
317
318 /* The compiler in this file is a general-purpose mechanism for
319    translating GDB expressions into bytecode.  One ought to be able to
320    find a million and one uses for it.
321
322    However, at the moment it is HOPELESSLY BRAIN-DAMAGED for the sake
323    of expediency.  Let he who is without sin cast the first stone.
324
325    For the data tracing facility, we need to insert `trace' bytecodes
326    before each data fetch; this records all the memory that the
327    expression touches in the course of evaluation, so that memory will
328    be available when the user later tries to evaluate the expression
329    in GDB.
330
331    This should be done (I think) in a post-processing pass, that walks
332    an arbitrary agent expression and inserts `trace' operations at the
333    appropriate points.  But it's much faster to just hack them
334    directly into the code.  And since we're in a crunch, that's what
335    I've done.
336
337    Setting the flag trace_kludge to non-zero enables the code that
338    emits the trace bytecodes at the appropriate points.  */
339 int trace_kludge;
340
341 /* Inspired by trace_kludge, this indicates that pointers to chars
342    should get an added tracenz bytecode to record nonzero bytes, up to
343    a length that is the value of trace_string_kludge.  */
344 int trace_string_kludge;
345
346 /* Scan for all static fields in the given class, including any base
347    classes, and generate tracing bytecodes for each.  */
348
349 static void
350 gen_trace_static_fields (struct gdbarch *gdbarch,
351                          struct agent_expr *ax,
352                          struct type *type)
353 {
354   int i, nbases = TYPE_N_BASECLASSES (type);
355   struct axs_value value;
356
357   CHECK_TYPEDEF (type);
358
359   for (i = TYPE_NFIELDS (type) - 1; i >= nbases; i--)
360     {
361       if (field_is_static (&TYPE_FIELD (type, i)))
362         {
363           gen_static_field (gdbarch, ax, &value, type, i);
364           if (value.optimized_out)
365             continue;
366           switch (value.kind)
367             {
368             case axs_lvalue_memory:
369               {
370                 int length = TYPE_LENGTH (check_typedef (value.type));
371
372                 ax_const_l (ax, length);
373                 ax_simple (ax, aop_trace);
374               }
375               break;
376
377             case axs_lvalue_register:
378               /* We don't actually need the register's value to be pushed,
379                  just note that we need it to be collected.  */
380               ax_reg_mask (ax, value.u.reg);
381
382             default:
383               break;
384             }
385         }
386     }
387
388   /* Now scan through base classes recursively.  */
389   for (i = 0; i < nbases; i++)
390     {
391       struct type *basetype = check_typedef (TYPE_BASECLASS (type, i));
392
393       gen_trace_static_fields (gdbarch, ax, basetype);
394     }
395 }
396
397 /* Trace the lvalue on the stack, if it needs it.  In either case, pop
398    the value.  Useful on the left side of a comma, and at the end of
399    an expression being used for tracing.  */
400 static void
401 gen_traced_pop (struct gdbarch *gdbarch,
402                 struct agent_expr *ax, struct axs_value *value)
403 {
404   int string_trace = 0;
405   if (trace_string_kludge
406       && TYPE_CODE (value->type) == TYPE_CODE_PTR
407       && c_textual_element_type (check_typedef (TYPE_TARGET_TYPE (value->type)),
408                                  's'))
409     string_trace = 1;
410
411   if (trace_kludge)
412     switch (value->kind)
413       {
414       case axs_rvalue:
415         if (string_trace)
416           {
417             ax_const_l (ax, trace_string_kludge);
418             ax_simple (ax, aop_tracenz);
419           }
420         else
421           /* We don't trace rvalues, just the lvalues necessary to
422              produce them.  So just dispose of this value.  */
423           ax_simple (ax, aop_pop);
424         break;
425
426       case axs_lvalue_memory:
427         {
428           int length = TYPE_LENGTH (check_typedef (value->type));
429
430           if (string_trace)
431             ax_simple (ax, aop_dup);
432
433           /* There's no point in trying to use a trace_quick bytecode
434              here, since "trace_quick SIZE pop" is three bytes, whereas
435              "const8 SIZE trace" is also three bytes, does the same
436              thing, and the simplest code which generates that will also
437              work correctly for objects with large sizes.  */
438           ax_const_l (ax, length);
439           ax_simple (ax, aop_trace);
440
441           if (string_trace)
442             {
443               ax_simple (ax, aop_ref32);
444               ax_const_l (ax, trace_string_kludge);
445               ax_simple (ax, aop_tracenz);
446             }
447         }
448         break;
449
450       case axs_lvalue_register:
451         /* We don't actually need the register's value to be on the
452            stack, and the target will get heartburn if the register is
453            larger than will fit in a stack, so just mark it for
454            collection and be done with it.  */
455         ax_reg_mask (ax, value->u.reg);
456        
457         /* But if the register points to a string, assume the value
458            will fit on the stack and push it anyway.  */
459         if (string_trace)
460           {
461             ax_reg (ax, value->u.reg);
462             ax_const_l (ax, trace_string_kludge);
463             ax_simple (ax, aop_tracenz);
464           }
465         break;
466       }
467   else
468     /* If we're not tracing, just pop the value.  */
469     ax_simple (ax, aop_pop);
470
471   /* To trace C++ classes with static fields stored elsewhere.  */
472   if (trace_kludge
473       && (TYPE_CODE (value->type) == TYPE_CODE_STRUCT
474           || TYPE_CODE (value->type) == TYPE_CODE_UNION))
475     gen_trace_static_fields (gdbarch, ax, value->type);
476 }
477 \f
478
479
480 /* Generating bytecode from GDB expressions: helper functions */
481
482 /* Assume that the lower bits of the top of the stack is a value of
483    type TYPE, and the upper bits are zero.  Sign-extend if necessary.  */
484 static void
485 gen_sign_extend (struct agent_expr *ax, struct type *type)
486 {
487   /* Do we need to sign-extend this?  */
488   if (!TYPE_UNSIGNED (type))
489     ax_ext (ax, TYPE_LENGTH (type) * TARGET_CHAR_BIT);
490 }
491
492
493 /* Assume the lower bits of the top of the stack hold a value of type
494    TYPE, and the upper bits are garbage.  Sign-extend or truncate as
495    needed.  */
496 static void
497 gen_extend (struct agent_expr *ax, struct type *type)
498 {
499   int bits = TYPE_LENGTH (type) * TARGET_CHAR_BIT;
500
501   /* I just had to.  */
502   ((TYPE_UNSIGNED (type) ? ax_zero_ext : ax_ext) (ax, bits));
503 }
504
505
506 /* Assume that the top of the stack contains a value of type "pointer
507    to TYPE"; generate code to fetch its value.  Note that TYPE is the
508    target type, not the pointer type.  */
509 static void
510 gen_fetch (struct agent_expr *ax, struct type *type)
511 {
512   if (trace_kludge)
513     {
514       /* Record the area of memory we're about to fetch.  */
515       ax_trace_quick (ax, TYPE_LENGTH (type));
516     }
517
518   switch (TYPE_CODE (type))
519     {
520     case TYPE_CODE_PTR:
521     case TYPE_CODE_REF:
522     case TYPE_CODE_ENUM:
523     case TYPE_CODE_INT:
524     case TYPE_CODE_CHAR:
525     case TYPE_CODE_BOOL:
526       /* It's a scalar value, so we know how to dereference it.  How
527          many bytes long is it?  */
528       switch (TYPE_LENGTH (type))
529         {
530         case 8 / TARGET_CHAR_BIT:
531           ax_simple (ax, aop_ref8);
532           break;
533         case 16 / TARGET_CHAR_BIT:
534           ax_simple (ax, aop_ref16);
535           break;
536         case 32 / TARGET_CHAR_BIT:
537           ax_simple (ax, aop_ref32);
538           break;
539         case 64 / TARGET_CHAR_BIT:
540           ax_simple (ax, aop_ref64);
541           break;
542
543           /* Either our caller shouldn't have asked us to dereference
544              that pointer (other code's fault), or we're not
545              implementing something we should be (this code's fault).
546              In any case, it's a bug the user shouldn't see.  */
547         default:
548           internal_error (__FILE__, __LINE__,
549                           _("gen_fetch: strange size"));
550         }
551
552       gen_sign_extend (ax, type);
553       break;
554
555     default:
556       /* Either our caller shouldn't have asked us to dereference that
557          pointer (other code's fault), or we're not implementing
558          something we should be (this code's fault).  In any case,
559          it's a bug the user shouldn't see.  */
560       internal_error (__FILE__, __LINE__,
561                       _("gen_fetch: bad type code"));
562     }
563 }
564
565
566 /* Generate code to left shift the top of the stack by DISTANCE bits, or
567    right shift it by -DISTANCE bits if DISTANCE < 0.  This generates
568    unsigned (logical) right shifts.  */
569 static void
570 gen_left_shift (struct agent_expr *ax, int distance)
571 {
572   if (distance > 0)
573     {
574       ax_const_l (ax, distance);
575       ax_simple (ax, aop_lsh);
576     }
577   else if (distance < 0)
578     {
579       ax_const_l (ax, -distance);
580       ax_simple (ax, aop_rsh_unsigned);
581     }
582 }
583 \f
584
585
586 /* Generating bytecode from GDB expressions: symbol references */
587
588 /* Generate code to push the base address of the argument portion of
589    the top stack frame.  */
590 static void
591 gen_frame_args_address (struct gdbarch *gdbarch, struct agent_expr *ax)
592 {
593   int frame_reg;
594   LONGEST frame_offset;
595
596   gdbarch_virtual_frame_pointer (gdbarch,
597                                  ax->scope, &frame_reg, &frame_offset);
598   ax_reg (ax, frame_reg);
599   gen_offset (ax, frame_offset);
600 }
601
602
603 /* Generate code to push the base address of the locals portion of the
604    top stack frame.  */
605 static void
606 gen_frame_locals_address (struct gdbarch *gdbarch, struct agent_expr *ax)
607 {
608   int frame_reg;
609   LONGEST frame_offset;
610
611   gdbarch_virtual_frame_pointer (gdbarch,
612                                  ax->scope, &frame_reg, &frame_offset);
613   ax_reg (ax, frame_reg);
614   gen_offset (ax, frame_offset);
615 }
616
617
618 /* Generate code to add OFFSET to the top of the stack.  Try to
619    generate short and readable code.  We use this for getting to
620    variables on the stack, and structure members.  If we were
621    programming in ML, it would be clearer why these are the same
622    thing.  */
623 static void
624 gen_offset (struct agent_expr *ax, int offset)
625 {
626   /* It would suffice to simply push the offset and add it, but this
627      makes it easier to read positive and negative offsets in the
628      bytecode.  */
629   if (offset > 0)
630     {
631       ax_const_l (ax, offset);
632       ax_simple (ax, aop_add);
633     }
634   else if (offset < 0)
635     {
636       ax_const_l (ax, -offset);
637       ax_simple (ax, aop_sub);
638     }
639 }
640
641
642 /* In many cases, a symbol's value is the offset from some other
643    address (stack frame, base register, etc.)  Generate code to add
644    VAR's value to the top of the stack.  */
645 static void
646 gen_sym_offset (struct agent_expr *ax, struct symbol *var)
647 {
648   gen_offset (ax, SYMBOL_VALUE (var));
649 }
650
651
652 /* Generate code for a variable reference to AX.  The variable is the
653    symbol VAR.  Set VALUE to describe the result.  */
654
655 static void
656 gen_var_ref (struct gdbarch *gdbarch, struct agent_expr *ax,
657              struct axs_value *value, struct symbol *var)
658 {
659   /* Dereference any typedefs.  */
660   value->type = check_typedef (SYMBOL_TYPE (var));
661   value->optimized_out = 0;
662
663   /* I'm imitating the code in read_var_value.  */
664   switch (SYMBOL_CLASS (var))
665     {
666     case LOC_CONST:             /* A constant, like an enum value.  */
667       ax_const_l (ax, (LONGEST) SYMBOL_VALUE (var));
668       value->kind = axs_rvalue;
669       break;
670
671     case LOC_LABEL:             /* A goto label, being used as a value.  */
672       ax_const_l (ax, (LONGEST) SYMBOL_VALUE_ADDRESS (var));
673       value->kind = axs_rvalue;
674       break;
675
676     case LOC_CONST_BYTES:
677       internal_error (__FILE__, __LINE__,
678                       _("gen_var_ref: LOC_CONST_BYTES "
679                         "symbols are not supported"));
680
681       /* Variable at a fixed location in memory.  Easy.  */
682     case LOC_STATIC:
683       /* Push the address of the variable.  */
684       ax_const_l (ax, SYMBOL_VALUE_ADDRESS (var));
685       value->kind = axs_lvalue_memory;
686       break;
687
688     case LOC_ARG:               /* var lives in argument area of frame */
689       gen_frame_args_address (gdbarch, ax);
690       gen_sym_offset (ax, var);
691       value->kind = axs_lvalue_memory;
692       break;
693
694     case LOC_REF_ARG:           /* As above, but the frame slot really
695                                    holds the address of the variable.  */
696       gen_frame_args_address (gdbarch, ax);
697       gen_sym_offset (ax, var);
698       /* Don't assume any particular pointer size.  */
699       gen_fetch (ax, builtin_type (gdbarch)->builtin_data_ptr);
700       value->kind = axs_lvalue_memory;
701       break;
702
703     case LOC_LOCAL:             /* var lives in locals area of frame */
704       gen_frame_locals_address (gdbarch, ax);
705       gen_sym_offset (ax, var);
706       value->kind = axs_lvalue_memory;
707       break;
708
709     case LOC_TYPEDEF:
710       error (_("Cannot compute value of typedef `%s'."),
711              SYMBOL_PRINT_NAME (var));
712       break;
713
714     case LOC_BLOCK:
715       ax_const_l (ax, BLOCK_START (SYMBOL_BLOCK_VALUE (var)));
716       value->kind = axs_rvalue;
717       break;
718
719     case LOC_REGISTER:
720       /* Don't generate any code at all; in the process of treating
721          this as an lvalue or rvalue, the caller will generate the
722          right code.  */
723       value->kind = axs_lvalue_register;
724       value->u.reg = SYMBOL_REGISTER_OPS (var)->register_number (var, gdbarch);
725       break;
726
727       /* A lot like LOC_REF_ARG, but the pointer lives directly in a
728          register, not on the stack.  Simpler than LOC_REGISTER
729          because it's just like any other case where the thing
730          has a real address.  */
731     case LOC_REGPARM_ADDR:
732       ax_reg (ax, SYMBOL_REGISTER_OPS (var)->register_number (var, gdbarch));
733       value->kind = axs_lvalue_memory;
734       break;
735
736     case LOC_UNRESOLVED:
737       {
738         struct minimal_symbol *msym
739           = lookup_minimal_symbol (SYMBOL_LINKAGE_NAME (var), NULL, NULL);
740
741         if (!msym)
742           error (_("Couldn't resolve symbol `%s'."), SYMBOL_PRINT_NAME (var));
743
744         /* Push the address of the variable.  */
745         ax_const_l (ax, SYMBOL_VALUE_ADDRESS (msym));
746         value->kind = axs_lvalue_memory;
747       }
748       break;
749
750     case LOC_COMPUTED:
751       /* FIXME: cagney/2004-01-26: It should be possible to
752          unconditionally call the SYMBOL_COMPUTED_OPS method when available.
753          Unfortunately DWARF 2 stores the frame-base (instead of the
754          function) location in a function's symbol.  Oops!  For the
755          moment enable this when/where applicable.  */
756       SYMBOL_COMPUTED_OPS (var)->tracepoint_var_ref (var, gdbarch, ax, value);
757       break;
758
759     case LOC_OPTIMIZED_OUT:
760       /* Flag this, but don't say anything; leave it up to callers to
761          warn the user.  */
762       value->optimized_out = 1;
763       break;
764
765     default:
766       error (_("Cannot find value of botched symbol `%s'."),
767              SYMBOL_PRINT_NAME (var));
768       break;
769     }
770 }
771 \f
772
773
774 /* Generating bytecode from GDB expressions: literals */
775
776 static void
777 gen_int_literal (struct agent_expr *ax, struct axs_value *value, LONGEST k,
778                  struct type *type)
779 {
780   ax_const_l (ax, k);
781   value->kind = axs_rvalue;
782   value->type = check_typedef (type);
783 }
784 \f
785
786
787 /* Generating bytecode from GDB expressions: unary conversions, casts */
788
789 /* Take what's on the top of the stack (as described by VALUE), and
790    try to make an rvalue out of it.  Signal an error if we can't do
791    that.  */
792 static void
793 require_rvalue (struct agent_expr *ax, struct axs_value *value)
794 {
795   /* Only deal with scalars, structs and such may be too large
796      to fit in a stack entry.  */
797   value->type = check_typedef (value->type);
798   if (TYPE_CODE (value->type) == TYPE_CODE_ARRAY
799       || TYPE_CODE (value->type) == TYPE_CODE_STRUCT
800       || TYPE_CODE (value->type) == TYPE_CODE_UNION
801       || TYPE_CODE (value->type) == TYPE_CODE_FUNC)
802     error (_("Value not scalar: cannot be an rvalue."));
803
804   switch (value->kind)
805     {
806     case axs_rvalue:
807       /* It's already an rvalue.  */
808       break;
809
810     case axs_lvalue_memory:
811       /* The top of stack is the address of the object.  Dereference.  */
812       gen_fetch (ax, value->type);
813       break;
814
815     case axs_lvalue_register:
816       /* There's nothing on the stack, but value->u.reg is the
817          register number containing the value.
818
819          When we add floating-point support, this is going to have to
820          change.  What about SPARC register pairs, for example?  */
821       ax_reg (ax, value->u.reg);
822       gen_extend (ax, value->type);
823       break;
824     }
825
826   value->kind = axs_rvalue;
827 }
828
829
830 /* Assume the top of the stack is described by VALUE, and perform the
831    usual unary conversions.  This is motivated by ANSI 6.2.2, but of
832    course GDB expressions are not ANSI; they're the mishmash union of
833    a bunch of languages.  Rah.
834
835    NOTE!  This function promises to produce an rvalue only when the
836    incoming value is of an appropriate type.  In other words, the
837    consumer of the value this function produces may assume the value
838    is an rvalue only after checking its type.
839
840    The immediate issue is that if the user tries to use a structure or
841    union as an operand of, say, the `+' operator, we don't want to try
842    to convert that structure to an rvalue; require_rvalue will bomb on
843    structs and unions.  Rather, we want to simply pass the struct
844    lvalue through unchanged, and let `+' raise an error.  */
845
846 static void
847 gen_usual_unary (struct expression *exp, struct agent_expr *ax,
848                  struct axs_value *value)
849 {
850   /* We don't have to generate any code for the usual integral
851      conversions, since values are always represented as full-width on
852      the stack.  Should we tweak the type?  */
853
854   /* Some types require special handling.  */
855   switch (TYPE_CODE (value->type))
856     {
857       /* Functions get converted to a pointer to the function.  */
858     case TYPE_CODE_FUNC:
859       value->type = lookup_pointer_type (value->type);
860       value->kind = axs_rvalue; /* Should always be true, but just in case.  */
861       break;
862
863       /* Arrays get converted to a pointer to their first element, and
864          are no longer an lvalue.  */
865     case TYPE_CODE_ARRAY:
866       {
867         struct type *elements = TYPE_TARGET_TYPE (value->type);
868
869         value->type = lookup_pointer_type (elements);
870         value->kind = axs_rvalue;
871         /* We don't need to generate any code; the address of the array
872            is also the address of its first element.  */
873       }
874       break;
875
876       /* Don't try to convert structures and unions to rvalues.  Let the
877          consumer signal an error.  */
878     case TYPE_CODE_STRUCT:
879     case TYPE_CODE_UNION:
880       return;
881     }
882
883   /* If the value is an lvalue, dereference it.  */
884   require_rvalue (ax, value);
885 }
886
887
888 /* Return non-zero iff the type TYPE1 is considered "wider" than the
889    type TYPE2, according to the rules described in gen_usual_arithmetic.  */
890 static int
891 type_wider_than (struct type *type1, struct type *type2)
892 {
893   return (TYPE_LENGTH (type1) > TYPE_LENGTH (type2)
894           || (TYPE_LENGTH (type1) == TYPE_LENGTH (type2)
895               && TYPE_UNSIGNED (type1)
896               && !TYPE_UNSIGNED (type2)));
897 }
898
899
900 /* Return the "wider" of the two types TYPE1 and TYPE2.  */
901 static struct type *
902 max_type (struct type *type1, struct type *type2)
903 {
904   return type_wider_than (type1, type2) ? type1 : type2;
905 }
906
907
908 /* Generate code to convert a scalar value of type FROM to type TO.  */
909 static void
910 gen_conversion (struct agent_expr *ax, struct type *from, struct type *to)
911 {
912   /* Perhaps there is a more graceful way to state these rules.  */
913
914   /* If we're converting to a narrower type, then we need to clear out
915      the upper bits.  */
916   if (TYPE_LENGTH (to) < TYPE_LENGTH (from))
917     gen_extend (ax, from);
918
919   /* If the two values have equal width, but different signednesses,
920      then we need to extend.  */
921   else if (TYPE_LENGTH (to) == TYPE_LENGTH (from))
922     {
923       if (TYPE_UNSIGNED (from) != TYPE_UNSIGNED (to))
924         gen_extend (ax, to);
925     }
926
927   /* If we're converting to a wider type, and becoming unsigned, then
928      we need to zero out any possible sign bits.  */
929   else if (TYPE_LENGTH (to) > TYPE_LENGTH (from))
930     {
931       if (TYPE_UNSIGNED (to))
932         gen_extend (ax, to);
933     }
934 }
935
936
937 /* Return non-zero iff the type FROM will require any bytecodes to be
938    emitted to be converted to the type TO.  */
939 static int
940 is_nontrivial_conversion (struct type *from, struct type *to)
941 {
942   struct agent_expr *ax = new_agent_expr (NULL, 0);
943   int nontrivial;
944
945   /* Actually generate the code, and see if anything came out.  At the
946      moment, it would be trivial to replicate the code in
947      gen_conversion here, but in the future, when we're supporting
948      floating point and the like, it may not be.  Doing things this
949      way allows this function to be independent of the logic in
950      gen_conversion.  */
951   gen_conversion (ax, from, to);
952   nontrivial = ax->len > 0;
953   free_agent_expr (ax);
954   return nontrivial;
955 }
956
957
958 /* Generate code to perform the "usual arithmetic conversions" (ANSI C
959    6.2.1.5) for the two operands of an arithmetic operator.  This
960    effectively finds a "least upper bound" type for the two arguments,
961    and promotes each argument to that type.  *VALUE1 and *VALUE2
962    describe the values as they are passed in, and as they are left.  */
963 static void
964 gen_usual_arithmetic (struct expression *exp, struct agent_expr *ax,
965                       struct axs_value *value1, struct axs_value *value2)
966 {
967   /* Do the usual binary conversions.  */
968   if (TYPE_CODE (value1->type) == TYPE_CODE_INT
969       && TYPE_CODE (value2->type) == TYPE_CODE_INT)
970     {
971       /* The ANSI integral promotions seem to work this way: Order the
972          integer types by size, and then by signedness: an n-bit
973          unsigned type is considered "wider" than an n-bit signed
974          type.  Promote to the "wider" of the two types, and always
975          promote at least to int.  */
976       struct type *target = max_type (builtin_type (exp->gdbarch)->builtin_int,
977                                       max_type (value1->type, value2->type));
978
979       /* Deal with value2, on the top of the stack.  */
980       gen_conversion (ax, value2->type, target);
981
982       /* Deal with value1, not on the top of the stack.  Don't
983          generate the `swap' instructions if we're not actually going
984          to do anything.  */
985       if (is_nontrivial_conversion (value1->type, target))
986         {
987           ax_simple (ax, aop_swap);
988           gen_conversion (ax, value1->type, target);
989           ax_simple (ax, aop_swap);
990         }
991
992       value1->type = value2->type = check_typedef (target);
993     }
994 }
995
996
997 /* Generate code to perform the integral promotions (ANSI 6.2.1.1) on
998    the value on the top of the stack, as described by VALUE.  Assume
999    the value has integral type.  */
1000 static void
1001 gen_integral_promotions (struct expression *exp, struct agent_expr *ax,
1002                          struct axs_value *value)
1003 {
1004   const struct builtin_type *builtin = builtin_type (exp->gdbarch);
1005
1006   if (!type_wider_than (value->type, builtin->builtin_int))
1007     {
1008       gen_conversion (ax, value->type, builtin->builtin_int);
1009       value->type = builtin->builtin_int;
1010     }
1011   else if (!type_wider_than (value->type, builtin->builtin_unsigned_int))
1012     {
1013       gen_conversion (ax, value->type, builtin->builtin_unsigned_int);
1014       value->type = builtin->builtin_unsigned_int;
1015     }
1016 }
1017
1018
1019 /* Generate code for a cast to TYPE.  */
1020 static void
1021 gen_cast (struct agent_expr *ax, struct axs_value *value, struct type *type)
1022 {
1023   /* GCC does allow casts to yield lvalues, so this should be fixed
1024      before merging these changes into the trunk.  */
1025   require_rvalue (ax, value);
1026   /* Dereference typedefs.  */
1027   type = check_typedef (type);
1028
1029   switch (TYPE_CODE (type))
1030     {
1031     case TYPE_CODE_PTR:
1032     case TYPE_CODE_REF:
1033       /* It's implementation-defined, and I'll bet this is what GCC
1034          does.  */
1035       break;
1036
1037     case TYPE_CODE_ARRAY:
1038     case TYPE_CODE_STRUCT:
1039     case TYPE_CODE_UNION:
1040     case TYPE_CODE_FUNC:
1041       error (_("Invalid type cast: intended type must be scalar."));
1042
1043     case TYPE_CODE_ENUM:
1044     case TYPE_CODE_BOOL:
1045       /* We don't have to worry about the size of the value, because
1046          all our integral values are fully sign-extended, and when
1047          casting pointers we can do anything we like.  Is there any
1048          way for us to know what GCC actually does with a cast like
1049          this?  */
1050       break;
1051
1052     case TYPE_CODE_INT:
1053       gen_conversion (ax, value->type, type);
1054       break;
1055
1056     case TYPE_CODE_VOID:
1057       /* We could pop the value, and rely on everyone else to check
1058          the type and notice that this value doesn't occupy a stack
1059          slot.  But for now, leave the value on the stack, and
1060          preserve the "value == stack element" assumption.  */
1061       break;
1062
1063     default:
1064       error (_("Casts to requested type are not yet implemented."));
1065     }
1066
1067   value->type = type;
1068 }
1069 \f
1070
1071
1072 /* Generating bytecode from GDB expressions: arithmetic */
1073
1074 /* Scale the integer on the top of the stack by the size of the target
1075    of the pointer type TYPE.  */
1076 static void
1077 gen_scale (struct agent_expr *ax, enum agent_op op, struct type *type)
1078 {
1079   struct type *element = TYPE_TARGET_TYPE (type);
1080
1081   if (TYPE_LENGTH (element) != 1)
1082     {
1083       ax_const_l (ax, TYPE_LENGTH (element));
1084       ax_simple (ax, op);
1085     }
1086 }
1087
1088
1089 /* Generate code for pointer arithmetic PTR + INT.  */
1090 static void
1091 gen_ptradd (struct agent_expr *ax, struct axs_value *value,
1092             struct axs_value *value1, struct axs_value *value2)
1093 {
1094   gdb_assert (pointer_type (value1->type));
1095   gdb_assert (TYPE_CODE (value2->type) == TYPE_CODE_INT);
1096
1097   gen_scale (ax, aop_mul, value1->type);
1098   ax_simple (ax, aop_add);
1099   gen_extend (ax, value1->type);        /* Catch overflow.  */
1100   value->type = value1->type;
1101   value->kind = axs_rvalue;
1102 }
1103
1104
1105 /* Generate code for pointer arithmetic PTR - INT.  */
1106 static void
1107 gen_ptrsub (struct agent_expr *ax, struct axs_value *value,
1108             struct axs_value *value1, struct axs_value *value2)
1109 {
1110   gdb_assert (pointer_type (value1->type));
1111   gdb_assert (TYPE_CODE (value2->type) == TYPE_CODE_INT);
1112
1113   gen_scale (ax, aop_mul, value1->type);
1114   ax_simple (ax, aop_sub);
1115   gen_extend (ax, value1->type);        /* Catch overflow.  */
1116   value->type = value1->type;
1117   value->kind = axs_rvalue;
1118 }
1119
1120
1121 /* Generate code for pointer arithmetic PTR - PTR.  */
1122 static void
1123 gen_ptrdiff (struct agent_expr *ax, struct axs_value *value,
1124              struct axs_value *value1, struct axs_value *value2,
1125              struct type *result_type)
1126 {
1127   gdb_assert (pointer_type (value1->type));
1128   gdb_assert (pointer_type (value2->type));
1129
1130   if (TYPE_LENGTH (TYPE_TARGET_TYPE (value1->type))
1131       != TYPE_LENGTH (TYPE_TARGET_TYPE (value2->type)))
1132     error (_("\
1133 First argument of `-' is a pointer, but second argument is neither\n\
1134 an integer nor a pointer of the same type."));
1135
1136   ax_simple (ax, aop_sub);
1137   gen_scale (ax, aop_div_unsigned, value1->type);
1138   value->type = result_type;
1139   value->kind = axs_rvalue;
1140 }
1141
1142 static void
1143 gen_equal (struct agent_expr *ax, struct axs_value *value,
1144            struct axs_value *value1, struct axs_value *value2,
1145            struct type *result_type)
1146 {
1147   if (pointer_type (value1->type) || pointer_type (value2->type))
1148     ax_simple (ax, aop_equal);
1149   else
1150     gen_binop (ax, value, value1, value2,
1151                aop_equal, aop_equal, 0, "equal");
1152   value->type = result_type;
1153   value->kind = axs_rvalue;
1154 }
1155
1156 static void
1157 gen_less (struct agent_expr *ax, struct axs_value *value,
1158           struct axs_value *value1, struct axs_value *value2,
1159           struct type *result_type)
1160 {
1161   if (pointer_type (value1->type) || pointer_type (value2->type))
1162     ax_simple (ax, aop_less_unsigned);
1163   else
1164     gen_binop (ax, value, value1, value2,
1165                aop_less_signed, aop_less_unsigned, 0, "less than");
1166   value->type = result_type;
1167   value->kind = axs_rvalue;
1168 }
1169
1170 /* Generate code for a binary operator that doesn't do pointer magic.
1171    We set VALUE to describe the result value; we assume VALUE1 and
1172    VALUE2 describe the two operands, and that they've undergone the
1173    usual binary conversions.  MAY_CARRY should be non-zero iff the
1174    result needs to be extended.  NAME is the English name of the
1175    operator, used in error messages */
1176 static void
1177 gen_binop (struct agent_expr *ax, struct axs_value *value,
1178            struct axs_value *value1, struct axs_value *value2,
1179            enum agent_op op, enum agent_op op_unsigned,
1180            int may_carry, char *name)
1181 {
1182   /* We only handle INT op INT.  */
1183   if ((TYPE_CODE (value1->type) != TYPE_CODE_INT)
1184       || (TYPE_CODE (value2->type) != TYPE_CODE_INT))
1185     error (_("Invalid combination of types in %s."), name);
1186
1187   ax_simple (ax,
1188              TYPE_UNSIGNED (value1->type) ? op_unsigned : op);
1189   if (may_carry)
1190     gen_extend (ax, value1->type);      /* catch overflow */
1191   value->type = value1->type;
1192   value->kind = axs_rvalue;
1193 }
1194
1195
1196 static void
1197 gen_logical_not (struct agent_expr *ax, struct axs_value *value,
1198                  struct type *result_type)
1199 {
1200   if (TYPE_CODE (value->type) != TYPE_CODE_INT
1201       && TYPE_CODE (value->type) != TYPE_CODE_PTR)
1202     error (_("Invalid type of operand to `!'."));
1203
1204   ax_simple (ax, aop_log_not);
1205   value->type = result_type;
1206 }
1207
1208
1209 static void
1210 gen_complement (struct agent_expr *ax, struct axs_value *value)
1211 {
1212   if (TYPE_CODE (value->type) != TYPE_CODE_INT)
1213     error (_("Invalid type of operand to `~'."));
1214
1215   ax_simple (ax, aop_bit_not);
1216   gen_extend (ax, value->type);
1217 }
1218 \f
1219
1220
1221 /* Generating bytecode from GDB expressions: * & . -> @ sizeof */
1222
1223 /* Dereference the value on the top of the stack.  */
1224 static void
1225 gen_deref (struct agent_expr *ax, struct axs_value *value)
1226 {
1227   /* The caller should check the type, because several operators use
1228      this, and we don't know what error message to generate.  */
1229   if (!pointer_type (value->type))
1230     internal_error (__FILE__, __LINE__,
1231                     _("gen_deref: expected a pointer"));
1232
1233   /* We've got an rvalue now, which is a pointer.  We want to yield an
1234      lvalue, whose address is exactly that pointer.  So we don't
1235      actually emit any code; we just change the type from "Pointer to
1236      T" to "T", and mark the value as an lvalue in memory.  Leave it
1237      to the consumer to actually dereference it.  */
1238   value->type = check_typedef (TYPE_TARGET_TYPE (value->type));
1239   if (TYPE_CODE (value->type) == TYPE_CODE_VOID)
1240     error (_("Attempt to dereference a generic pointer."));
1241   value->kind = ((TYPE_CODE (value->type) == TYPE_CODE_FUNC)
1242                  ? axs_rvalue : axs_lvalue_memory);
1243 }
1244
1245
1246 /* Produce the address of the lvalue on the top of the stack.  */
1247 static void
1248 gen_address_of (struct agent_expr *ax, struct axs_value *value)
1249 {
1250   /* Special case for taking the address of a function.  The ANSI
1251      standard describes this as a special case, too, so this
1252      arrangement is not without motivation.  */
1253   if (TYPE_CODE (value->type) == TYPE_CODE_FUNC)
1254     /* The value's already an rvalue on the stack, so we just need to
1255        change the type.  */
1256     value->type = lookup_pointer_type (value->type);
1257   else
1258     switch (value->kind)
1259       {
1260       case axs_rvalue:
1261         error (_("Operand of `&' is an rvalue, which has no address."));
1262
1263       case axs_lvalue_register:
1264         error (_("Operand of `&' is in a register, and has no address."));
1265
1266       case axs_lvalue_memory:
1267         value->kind = axs_rvalue;
1268         value->type = lookup_pointer_type (value->type);
1269         break;
1270       }
1271 }
1272
1273 /* Generate code to push the value of a bitfield of a structure whose
1274    address is on the top of the stack.  START and END give the
1275    starting and one-past-ending *bit* numbers of the field within the
1276    structure.  */
1277 static void
1278 gen_bitfield_ref (struct expression *exp, struct agent_expr *ax,
1279                   struct axs_value *value, struct type *type,
1280                   int start, int end)
1281 {
1282   /* Note that ops[i] fetches 8 << i bits.  */
1283   static enum agent_op ops[]
1284     = {aop_ref8, aop_ref16, aop_ref32, aop_ref64};
1285   static int num_ops = (sizeof (ops) / sizeof (ops[0]));
1286
1287   /* We don't want to touch any byte that the bitfield doesn't
1288      actually occupy; we shouldn't make any accesses we're not
1289      explicitly permitted to.  We rely here on the fact that the
1290      bytecode `ref' operators work on unaligned addresses.
1291
1292      It takes some fancy footwork to get the stack to work the way
1293      we'd like.  Say we're retrieving a bitfield that requires three
1294      fetches.  Initially, the stack just contains the address:
1295      addr
1296      For the first fetch, we duplicate the address
1297      addr addr
1298      then add the byte offset, do the fetch, and shift and mask as
1299      needed, yielding a fragment of the value, properly aligned for
1300      the final bitwise or:
1301      addr frag1
1302      then we swap, and repeat the process:
1303      frag1 addr                    --- address on top
1304      frag1 addr addr               --- duplicate it
1305      frag1 addr frag2              --- get second fragment
1306      frag1 frag2 addr              --- swap again
1307      frag1 frag2 frag3             --- get third fragment
1308      Notice that, since the third fragment is the last one, we don't
1309      bother duplicating the address this time.  Now we have all the
1310      fragments on the stack, and we can simply `or' them together,
1311      yielding the final value of the bitfield.  */
1312
1313   /* The first and one-after-last bits in the field, but rounded down
1314      and up to byte boundaries.  */
1315   int bound_start = (start / TARGET_CHAR_BIT) * TARGET_CHAR_BIT;
1316   int bound_end = (((end + TARGET_CHAR_BIT - 1)
1317                     / TARGET_CHAR_BIT)
1318                    * TARGET_CHAR_BIT);
1319
1320   /* current bit offset within the structure */
1321   int offset;
1322
1323   /* The index in ops of the opcode we're considering.  */
1324   int op;
1325
1326   /* The number of fragments we generated in the process.  Probably
1327      equal to the number of `one' bits in bytesize, but who cares?  */
1328   int fragment_count;
1329
1330   /* Dereference any typedefs.  */
1331   type = check_typedef (type);
1332
1333   /* Can we fetch the number of bits requested at all?  */
1334   if ((end - start) > ((1 << num_ops) * 8))
1335     internal_error (__FILE__, __LINE__,
1336                     _("gen_bitfield_ref: bitfield too wide"));
1337
1338   /* Note that we know here that we only need to try each opcode once.
1339      That may not be true on machines with weird byte sizes.  */
1340   offset = bound_start;
1341   fragment_count = 0;
1342   for (op = num_ops - 1; op >= 0; op--)
1343     {
1344       /* number of bits that ops[op] would fetch */
1345       int op_size = 8 << op;
1346
1347       /* The stack at this point, from bottom to top, contains zero or
1348          more fragments, then the address.  */
1349
1350       /* Does this fetch fit within the bitfield?  */
1351       if (offset + op_size <= bound_end)
1352         {
1353           /* Is this the last fragment?  */
1354           int last_frag = (offset + op_size == bound_end);
1355
1356           if (!last_frag)
1357             ax_simple (ax, aop_dup);    /* keep a copy of the address */
1358
1359           /* Add the offset.  */
1360           gen_offset (ax, offset / TARGET_CHAR_BIT);
1361
1362           if (trace_kludge)
1363             {
1364               /* Record the area of memory we're about to fetch.  */
1365               ax_trace_quick (ax, op_size / TARGET_CHAR_BIT);
1366             }
1367
1368           /* Perform the fetch.  */
1369           ax_simple (ax, ops[op]);
1370
1371           /* Shift the bits we have to their proper position.
1372              gen_left_shift will generate right shifts when the operand
1373              is negative.
1374
1375              A big-endian field diagram to ponder:
1376              byte 0  byte 1  byte 2  byte 3  byte 4  byte 5  byte 6  byte 7
1377              +------++------++------++------++------++------++------++------+
1378              xxxxAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBCCCCCxxxxxxxxxxx
1379              ^               ^               ^    ^
1380              bit number      16              32              48   53
1381              These are bit numbers as supplied by GDB.  Note that the
1382              bit numbers run from right to left once you've fetched the
1383              value!
1384
1385              A little-endian field diagram to ponder:
1386              byte 7  byte 6  byte 5  byte 4  byte 3  byte 2  byte 1  byte 0
1387              +------++------++------++------++------++------++------++------+
1388              xxxxxxxxxxxAAAAABBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCxxxx
1389              ^               ^               ^           ^   ^
1390              bit number     48              32              16          4   0
1391
1392              In both cases, the most significant end is on the left
1393              (i.e. normal numeric writing order), which means that you
1394              don't go crazy thinking about `left' and `right' shifts.
1395
1396              We don't have to worry about masking yet:
1397              - If they contain garbage off the least significant end, then we
1398              must be looking at the low end of the field, and the right
1399              shift will wipe them out.
1400              - If they contain garbage off the most significant end, then we
1401              must be looking at the most significant end of the word, and
1402              the sign/zero extension will wipe them out.
1403              - If we're in the interior of the word, then there is no garbage
1404              on either end, because the ref operators zero-extend.  */
1405           if (gdbarch_byte_order (exp->gdbarch) == BFD_ENDIAN_BIG)
1406             gen_left_shift (ax, end - (offset + op_size));
1407           else
1408             gen_left_shift (ax, offset - start);
1409
1410           if (!last_frag)
1411             /* Bring the copy of the address up to the top.  */
1412             ax_simple (ax, aop_swap);
1413
1414           offset += op_size;
1415           fragment_count++;
1416         }
1417     }
1418
1419   /* Generate enough bitwise `or' operations to combine all the
1420      fragments we left on the stack.  */
1421   while (fragment_count-- > 1)
1422     ax_simple (ax, aop_bit_or);
1423
1424   /* Sign- or zero-extend the value as appropriate.  */
1425   ((TYPE_UNSIGNED (type) ? ax_zero_ext : ax_ext) (ax, end - start));
1426
1427   /* This is *not* an lvalue.  Ugh.  */
1428   value->kind = axs_rvalue;
1429   value->type = type;
1430 }
1431
1432 /* Generate bytecodes for field number FIELDNO of type TYPE.  OFFSET
1433    is an accumulated offset (in bytes), will be nonzero for objects
1434    embedded in other objects, like C++ base classes.  Behavior should
1435    generally follow value_primitive_field.  */
1436
1437 static void
1438 gen_primitive_field (struct expression *exp,
1439                      struct agent_expr *ax, struct axs_value *value,
1440                      int offset, int fieldno, struct type *type)
1441 {
1442   /* Is this a bitfield?  */
1443   if (TYPE_FIELD_PACKED (type, fieldno))
1444     gen_bitfield_ref (exp, ax, value, TYPE_FIELD_TYPE (type, fieldno),
1445                       (offset * TARGET_CHAR_BIT
1446                        + TYPE_FIELD_BITPOS (type, fieldno)),
1447                       (offset * TARGET_CHAR_BIT
1448                        + TYPE_FIELD_BITPOS (type, fieldno)
1449                        + TYPE_FIELD_BITSIZE (type, fieldno)));
1450   else
1451     {
1452       gen_offset (ax, offset
1453                   + TYPE_FIELD_BITPOS (type, fieldno) / TARGET_CHAR_BIT);
1454       value->kind = axs_lvalue_memory;
1455       value->type = TYPE_FIELD_TYPE (type, fieldno);
1456     }
1457 }
1458
1459 /* Search for the given field in either the given type or one of its
1460    base classes.  Return 1 if found, 0 if not.  */
1461
1462 static int
1463 gen_struct_ref_recursive (struct expression *exp, struct agent_expr *ax,
1464                           struct axs_value *value,
1465                           char *field, int offset, struct type *type)
1466 {
1467   int i, rslt;
1468   int nbases = TYPE_N_BASECLASSES (type);
1469
1470   CHECK_TYPEDEF (type);
1471
1472   for (i = TYPE_NFIELDS (type) - 1; i >= nbases; i--)
1473     {
1474       const char *this_name = TYPE_FIELD_NAME (type, i);
1475
1476       if (this_name)
1477         {
1478           if (strcmp (field, this_name) == 0)
1479             {
1480               /* Note that bytecodes for the struct's base (aka
1481                  "this") will have been generated already, which will
1482                  be unnecessary but not harmful if the static field is
1483                  being handled as a global.  */
1484               if (field_is_static (&TYPE_FIELD (type, i)))
1485                 {
1486                   gen_static_field (exp->gdbarch, ax, value, type, i);
1487                   if (value->optimized_out)
1488                     error (_("static field `%s' has been "
1489                              "optimized out, cannot use"),
1490                            field);
1491                   return 1;
1492                 }
1493
1494               gen_primitive_field (exp, ax, value, offset, i, type);
1495               return 1;
1496             }
1497 #if 0 /* is this right? */
1498           if (this_name[0] == '\0')
1499             internal_error (__FILE__, __LINE__,
1500                             _("find_field: anonymous unions not supported"));
1501 #endif
1502         }
1503     }
1504
1505   /* Now scan through base classes recursively.  */
1506   for (i = 0; i < nbases; i++)
1507     {
1508       struct type *basetype = check_typedef (TYPE_BASECLASS (type, i));
1509
1510       rslt = gen_struct_ref_recursive (exp, ax, value, field,
1511                                        offset + TYPE_BASECLASS_BITPOS (type, i)
1512                                        / TARGET_CHAR_BIT,
1513                                        basetype);
1514       if (rslt)
1515         return 1;
1516     }
1517
1518   /* Not found anywhere, flag so caller can complain.  */
1519   return 0;
1520 }
1521
1522 /* Generate code to reference the member named FIELD of a structure or
1523    union.  The top of the stack, as described by VALUE, should have
1524    type (pointer to a)* struct/union.  OPERATOR_NAME is the name of
1525    the operator being compiled, and OPERAND_NAME is the kind of thing
1526    it operates on; we use them in error messages.  */
1527 static void
1528 gen_struct_ref (struct expression *exp, struct agent_expr *ax,
1529                 struct axs_value *value, char *field,
1530                 char *operator_name, char *operand_name)
1531 {
1532   struct type *type;
1533   int found;
1534
1535   /* Follow pointers until we reach a non-pointer.  These aren't the C
1536      semantics, but they're what the normal GDB evaluator does, so we
1537      should at least be consistent.  */
1538   while (pointer_type (value->type))
1539     {
1540       require_rvalue (ax, value);
1541       gen_deref (ax, value);
1542     }
1543   type = check_typedef (value->type);
1544
1545   /* This must yield a structure or a union.  */
1546   if (TYPE_CODE (type) != TYPE_CODE_STRUCT
1547       && TYPE_CODE (type) != TYPE_CODE_UNION)
1548     error (_("The left operand of `%s' is not a %s."),
1549            operator_name, operand_name);
1550
1551   /* And it must be in memory; we don't deal with structure rvalues,
1552      or structures living in registers.  */
1553   if (value->kind != axs_lvalue_memory)
1554     error (_("Structure does not live in memory."));
1555
1556   /* Search through fields and base classes recursively.  */
1557   found = gen_struct_ref_recursive (exp, ax, value, field, 0, type);
1558   
1559   if (!found)
1560     error (_("Couldn't find member named `%s' in struct/union/class `%s'"),
1561            field, TYPE_TAG_NAME (type));
1562 }
1563
1564 static int
1565 gen_namespace_elt (struct expression *exp,
1566                    struct agent_expr *ax, struct axs_value *value,
1567                    const struct type *curtype, char *name);
1568 static int
1569 gen_maybe_namespace_elt (struct expression *exp,
1570                          struct agent_expr *ax, struct axs_value *value,
1571                          const struct type *curtype, char *name);
1572
1573 static void
1574 gen_static_field (struct gdbarch *gdbarch,
1575                   struct agent_expr *ax, struct axs_value *value,
1576                   struct type *type, int fieldno)
1577 {
1578   if (TYPE_FIELD_LOC_KIND (type, fieldno) == FIELD_LOC_KIND_PHYSADDR)
1579     {
1580       ax_const_l (ax, TYPE_FIELD_STATIC_PHYSADDR (type, fieldno));
1581       value->kind = axs_lvalue_memory;
1582       value->type = TYPE_FIELD_TYPE (type, fieldno);
1583       value->optimized_out = 0;
1584     }
1585   else
1586     {
1587       const char *phys_name = TYPE_FIELD_STATIC_PHYSNAME (type, fieldno);
1588       struct symbol *sym = lookup_symbol (phys_name, 0, VAR_DOMAIN, 0);
1589
1590       if (sym)
1591         {
1592           gen_var_ref (gdbarch, ax, value, sym);
1593   
1594           /* Don't error if the value was optimized out, we may be
1595              scanning all static fields and just want to pass over this
1596              and continue with the rest.  */
1597         }
1598       else
1599         {
1600           /* Silently assume this was optimized out; class printing
1601              will let the user know why the data is missing.  */
1602           value->optimized_out = 1;
1603         }
1604     }
1605 }
1606
1607 static int
1608 gen_struct_elt_for_reference (struct expression *exp,
1609                               struct agent_expr *ax, struct axs_value *value,
1610                               struct type *type, char *fieldname)
1611 {
1612   struct type *t = type;
1613   int i;
1614
1615   if (TYPE_CODE (t) != TYPE_CODE_STRUCT
1616       && TYPE_CODE (t) != TYPE_CODE_UNION)
1617     internal_error (__FILE__, __LINE__,
1618                     _("non-aggregate type to gen_struct_elt_for_reference"));
1619
1620   for (i = TYPE_NFIELDS (t) - 1; i >= TYPE_N_BASECLASSES (t); i--)
1621     {
1622       const char *t_field_name = TYPE_FIELD_NAME (t, i);
1623
1624       if (t_field_name && strcmp (t_field_name, fieldname) == 0)
1625         {
1626           if (field_is_static (&TYPE_FIELD (t, i)))
1627             {
1628               gen_static_field (exp->gdbarch, ax, value, t, i);
1629               if (value->optimized_out)
1630                 error (_("static field `%s' has been "
1631                          "optimized out, cannot use"),
1632                        fieldname);
1633               return 1;
1634             }
1635           if (TYPE_FIELD_PACKED (t, i))
1636             error (_("pointers to bitfield members not allowed"));
1637
1638           /* FIXME we need a way to do "want_address" equivalent */       
1639
1640           error (_("Cannot reference non-static field \"%s\""), fieldname);
1641         }
1642     }
1643
1644   /* FIXME add other scoped-reference cases here */
1645
1646   /* Do a last-ditch lookup.  */
1647   return gen_maybe_namespace_elt (exp, ax, value, type, fieldname);
1648 }
1649
1650 /* C++: Return the member NAME of the namespace given by the type
1651    CURTYPE.  */
1652
1653 static int
1654 gen_namespace_elt (struct expression *exp,
1655                    struct agent_expr *ax, struct axs_value *value,
1656                    const struct type *curtype, char *name)
1657 {
1658   int found = gen_maybe_namespace_elt (exp, ax, value, curtype, name);
1659
1660   if (!found)
1661     error (_("No symbol \"%s\" in namespace \"%s\"."), 
1662            name, TYPE_TAG_NAME (curtype));
1663
1664   return found;
1665 }
1666
1667 /* A helper function used by value_namespace_elt and
1668    value_struct_elt_for_reference.  It looks up NAME inside the
1669    context CURTYPE; this works if CURTYPE is a namespace or if CURTYPE
1670    is a class and NAME refers to a type in CURTYPE itself (as opposed
1671    to, say, some base class of CURTYPE).  */
1672
1673 static int
1674 gen_maybe_namespace_elt (struct expression *exp,
1675                          struct agent_expr *ax, struct axs_value *value,
1676                          const struct type *curtype, char *name)
1677 {
1678   const char *namespace_name = TYPE_TAG_NAME (curtype);
1679   struct symbol *sym;
1680
1681   sym = cp_lookup_symbol_namespace (namespace_name, name,
1682                                     block_for_pc (ax->scope),
1683                                     VAR_DOMAIN);
1684
1685   if (sym == NULL)
1686     return 0;
1687
1688   gen_var_ref (exp->gdbarch, ax, value, sym);
1689
1690   if (value->optimized_out)
1691     error (_("`%s' has been optimized out, cannot use"),
1692            SYMBOL_PRINT_NAME (sym));
1693
1694   return 1;
1695 }
1696
1697
1698 static int
1699 gen_aggregate_elt_ref (struct expression *exp,
1700                        struct agent_expr *ax, struct axs_value *value,
1701                        struct type *type, char *field,
1702                        char *operator_name, char *operand_name)
1703 {
1704   switch (TYPE_CODE (type))
1705     {
1706     case TYPE_CODE_STRUCT:
1707     case TYPE_CODE_UNION:
1708       return gen_struct_elt_for_reference (exp, ax, value, type, field);
1709       break;
1710     case TYPE_CODE_NAMESPACE:
1711       return gen_namespace_elt (exp, ax, value, type, field);
1712       break;
1713     default:
1714       internal_error (__FILE__, __LINE__,
1715                       _("non-aggregate type in gen_aggregate_elt_ref"));
1716     }
1717
1718   return 0;
1719 }
1720
1721 /* Generate code for GDB's magical `repeat' operator.
1722    LVALUE @ INT creates an array INT elements long, and whose elements
1723    have the same type as LVALUE, located in memory so that LVALUE is
1724    its first element.  For example, argv[0]@argc gives you the array
1725    of command-line arguments.
1726
1727    Unfortunately, because we have to know the types before we actually
1728    have a value for the expression, we can't implement this perfectly
1729    without changing the type system, having values that occupy two
1730    stack slots, doing weird things with sizeof, etc.  So we require
1731    the right operand to be a constant expression.  */
1732 static void
1733 gen_repeat (struct expression *exp, union exp_element **pc,
1734             struct agent_expr *ax, struct axs_value *value)
1735 {
1736   struct axs_value value1;
1737
1738   /* We don't want to turn this into an rvalue, so no conversions
1739      here.  */
1740   gen_expr (exp, pc, ax, &value1);
1741   if (value1.kind != axs_lvalue_memory)
1742     error (_("Left operand of `@' must be an object in memory."));
1743
1744   /* Evaluate the length; it had better be a constant.  */
1745   {
1746     struct value *v = const_expr (pc);
1747     int length;
1748
1749     if (!v)
1750       error (_("Right operand of `@' must be a "
1751                "constant, in agent expressions."));
1752     if (TYPE_CODE (value_type (v)) != TYPE_CODE_INT)
1753       error (_("Right operand of `@' must be an integer."));
1754     length = value_as_long (v);
1755     if (length <= 0)
1756       error (_("Right operand of `@' must be positive."));
1757
1758     /* The top of the stack is already the address of the object, so
1759        all we need to do is frob the type of the lvalue.  */
1760     {
1761       /* FIXME-type-allocation: need a way to free this type when we are
1762          done with it.  */
1763       struct type *array
1764         = lookup_array_range_type (value1.type, 0, length - 1);
1765
1766       value->kind = axs_lvalue_memory;
1767       value->type = array;
1768     }
1769   }
1770 }
1771
1772
1773 /* Emit code for the `sizeof' operator.
1774    *PC should point at the start of the operand expression; we advance it
1775    to the first instruction after the operand.  */
1776 static void
1777 gen_sizeof (struct expression *exp, union exp_element **pc,
1778             struct agent_expr *ax, struct axs_value *value,
1779             struct type *size_type)
1780 {
1781   /* We don't care about the value of the operand expression; we only
1782      care about its type.  However, in the current arrangement, the
1783      only way to find an expression's type is to generate code for it.
1784      So we generate code for the operand, and then throw it away,
1785      replacing it with code that simply pushes its size.  */
1786   int start = ax->len;
1787
1788   gen_expr (exp, pc, ax, value);
1789
1790   /* Throw away the code we just generated.  */
1791   ax->len = start;
1792
1793   ax_const_l (ax, TYPE_LENGTH (value->type));
1794   value->kind = axs_rvalue;
1795   value->type = size_type;
1796 }
1797 \f
1798
1799 /* Generating bytecode from GDB expressions: general recursive thingy  */
1800
1801 /* XXX: i18n */
1802 /* A gen_expr function written by a Gen-X'er guy.
1803    Append code for the subexpression of EXPR starting at *POS_P to AX.  */
1804 static void
1805 gen_expr (struct expression *exp, union exp_element **pc,
1806           struct agent_expr *ax, struct axs_value *value)
1807 {
1808   /* Used to hold the descriptions of operand expressions.  */
1809   struct axs_value value1, value2, value3;
1810   enum exp_opcode op = (*pc)[0].opcode, op2;
1811   int if1, go1, if2, go2, end;
1812   struct type *int_type = builtin_type (exp->gdbarch)->builtin_int;
1813
1814   /* If we're looking at a constant expression, just push its value.  */
1815   {
1816     struct value *v = maybe_const_expr (pc);
1817
1818     if (v)
1819       {
1820         ax_const_l (ax, value_as_long (v));
1821         value->kind = axs_rvalue;
1822         value->type = check_typedef (value_type (v));
1823         return;
1824       }
1825   }
1826
1827   /* Otherwise, go ahead and generate code for it.  */
1828   switch (op)
1829     {
1830       /* Binary arithmetic operators.  */
1831     case BINOP_ADD:
1832     case BINOP_SUB:
1833     case BINOP_MUL:
1834     case BINOP_DIV:
1835     case BINOP_REM:
1836     case BINOP_LSH:
1837     case BINOP_RSH:
1838     case BINOP_SUBSCRIPT:
1839     case BINOP_BITWISE_AND:
1840     case BINOP_BITWISE_IOR:
1841     case BINOP_BITWISE_XOR:
1842     case BINOP_EQUAL:
1843     case BINOP_NOTEQUAL:
1844     case BINOP_LESS:
1845     case BINOP_GTR:
1846     case BINOP_LEQ:
1847     case BINOP_GEQ:
1848       (*pc)++;
1849       gen_expr (exp, pc, ax, &value1);
1850       gen_usual_unary (exp, ax, &value1);
1851       gen_expr_binop_rest (exp, op, pc, ax, value, &value1, &value2);
1852       break;
1853
1854     case BINOP_LOGICAL_AND:
1855       (*pc)++;
1856       /* Generate the obvious sequence of tests and jumps.  */
1857       gen_expr (exp, pc, ax, &value1);
1858       gen_usual_unary (exp, ax, &value1);
1859       if1 = ax_goto (ax, aop_if_goto);
1860       go1 = ax_goto (ax, aop_goto);
1861       ax_label (ax, if1, ax->len);
1862       gen_expr (exp, pc, ax, &value2);
1863       gen_usual_unary (exp, ax, &value2);
1864       if2 = ax_goto (ax, aop_if_goto);
1865       go2 = ax_goto (ax, aop_goto);
1866       ax_label (ax, if2, ax->len);
1867       ax_const_l (ax, 1);
1868       end = ax_goto (ax, aop_goto);
1869       ax_label (ax, go1, ax->len);
1870       ax_label (ax, go2, ax->len);
1871       ax_const_l (ax, 0);
1872       ax_label (ax, end, ax->len);
1873       value->kind = axs_rvalue;
1874       value->type = int_type;
1875       break;
1876
1877     case BINOP_LOGICAL_OR:
1878       (*pc)++;
1879       /* Generate the obvious sequence of tests and jumps.  */
1880       gen_expr (exp, pc, ax, &value1);
1881       gen_usual_unary (exp, ax, &value1);
1882       if1 = ax_goto (ax, aop_if_goto);
1883       gen_expr (exp, pc, ax, &value2);
1884       gen_usual_unary (exp, ax, &value2);
1885       if2 = ax_goto (ax, aop_if_goto);
1886       ax_const_l (ax, 0);
1887       end = ax_goto (ax, aop_goto);
1888       ax_label (ax, if1, ax->len);
1889       ax_label (ax, if2, ax->len);
1890       ax_const_l (ax, 1);
1891       ax_label (ax, end, ax->len);
1892       value->kind = axs_rvalue;
1893       value->type = int_type;
1894       break;
1895
1896     case TERNOP_COND:
1897       (*pc)++;
1898       gen_expr (exp, pc, ax, &value1);
1899       gen_usual_unary (exp, ax, &value1);
1900       /* For (A ? B : C), it's easiest to generate subexpression
1901          bytecodes in order, but if_goto jumps on true, so we invert
1902          the sense of A.  Then we can do B by dropping through, and
1903          jump to do C.  */
1904       gen_logical_not (ax, &value1, int_type);
1905       if1 = ax_goto (ax, aop_if_goto);
1906       gen_expr (exp, pc, ax, &value2);
1907       gen_usual_unary (exp, ax, &value2);
1908       end = ax_goto (ax, aop_goto);
1909       ax_label (ax, if1, ax->len);
1910       gen_expr (exp, pc, ax, &value3);
1911       gen_usual_unary (exp, ax, &value3);
1912       ax_label (ax, end, ax->len);
1913       /* This is arbitary - what if B and C are incompatible types? */
1914       value->type = value2.type;
1915       value->kind = value2.kind;
1916       break;
1917
1918     case BINOP_ASSIGN:
1919       (*pc)++;
1920       if ((*pc)[0].opcode == OP_INTERNALVAR)
1921         {
1922           char *name = internalvar_name ((*pc)[1].internalvar);
1923           struct trace_state_variable *tsv;
1924
1925           (*pc) += 3;
1926           gen_expr (exp, pc, ax, value);
1927           tsv = find_trace_state_variable (name);
1928           if (tsv)
1929             {
1930               ax_tsv (ax, aop_setv, tsv->number);
1931               if (trace_kludge)
1932                 ax_tsv (ax, aop_tracev, tsv->number);
1933             }
1934           else
1935             error (_("$%s is not a trace state variable, "
1936                      "may not assign to it"), name);
1937         }
1938       else
1939         error (_("May only assign to trace state variables"));
1940       break;
1941
1942     case BINOP_ASSIGN_MODIFY:
1943       (*pc)++;
1944       op2 = (*pc)[0].opcode;
1945       (*pc)++;
1946       (*pc)++;
1947       if ((*pc)[0].opcode == OP_INTERNALVAR)
1948         {
1949           char *name = internalvar_name ((*pc)[1].internalvar);
1950           struct trace_state_variable *tsv;
1951
1952           (*pc) += 3;
1953           tsv = find_trace_state_variable (name);
1954           if (tsv)
1955             {
1956               /* The tsv will be the left half of the binary operation.  */
1957               ax_tsv (ax, aop_getv, tsv->number);
1958               if (trace_kludge)
1959                 ax_tsv (ax, aop_tracev, tsv->number);
1960               /* Trace state variables are always 64-bit integers.  */
1961               value1.kind = axs_rvalue;
1962               value1.type = builtin_type (exp->gdbarch)->builtin_long_long;
1963               /* Now do right half of expression.  */
1964               gen_expr_binop_rest (exp, op2, pc, ax, value, &value1, &value2);
1965               /* We have a result of the binary op, set the tsv.  */
1966               ax_tsv (ax, aop_setv, tsv->number);
1967               if (trace_kludge)
1968                 ax_tsv (ax, aop_tracev, tsv->number);
1969             }
1970           else
1971             error (_("$%s is not a trace state variable, "
1972                      "may not assign to it"), name);
1973         }
1974       else
1975         error (_("May only assign to trace state variables"));
1976       break;
1977
1978       /* Note that we need to be a little subtle about generating code
1979          for comma.  In C, we can do some optimizations here because
1980          we know the left operand is only being evaluated for effect.
1981          However, if the tracing kludge is in effect, then we always
1982          need to evaluate the left hand side fully, so that all the
1983          variables it mentions get traced.  */
1984     case BINOP_COMMA:
1985       (*pc)++;
1986       gen_expr (exp, pc, ax, &value1);
1987       /* Don't just dispose of the left operand.  We might be tracing,
1988          in which case we want to emit code to trace it if it's an
1989          lvalue.  */
1990       gen_traced_pop (exp->gdbarch, ax, &value1);
1991       gen_expr (exp, pc, ax, value);
1992       /* It's the consumer's responsibility to trace the right operand.  */
1993       break;
1994
1995     case OP_LONG:               /* some integer constant */
1996       {
1997         struct type *type = (*pc)[1].type;
1998         LONGEST k = (*pc)[2].longconst;
1999
2000         (*pc) += 4;
2001         gen_int_literal (ax, value, k, type);
2002       }
2003       break;
2004
2005     case OP_VAR_VALUE:
2006       gen_var_ref (exp->gdbarch, ax, value, (*pc)[2].symbol);
2007
2008       if (value->optimized_out)
2009         error (_("`%s' has been optimized out, cannot use"),
2010                SYMBOL_PRINT_NAME ((*pc)[2].symbol));
2011
2012       (*pc) += 4;
2013       break;
2014
2015     case OP_REGISTER:
2016       {
2017         const char *name = &(*pc)[2].string;
2018         int reg;
2019
2020         (*pc) += 4 + BYTES_TO_EXP_ELEM ((*pc)[1].longconst + 1);
2021         reg = user_reg_map_name_to_regnum (exp->gdbarch, name, strlen (name));
2022         if (reg == -1)
2023           internal_error (__FILE__, __LINE__,
2024                           _("Register $%s not available"), name);
2025         /* No support for tracing user registers yet.  */
2026         if (reg >= gdbarch_num_regs (exp->gdbarch)
2027             + gdbarch_num_pseudo_regs (exp->gdbarch))
2028           error (_("'%s' is a user-register; "
2029                    "GDB cannot yet trace user-register contents."),
2030                  name);
2031         value->kind = axs_lvalue_register;
2032         value->u.reg = reg;
2033         value->type = register_type (exp->gdbarch, reg);
2034       }
2035       break;
2036
2037     case OP_INTERNALVAR:
2038       {
2039         const char *name = internalvar_name ((*pc)[1].internalvar);
2040         struct trace_state_variable *tsv;
2041
2042         (*pc) += 3;
2043         tsv = find_trace_state_variable (name);
2044         if (tsv)
2045           {
2046             ax_tsv (ax, aop_getv, tsv->number);
2047             if (trace_kludge)
2048               ax_tsv (ax, aop_tracev, tsv->number);
2049             /* Trace state variables are always 64-bit integers.  */
2050             value->kind = axs_rvalue;
2051             value->type = builtin_type (exp->gdbarch)->builtin_long_long;
2052           }
2053         else
2054           error (_("$%s is not a trace state variable; GDB agent "
2055                    "expressions cannot use convenience variables."), name);
2056       }
2057       break;
2058
2059       /* Weirdo operator: see comments for gen_repeat for details.  */
2060     case BINOP_REPEAT:
2061       /* Note that gen_repeat handles its own argument evaluation.  */
2062       (*pc)++;
2063       gen_repeat (exp, pc, ax, value);
2064       break;
2065
2066     case UNOP_CAST:
2067       {
2068         struct type *type = (*pc)[1].type;
2069
2070         (*pc) += 3;
2071         gen_expr (exp, pc, ax, value);
2072         gen_cast (ax, value, type);
2073       }
2074       break;
2075
2076     case UNOP_MEMVAL:
2077       {
2078         struct type *type = check_typedef ((*pc)[1].type);
2079
2080         (*pc) += 3;
2081         gen_expr (exp, pc, ax, value);
2082
2083         /* If we have an axs_rvalue or an axs_lvalue_memory, then we
2084            already have the right value on the stack.  For
2085            axs_lvalue_register, we must convert.  */
2086         if (value->kind == axs_lvalue_register)
2087           require_rvalue (ax, value);
2088
2089         value->type = type;
2090         value->kind = axs_lvalue_memory;
2091       }
2092       break;
2093
2094     case UNOP_PLUS:
2095       (*pc)++;
2096       /* + FOO is equivalent to 0 + FOO, which can be optimized.  */
2097       gen_expr (exp, pc, ax, value);
2098       gen_usual_unary (exp, ax, value);
2099       break;
2100       
2101     case UNOP_NEG:
2102       (*pc)++;
2103       /* -FOO is equivalent to 0 - FOO.  */
2104       gen_int_literal (ax, &value1, 0,
2105                        builtin_type (exp->gdbarch)->builtin_int);
2106       gen_usual_unary (exp, ax, &value1);       /* shouldn't do much */
2107       gen_expr (exp, pc, ax, &value2);
2108       gen_usual_unary (exp, ax, &value2);
2109       gen_usual_arithmetic (exp, ax, &value1, &value2);
2110       gen_binop (ax, value, &value1, &value2, aop_sub, aop_sub, 1, "negation");
2111       break;
2112
2113     case UNOP_LOGICAL_NOT:
2114       (*pc)++;
2115       gen_expr (exp, pc, ax, value);
2116       gen_usual_unary (exp, ax, value);
2117       gen_logical_not (ax, value, int_type);
2118       break;
2119
2120     case UNOP_COMPLEMENT:
2121       (*pc)++;
2122       gen_expr (exp, pc, ax, value);
2123       gen_usual_unary (exp, ax, value);
2124       gen_integral_promotions (exp, ax, value);
2125       gen_complement (ax, value);
2126       break;
2127
2128     case UNOP_IND:
2129       (*pc)++;
2130       gen_expr (exp, pc, ax, value);
2131       gen_usual_unary (exp, ax, value);
2132       if (!pointer_type (value->type))
2133         error (_("Argument of unary `*' is not a pointer."));
2134       gen_deref (ax, value);
2135       break;
2136
2137     case UNOP_ADDR:
2138       (*pc)++;
2139       gen_expr (exp, pc, ax, value);
2140       gen_address_of (ax, value);
2141       break;
2142
2143     case UNOP_SIZEOF:
2144       (*pc)++;
2145       /* Notice that gen_sizeof handles its own operand, unlike most
2146          of the other unary operator functions.  This is because we
2147          have to throw away the code we generate.  */
2148       gen_sizeof (exp, pc, ax, value,
2149                   builtin_type (exp->gdbarch)->builtin_int);
2150       break;
2151
2152     case STRUCTOP_STRUCT:
2153     case STRUCTOP_PTR:
2154       {
2155         int length = (*pc)[1].longconst;
2156         char *name = &(*pc)[2].string;
2157
2158         (*pc) += 4 + BYTES_TO_EXP_ELEM (length + 1);
2159         gen_expr (exp, pc, ax, value);
2160         if (op == STRUCTOP_STRUCT)
2161           gen_struct_ref (exp, ax, value, name, ".", "structure or union");
2162         else if (op == STRUCTOP_PTR)
2163           gen_struct_ref (exp, ax, value, name, "->",
2164                           "pointer to a structure or union");
2165         else
2166           /* If this `if' chain doesn't handle it, then the case list
2167              shouldn't mention it, and we shouldn't be here.  */
2168           internal_error (__FILE__, __LINE__,
2169                           _("gen_expr: unhandled struct case"));
2170       }
2171       break;
2172
2173     case OP_THIS:
2174       {
2175         char *this_name;
2176         struct symbol *sym, *func;
2177         struct block *b;
2178         const struct language_defn *lang;
2179
2180         b = block_for_pc (ax->scope);
2181         func = block_linkage_function (b);
2182         lang = language_def (SYMBOL_LANGUAGE (func));
2183
2184         sym = lookup_language_this (lang, b);
2185         if (!sym)
2186           error (_("no `%s' found"), lang->la_name_of_this);
2187
2188         gen_var_ref (exp->gdbarch, ax, value, sym);
2189
2190         if (value->optimized_out)
2191           error (_("`%s' has been optimized out, cannot use"),
2192                  SYMBOL_PRINT_NAME (sym));
2193
2194         (*pc) += 2;
2195       }
2196       break;
2197
2198     case OP_SCOPE:
2199       {
2200         struct type *type = (*pc)[1].type;
2201         int length = longest_to_int ((*pc)[2].longconst);
2202         char *name = &(*pc)[3].string;
2203         int found;
2204
2205         found = gen_aggregate_elt_ref (exp, ax, value, type, name,
2206                                        "?", "??");
2207         if (!found)
2208           error (_("There is no field named %s"), name);
2209         (*pc) += 5 + BYTES_TO_EXP_ELEM (length + 1);
2210       }
2211       break;
2212
2213     case OP_TYPE:
2214       error (_("Attempt to use a type name as an expression."));
2215
2216     default:
2217       error (_("Unsupported operator %s (%d) in expression."),
2218              op_string (op), op);
2219     }
2220 }
2221
2222 /* This handles the middle-to-right-side of code generation for binary
2223    expressions, which is shared between regular binary operations and
2224    assign-modify (+= and friends) expressions.  */
2225
2226 static void
2227 gen_expr_binop_rest (struct expression *exp,
2228                      enum exp_opcode op, union exp_element **pc,
2229                      struct agent_expr *ax, struct axs_value *value,
2230                      struct axs_value *value1, struct axs_value *value2)
2231 {
2232   struct type *int_type = builtin_type (exp->gdbarch)->builtin_int;
2233
2234   gen_expr (exp, pc, ax, value2);
2235   gen_usual_unary (exp, ax, value2);
2236   gen_usual_arithmetic (exp, ax, value1, value2);
2237   switch (op)
2238     {
2239     case BINOP_ADD:
2240       if (TYPE_CODE (value1->type) == TYPE_CODE_INT
2241           && pointer_type (value2->type))
2242         {
2243           /* Swap the values and proceed normally.  */
2244           ax_simple (ax, aop_swap);
2245           gen_ptradd (ax, value, value2, value1);
2246         }
2247       else if (pointer_type (value1->type)
2248                && TYPE_CODE (value2->type) == TYPE_CODE_INT)
2249         gen_ptradd (ax, value, value1, value2);
2250       else
2251         gen_binop (ax, value, value1, value2,
2252                    aop_add, aop_add, 1, "addition");
2253       break;
2254     case BINOP_SUB:
2255       if (pointer_type (value1->type)
2256           && TYPE_CODE (value2->type) == TYPE_CODE_INT)
2257         gen_ptrsub (ax,value, value1, value2);
2258       else if (pointer_type (value1->type)
2259                && pointer_type (value2->type))
2260         /* FIXME --- result type should be ptrdiff_t */
2261         gen_ptrdiff (ax, value, value1, value2,
2262                      builtin_type (exp->gdbarch)->builtin_long);
2263       else
2264         gen_binop (ax, value, value1, value2,
2265                    aop_sub, aop_sub, 1, "subtraction");
2266       break;
2267     case BINOP_MUL:
2268       gen_binop (ax, value, value1, value2,
2269                  aop_mul, aop_mul, 1, "multiplication");
2270       break;
2271     case BINOP_DIV:
2272       gen_binop (ax, value, value1, value2,
2273                  aop_div_signed, aop_div_unsigned, 1, "division");
2274       break;
2275     case BINOP_REM:
2276       gen_binop (ax, value, value1, value2,
2277                  aop_rem_signed, aop_rem_unsigned, 1, "remainder");
2278       break;
2279     case BINOP_LSH:
2280       gen_binop (ax, value, value1, value2,
2281                  aop_lsh, aop_lsh, 1, "left shift");
2282       break;
2283     case BINOP_RSH:
2284       gen_binop (ax, value, value1, value2,
2285                  aop_rsh_signed, aop_rsh_unsigned, 1, "right shift");
2286       break;
2287     case BINOP_SUBSCRIPT:
2288       {
2289         struct type *type;
2290
2291         if (binop_types_user_defined_p (op, value1->type, value2->type))
2292           {
2293             error (_("cannot subscript requested type: "
2294                      "cannot call user defined functions"));
2295           }
2296         else
2297           {
2298             /* If the user attempts to subscript something that is not
2299                an array or pointer type (like a plain int variable for
2300                example), then report this as an error.  */
2301             type = check_typedef (value1->type);
2302             if (TYPE_CODE (type) != TYPE_CODE_ARRAY
2303                 && TYPE_CODE (type) != TYPE_CODE_PTR)
2304               {
2305                 if (TYPE_NAME (type))
2306                   error (_("cannot subscript something of type `%s'"),
2307                          TYPE_NAME (type));
2308                 else
2309                   error (_("cannot subscript requested type"));
2310               }
2311           }
2312
2313         if (!is_integral_type (value2->type))
2314           error (_("Argument to arithmetic operation "
2315                    "not a number or boolean."));
2316
2317         gen_ptradd (ax, value, value1, value2);
2318         gen_deref (ax, value);
2319         break;
2320       }
2321     case BINOP_BITWISE_AND:
2322       gen_binop (ax, value, value1, value2,
2323                  aop_bit_and, aop_bit_and, 0, "bitwise and");
2324       break;
2325
2326     case BINOP_BITWISE_IOR:
2327       gen_binop (ax, value, value1, value2,
2328                  aop_bit_or, aop_bit_or, 0, "bitwise or");
2329       break;
2330       
2331     case BINOP_BITWISE_XOR:
2332       gen_binop (ax, value, value1, value2,
2333                  aop_bit_xor, aop_bit_xor, 0, "bitwise exclusive-or");
2334       break;
2335
2336     case BINOP_EQUAL:
2337       gen_equal (ax, value, value1, value2, int_type);
2338       break;
2339
2340     case BINOP_NOTEQUAL:
2341       gen_equal (ax, value, value1, value2, int_type);
2342       gen_logical_not (ax, value, int_type);
2343       break;
2344
2345     case BINOP_LESS:
2346       gen_less (ax, value, value1, value2, int_type);
2347       break;
2348
2349     case BINOP_GTR:
2350       ax_simple (ax, aop_swap);
2351       gen_less (ax, value, value1, value2, int_type);
2352       break;
2353
2354     case BINOP_LEQ:
2355       ax_simple (ax, aop_swap);
2356       gen_less (ax, value, value1, value2, int_type);
2357       gen_logical_not (ax, value, int_type);
2358       break;
2359
2360     case BINOP_GEQ:
2361       gen_less (ax, value, value1, value2, int_type);
2362       gen_logical_not (ax, value, int_type);
2363       break;
2364
2365     default:
2366       /* We should only list operators in the outer case statement
2367          that we actually handle in the inner case statement.  */
2368       internal_error (__FILE__, __LINE__,
2369                       _("gen_expr: op case sets don't match"));
2370     }
2371 }
2372 \f
2373
2374 /* Given a single variable and a scope, generate bytecodes to trace
2375    its value.  This is for use in situations where we have only a
2376    variable's name, and no parsed expression; for instance, when the
2377    name comes from a list of local variables of a function.  */
2378
2379 struct agent_expr *
2380 gen_trace_for_var (CORE_ADDR scope, struct gdbarch *gdbarch,
2381                    struct symbol *var)
2382 {
2383   struct cleanup *old_chain = 0;
2384   struct agent_expr *ax = new_agent_expr (gdbarch, scope);
2385   struct axs_value value;
2386
2387   old_chain = make_cleanup_free_agent_expr (ax);
2388
2389   trace_kludge = 1;
2390   gen_var_ref (gdbarch, ax, &value, var);
2391
2392   /* If there is no actual variable to trace, flag it by returning
2393      an empty agent expression.  */
2394   if (value.optimized_out)
2395     {
2396       do_cleanups (old_chain);
2397       return NULL;
2398     }
2399
2400   /* Make sure we record the final object, and get rid of it.  */
2401   gen_traced_pop (gdbarch, ax, &value);
2402
2403   /* Oh, and terminate.  */
2404   ax_simple (ax, aop_end);
2405
2406   /* We have successfully built the agent expr, so cancel the cleanup
2407      request.  If we add more cleanups that we always want done, this
2408      will have to get more complicated.  */
2409   discard_cleanups (old_chain);
2410   return ax;
2411 }
2412
2413 /* Generating bytecode from GDB expressions: driver */
2414
2415 /* Given a GDB expression EXPR, return bytecode to trace its value.
2416    The result will use the `trace' and `trace_quick' bytecodes to
2417    record the value of all memory touched by the expression.  The
2418    caller can then use the ax_reqs function to discover which
2419    registers it relies upon.  */
2420 struct agent_expr *
2421 gen_trace_for_expr (CORE_ADDR scope, struct expression *expr)
2422 {
2423   struct cleanup *old_chain = 0;
2424   struct agent_expr *ax = new_agent_expr (expr->gdbarch, scope);
2425   union exp_element *pc;
2426   struct axs_value value;
2427
2428   old_chain = make_cleanup_free_agent_expr (ax);
2429
2430   pc = expr->elts;
2431   trace_kludge = 1;
2432   value.optimized_out = 0;
2433   gen_expr (expr, &pc, ax, &value);
2434
2435   /* Make sure we record the final object, and get rid of it.  */
2436   gen_traced_pop (expr->gdbarch, ax, &value);
2437
2438   /* Oh, and terminate.  */
2439   ax_simple (ax, aop_end);
2440
2441   /* We have successfully built the agent expr, so cancel the cleanup
2442      request.  If we add more cleanups that we always want done, this
2443      will have to get more complicated.  */
2444   discard_cleanups (old_chain);
2445   return ax;
2446 }
2447
2448 /* Given a GDB expression EXPR, return a bytecode sequence that will
2449    evaluate and return a result.  The bytecodes will do a direct
2450    evaluation, using the current data on the target, rather than
2451    recording blocks of memory and registers for later use, as
2452    gen_trace_for_expr does.  The generated bytecode sequence leaves
2453    the result of expression evaluation on the top of the stack.  */
2454
2455 struct agent_expr *
2456 gen_eval_for_expr (CORE_ADDR scope, struct expression *expr)
2457 {
2458   struct cleanup *old_chain = 0;
2459   struct agent_expr *ax = new_agent_expr (expr->gdbarch, scope);
2460   union exp_element *pc;
2461   struct axs_value value;
2462
2463   old_chain = make_cleanup_free_agent_expr (ax);
2464
2465   pc = expr->elts;
2466   trace_kludge = 0;
2467   value.optimized_out = 0;
2468   gen_expr (expr, &pc, ax, &value);
2469
2470   require_rvalue (ax, &value);
2471
2472   /* Oh, and terminate.  */
2473   ax_simple (ax, aop_end);
2474
2475   /* We have successfully built the agent expr, so cancel the cleanup
2476      request.  If we add more cleanups that we always want done, this
2477      will have to get more complicated.  */
2478   discard_cleanups (old_chain);
2479   return ax;
2480 }
2481
2482 struct agent_expr *
2483 gen_trace_for_return_address (CORE_ADDR scope, struct gdbarch *gdbarch)
2484 {
2485   struct cleanup *old_chain = 0;
2486   struct agent_expr *ax = new_agent_expr (gdbarch, scope);
2487   struct axs_value value;
2488
2489   old_chain = make_cleanup_free_agent_expr (ax);
2490
2491   trace_kludge = 1;
2492
2493   gdbarch_gen_return_address (gdbarch, ax, &value, scope);
2494
2495   /* Make sure we record the final object, and get rid of it.  */
2496   gen_traced_pop (gdbarch, ax, &value);
2497
2498   /* Oh, and terminate.  */
2499   ax_simple (ax, aop_end);
2500
2501   /* We have successfully built the agent expr, so cancel the cleanup
2502      request.  If we add more cleanups that we always want done, this
2503      will have to get more complicated.  */
2504   discard_cleanups (old_chain);
2505   return ax;
2506 }
2507
2508 static void
2509 agent_command (char *exp, int from_tty)
2510 {
2511   struct cleanup *old_chain = 0;
2512   struct expression *expr;
2513   struct agent_expr *agent;
2514   struct frame_info *fi = get_current_frame (); /* need current scope */
2515
2516   /* We don't deal with overlay debugging at the moment.  We need to
2517      think more carefully about this.  If you copy this code into
2518      another command, change the error message; the user shouldn't
2519      have to know anything about agent expressions.  */
2520   if (overlay_debugging)
2521     error (_("GDB can't do agent expression translation with overlays."));
2522
2523   if (exp == 0)
2524     error_no_arg (_("expression to translate"));
2525
2526   trace_string_kludge = 0;
2527   if (*exp == '/')
2528     exp = decode_agent_options (exp);
2529
2530   /* Recognize the return address collection directive specially.  Note
2531      that it is not really an expression of any sort.  */
2532   if (strcmp (exp, "$_ret") == 0)
2533     {
2534       agent = gen_trace_for_return_address (get_frame_pc (fi),
2535                                             get_current_arch ());
2536       old_chain = make_cleanup_free_agent_expr (agent);
2537     }
2538   else
2539     {
2540       expr = parse_expression (exp);
2541       old_chain = make_cleanup (free_current_contents, &expr);
2542       agent = gen_trace_for_expr (get_frame_pc (fi), expr);
2543       make_cleanup_free_agent_expr (agent);
2544     }
2545
2546   ax_reqs (agent);
2547   ax_print (gdb_stdout, agent);
2548
2549   /* It would be nice to call ax_reqs here to gather some general info
2550      about the expression, and then print out the result.  */
2551
2552   do_cleanups (old_chain);
2553   dont_repeat ();
2554 }
2555
2556 /* Parse the given expression, compile it into an agent expression
2557    that does direct evaluation, and display the resulting
2558    expression.  */
2559
2560 static void
2561 agent_eval_command (char *exp, int from_tty)
2562 {
2563   struct cleanup *old_chain = 0;
2564   struct expression *expr;
2565   struct agent_expr *agent;
2566   struct frame_info *fi = get_current_frame (); /* need current scope */
2567
2568   /* We don't deal with overlay debugging at the moment.  We need to
2569      think more carefully about this.  If you copy this code into
2570      another command, change the error message; the user shouldn't
2571      have to know anything about agent expressions.  */
2572   if (overlay_debugging)
2573     error (_("GDB can't do agent expression translation with overlays."));
2574
2575   if (exp == 0)
2576     error_no_arg (_("expression to translate"));
2577
2578   expr = parse_expression (exp);
2579   old_chain = make_cleanup (free_current_contents, &expr);
2580   agent = gen_eval_for_expr (get_frame_pc (fi), expr);
2581   make_cleanup_free_agent_expr (agent);
2582   ax_reqs (agent);
2583   ax_print (gdb_stdout, agent);
2584
2585   /* It would be nice to call ax_reqs here to gather some general info
2586      about the expression, and then print out the result.  */
2587
2588   do_cleanups (old_chain);
2589   dont_repeat ();
2590 }
2591 \f
2592
2593 /* Initialization code.  */
2594
2595 void _initialize_ax_gdb (void);
2596 void
2597 _initialize_ax_gdb (void)
2598 {
2599   add_cmd ("agent", class_maintenance, agent_command,
2600            _("Translate an expression into "
2601              "remote agent bytecode for tracing."),
2602            &maintenancelist);
2603
2604   add_cmd ("agent-eval", class_maintenance, agent_eval_command,
2605            _("Translate an expression into remote "
2606              "agent bytecode for evaluation."),
2607            &maintenancelist);
2608 }