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