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