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