OSDN Git Service

904a3c4ef2bd93ec351f48c7113f022a1ad75c64
[pf3gnuchains/gcc-fork.git] / gcc / objc / sendmsg.c
1 /* GNU Objective C Runtime message lookup 
2    Copyright (C) 1993, 1995, 1996, 1997 Free Software Foundation, Inc.
3    Contributed by Kresten Krab Thorup
4
5 This file is part of GNU CC.
6
7 GNU CC is free software; you can redistribute it and/or modify it under the
8 terms of the GNU General Public License as published by the Free Software
9 Foundation; either version 2, or (at your option) any later version.
10
11 GNU CC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
14 details.
15
16 You should have received a copy of the GNU General Public License along with
17 GNU CC; see the file COPYING.  If not, write to the Free Software
18 Foundation, 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA.  */
20
21 /* As a special exception, if you link this library with files compiled with
22    GCC to produce an executable, this does not cause the resulting executable
23    to be covered by the GNU General Public License. This exception does not
24    however invalidate any other reasons why the executable file might be
25    covered by the GNU General Public License.  */
26
27 #include "../tconfig.h"
28 #include "runtime.h"
29 #include "sarray.h"
30 #include "encoding.h"
31
32 /* this is how we hack STRUCT_VALUE to be 1 or 0 */
33 #define gen_rtx(args...) 1
34 #define rtx int
35
36 #if STRUCT_VALUE == 0
37 #define INVISIBLE_STRUCT_RETURN 1
38 #else
39 #define INVISIBLE_STRUCT_RETURN 0
40 #endif
41
42 /* The uninstalled dispatch table */
43 struct sarray* __objc_uninstalled_dtable = 0;   /* !T:MUTEX */
44
45 /* Send +initialize to class */
46 static void __objc_send_initialize(Class);
47
48 static void __objc_install_dispatch_table_for_class (Class);
49
50 /* Forward declare some functions */
51 static void __objc_init_install_dtable(id, SEL);
52
53 /* Various forwarding functions that are used based upon the
54    return type for the selector.
55    __objc_block_forward for structures.
56    __objc_double_forward for floats/doubles.
57    __objc_word_forward for pointers or types that fit in registers.
58    */
59 static double __objc_double_forward(id, SEL, ...);
60 static id __objc_word_forward(id, SEL, ...);
61 typedef struct { id many[8]; } __big;
62 #if INVISIBLE_STRUCT_RETURN 
63 static __big 
64 #else
65 static id
66 #endif
67 __objc_block_forward(id, SEL, ...);
68 static Method_t search_for_method_in_hierarchy (Class class, SEL sel);
69 static Method_t search_for_method_in_list(MethodList_t list, SEL op);
70 id nil_method(id, SEL, ...);
71
72 /* Given a class and selector, return the selector's implementation.  */
73 __inline__
74 IMP
75 get_imp (Class class, SEL sel)
76 {
77   IMP impl;
78   void* res = sarray_get (class->dtable, (size_t) sel->sel_id);
79   if(res == __objc_init_install_dtable)
80     {
81       objc_mutex_lock(__objc_runtime_mutex);
82       __objc_install_dispatch_table_for_class (class);
83       objc_mutex_unlock(__objc_runtime_mutex);
84       res = sarray_get (class->dtable, (size_t) sel->sel_id);
85     }
86   if (res == 0)
87     {
88       const char *t = sel->sel_types;
89       if (t && (*t == '[' || *t == '(' || *t == '{'))
90         res = (IMP)__objc_block_forward;
91       else if (t && (*t == 'f' || *t == 'd'))
92         res = (IMP)__objc_double_forward;
93       else
94         res = (IMP)__objc_word_forward;
95     }
96   return res;
97 }
98
99 __inline__ BOOL
100 __objc_responds_to (id object, SEL sel)
101 {
102   void* res = sarray_get (object->class_pointer->dtable, (size_t) sel->sel_id);
103   if(res == __objc_init_install_dtable)
104     {
105       objc_mutex_lock(__objc_runtime_mutex);
106       __objc_install_dispatch_table_for_class (object->class_pointer);
107       objc_mutex_unlock(__objc_runtime_mutex);
108       res = sarray_get (object->class_pointer->dtable, (size_t) sel->sel_id);
109     }
110   return (res != 0);
111 }
112
113 /* This is the lookup function.  All entries in the table are either a 
114    valid method *or* one of `__objc_missing_method' which calls
115    forward:: etc, or `__objc_init_install_dtable' which installs the
116    real dtable */
117 __inline__ IMP
118 objc_msg_lookup(id receiver, SEL op)
119 {
120   IMP result;
121   if(receiver)
122     {
123       result = sarray_get(receiver->class_pointer->dtable, (sidx)op->sel_id);
124       if (result == 0)
125         {
126           const char *t = op->sel_types;
127           if (t && (*t == '[' || *t == '(' || *t == '{'))
128             result = (IMP)__objc_block_forward;
129           else if (t && (*t == 'f' || *t == 'd'))
130             result = (IMP)__objc_double_forward;
131           else
132             result = (IMP)__objc_word_forward;
133         }
134       return result;
135     }
136   else
137     return nil_method;
138 }
139
140 IMP
141 objc_msg_lookup_super (Super_t super, SEL sel)
142 {
143   if (super->self)
144     return get_imp (super->class, sel);
145   else
146     return nil_method;
147 }
148
149 int method_get_sizeof_arguments (Method*);
150
151 retval_t
152 objc_msg_sendv(id object, SEL op, arglist_t arg_frame)
153 {
154   Method* m = class_get_instance_method(object->class_pointer, op);
155   const char *type;
156   *((id*)method_get_first_argument (m, arg_frame, &type)) = object;
157   *((SEL*)method_get_next_argument (arg_frame, &type)) = op;
158   return __builtin_apply((apply_t)m->method_imp, 
159                          arg_frame,
160                          method_get_sizeof_arguments (m));
161 }
162
163 void __objc_init_dispatch_tables()
164 {
165   __objc_uninstalled_dtable
166     = sarray_new(200, __objc_init_install_dtable);
167 }
168
169 /* This one is a bit hairy.  This function is installed in the 
170    premature dispatch table, and thus called once for each class,
171    namely when the very first message is send to it.  */
172
173 static void __objc_init_install_dtable(id receiver, SEL op)
174 {
175   __label__ already_initialized;
176   IMP imp;
177   void* args;
178   void* result;
179
180   /* This may happen, if the programmer has taken the address of a 
181      method before the dtable was initialized... too bad for him! */
182   if(receiver->class_pointer->dtable != __objc_uninstalled_dtable)
183     goto already_initialized;
184
185   objc_mutex_lock(__objc_runtime_mutex);
186
187   if(CLS_ISCLASS(receiver->class_pointer))
188     {
189       /* receiver is an ordinary object */
190       assert(CLS_ISCLASS(receiver->class_pointer));
191
192       /* install instance methods table */
193       __objc_install_dispatch_table_for_class (receiver->class_pointer);
194
195       /* call +initialize -- this will in turn install the factory 
196          dispatch table if not already done :-) */
197       __objc_send_initialize(receiver->class_pointer);
198     }
199   else
200     {
201       /* receiver is a class object */
202       assert(CLS_ISCLASS((Class)receiver));
203       assert(CLS_ISMETA(receiver->class_pointer));
204
205       /* Install real dtable for factory methods */
206       __objc_install_dispatch_table_for_class (receiver->class_pointer);
207
208       if (strcmp (sel_get_name (op), "initialize"))
209         __objc_send_initialize((Class)receiver);
210       else
211         CLS_SETINITIALIZED((Class)receiver);
212     }
213   objc_mutex_unlock(__objc_runtime_mutex);
214
215 already_initialized:
216   
217   /* Get real method for this in newly installed dtable */
218   imp = get_imp(receiver->class_pointer, op);
219
220   args = __builtin_apply_args();
221   result = __builtin_apply((apply_t)imp, args, 96);
222   if (result)
223     __builtin_return (result);
224   else
225     return;
226   
227 }
228
229 /* Install dummy table for class which causes the first message to
230    that class (or instances hereof) to be initialized properly */
231 void __objc_install_premature_dtable(Class class)
232 {
233   assert(__objc_uninstalled_dtable);
234   class->dtable = __objc_uninstalled_dtable;
235 }   
236
237 /* Send +initialize to class if not already done */
238 static void __objc_send_initialize(Class class)
239 {
240   /* This *must* be a class object */
241   assert(CLS_ISCLASS(class));
242   assert(!CLS_ISMETA(class));
243
244   if (!CLS_ISINITIALIZED(class))
245     {
246       CLS_SETINITIALIZED(class);
247       CLS_SETINITIALIZED(class->class_pointer);
248       
249       if(class->super_class)
250         __objc_send_initialize(class->super_class);
251
252       {
253         SEL     op = sel_register_name ("initialize");
254         Class   tmpclass = class;
255         IMP     imp = 0;
256
257         while (!imp && tmpclass) {
258           MethodList_t method_list = tmpclass->class_pointer->methods;
259
260           while(!imp && method_list) {
261             int i;
262             Method_t method;
263
264             for (i=0;i<method_list->method_count;i++) {
265               method = &(method_list->method_list[i]);
266               if (method->method_name
267                   && method->method_name->sel_id == op->sel_id) {
268                 imp = method->method_imp;
269                 break;
270               }
271             }
272
273             method_list = method_list->method_next;
274
275           }
276
277           tmpclass = tmpclass->super_class;
278         }
279         if (imp)
280             (*imp)((id)class, op);
281                 
282       }
283     }
284 }
285
286 /* Walk on the methods list of class and install the methods in the reverse
287    order of the lists. Since methods added by categories are before the methods
288    of class in the methods list, this allows categories to substitute methods
289    declared in class. However if more than one category replace the same method
290    nothing is guarranteed about what method will be used.
291    Assumes that __objc_runtime_mutex is locked down. */
292 static void
293 __objc_install_methods_in_dtable (Class class, MethodList_t method_list)
294 {
295   int i;
296
297   if (!method_list)
298     return;
299
300   if (method_list->method_next)
301     __objc_install_methods_in_dtable (class, method_list->method_next);
302
303   for (i = 0; i < method_list->method_count; i++)
304     {
305       Method_t method = &(method_list->method_list[i]);
306       sarray_at_put_safe (class->dtable,
307                           (sidx) method->method_name->sel_id,
308                           method->method_imp);
309     }
310 }
311
312 /* Assumes that __objc_runtime_mutex is locked down. */
313 static void
314 __objc_install_dispatch_table_for_class (Class class)
315 {
316   Class super;
317   int counter;
318
319   /* If the class has not yet had it's class links resolved, we must 
320      re-compute all class links */
321   if(!CLS_ISRESOLV(class))
322     __objc_resolve_class_links();
323
324   super = class->super_class;
325
326   if (super != 0 && (super->dtable == __objc_uninstalled_dtable))
327     __objc_install_dispatch_table_for_class (super);
328
329   /* Allocate dtable if necessary */
330   if (super == 0)
331     {
332       objc_mutex_lock(__objc_runtime_mutex);
333       class->dtable = sarray_new (__objc_selector_max_index, 0);
334       objc_mutex_unlock(__objc_runtime_mutex);
335     }
336   else
337     class->dtable = sarray_lazy_copy (super->dtable);
338
339   __objc_install_methods_in_dtable (class, class->methods);
340 }
341
342 void __objc_update_dispatch_table_for_class (Class class)
343 {
344   Class next;
345   struct sarray *arr;
346
347   /* not yet installed -- skip it */
348   if (class->dtable == __objc_uninstalled_dtable) 
349     return;
350
351   objc_mutex_lock(__objc_runtime_mutex);
352
353   arr = class->dtable;
354   __objc_install_premature_dtable (class); /* someone might require it... */
355   sarray_free (arr);                       /* release memory */
356
357   /* could have been lazy... */
358   __objc_install_dispatch_table_for_class (class); 
359
360   if (class->subclass_list)     /* Traverse subclasses */
361     for (next = class->subclass_list; next; next = next->sibling_class)
362       __objc_update_dispatch_table_for_class (next);
363
364   objc_mutex_unlock(__objc_runtime_mutex);
365 }
366
367
368 /* This function adds a method list to a class.  This function is
369    typically called by another function specific to the run-time.  As
370    such this function does not worry about thread safe issues.
371
372    This one is only called for categories. Class objects have their
373    methods installed right away, and their selectors are made into
374    SEL's by the function __objc_register_selectors_from_class. */ 
375 void
376 class_add_method_list (Class class, MethodList_t list)
377 {
378   int i;
379
380   /* Passing of a linked list is not allowed.  Do multiple calls.  */
381   assert (!list->method_next);
382
383   /* Check for duplicates.  */
384   for (i = 0; i < list->method_count; ++i)
385     {
386       Method_t method = &list->method_list[i];
387
388       if (method->method_name)  /* Sometimes these are NULL */
389         {
390           /* This is where selector names are transmogrified to SEL's */
391           method->method_name = 
392             sel_register_typed_name ((const char*)method->method_name,
393                                      method->method_types);
394         }
395     }
396
397   /* Add the methods to the class's method list.  */
398   list->method_next = class->methods;
399   class->methods = list;
400
401   /* Update the dispatch table of class */
402   __objc_update_dispatch_table_for_class (class);
403 }
404
405 Method_t
406 class_get_instance_method(Class class, SEL op)
407 {
408   return search_for_method_in_hierarchy(class, op);
409 }
410
411 Method_t
412 class_get_class_method(MetaClass class, SEL op)
413 {
414   return search_for_method_in_hierarchy(class, op);
415 }
416
417
418 /* Search for a method starting from the current class up its hierarchy.
419    Return a pointer to the method's method structure if found.  NULL
420    otherwise. */   
421
422 static Method_t
423 search_for_method_in_hierarchy (Class cls, SEL sel)
424 {
425   Method_t method = NULL;
426   Class class;
427
428   if (! sel_is_mapped (sel))
429     return NULL;
430
431   /* Scan the method list of the class.  If the method isn't found in the
432      list then step to its super class. */
433   for (class = cls; ((! method) && class); class = class->super_class)
434     method = search_for_method_in_list (class->methods, sel);
435
436   return method;
437 }
438
439
440
441 /* Given a linked list of method and a method's name.  Search for the named
442    method's method structure.  Return a pointer to the method's method
443    structure if found.  NULL otherwise. */  
444 static Method_t
445 search_for_method_in_list (MethodList_t list, SEL op)
446 {
447   MethodList_t method_list = list;
448
449   if (! sel_is_mapped (op))
450     return NULL;
451
452   /* If not found then we'll search the list.  */
453   while (method_list)
454     {
455       int i;
456
457       /* Search the method list.  */
458       for (i = 0; i < method_list->method_count; ++i)
459         {
460           Method_t method = &method_list->method_list[i];
461
462           if (method->method_name)
463             if (method->method_name->sel_id == op->sel_id)
464               return method;
465         }
466
467       /* The method wasn't found.  Follow the link to the next list of
468          methods.  */
469       method_list = method_list->method_next;
470     }
471
472   return NULL;
473 }
474
475 static retval_t __objc_forward (id object, SEL sel, arglist_t args);
476
477 /* Forwarding pointers/integers through the normal registers */
478 static id
479 __objc_word_forward (id rcv, SEL op, ...)
480 {
481   void *args, *res;
482
483   args = __builtin_apply_args ();
484   res = __objc_forward (rcv, op, args);
485   if (res)
486     __builtin_return (res);
487   else
488     return res;
489 }
490
491 /* Specific routine for forwarding floats/double because of
492    architectural differences on some processors.  i386s for
493    example which uses a floating point stack versus general
494    registers for floating point numbers.  This forward routine 
495    makes sure that GCC restores the proper return values */
496 static double
497 __objc_double_forward (id rcv, SEL op, ...)
498 {
499   void *args, *res;
500
501   args = __builtin_apply_args ();
502   res = __objc_forward (rcv, op, args);
503   __builtin_return (res);
504 }
505
506 #if INVISIBLE_STRUCT_RETURN
507 static __big
508 #else
509 static id
510 #endif
511 __objc_block_forward (id rcv, SEL op, ...)
512 {
513   void *args, *res;
514
515   args = __builtin_apply_args ();
516   res = __objc_forward (rcv, op, args);
517   if (res)
518     __builtin_return (res);
519 }
520
521
522 /* This function is installed in the dispatch table for all methods which are
523    not implemented.  Thus, it is called when a selector is not recognized. */
524 static retval_t
525 __objc_forward (id object, SEL sel, arglist_t args)
526 {
527   IMP imp;
528   static SEL frwd_sel = 0;                      /* !T:SAFE2 */
529   SEL err_sel;
530
531   /* first try if the object understands forward:: */
532   if (!frwd_sel)
533     frwd_sel = sel_get_any_uid("forward::");
534
535   if (__objc_responds_to (object, frwd_sel))
536     {
537       imp = get_imp(object->class_pointer, frwd_sel);
538       return (*imp)(object, frwd_sel, sel, args);
539     }
540
541   /* If the object recognizes the doesNotRecognize: method then we're going
542      to send it. */
543   err_sel = sel_get_any_uid ("doesNotRecognize:");
544   if (__objc_responds_to (object, err_sel))
545     {
546       imp = get_imp (object->class_pointer, err_sel);
547       return (*imp) (object, err_sel, sel);
548     }
549   
550   /* The object doesn't recognize the method.  Check for responding to
551      error:.  If it does then sent it. */
552   {
553     size_t strlen (const char*);
554     char msg[256 + strlen ((const char*)sel_get_name (sel))
555              + strlen ((const char*)object->class_pointer->name)];
556
557     sprintf (msg, "(%s) %s does not recognize %s",
558              (CLS_ISMETA(object->class_pointer)
559               ? "class"
560               : "instance" ),
561              object->class_pointer->name, sel_get_name (sel));
562
563     err_sel = sel_get_any_uid ("error:");
564     if (__objc_responds_to (object, err_sel))
565       {
566         imp = get_imp (object->class_pointer, err_sel);
567         return (*imp) (object, sel_get_any_uid ("error:"), msg);
568       }
569
570     /* The object doesn't respond to doesNotRecognize: or error:;  Therefore,
571        a default action is taken. */
572     objc_error (object, OBJC_ERR_UNIMPLEMENTED, "%s\n", msg);
573   }
574 }
575
576 void __objc_print_dtable_stats()
577 {
578   int total = 0;
579
580   objc_mutex_lock(__objc_runtime_mutex);
581
582   printf("memory usage: (%s)\n",
583 #ifdef OBJC_SPARSE2
584          "2-level sparse arrays"
585 #else
586          "3-level sparse arrays"
587 #endif
588          );
589
590   printf("arrays: %d = %ld bytes\n", narrays, 
591          (int)narrays*sizeof(struct sarray));
592   total += narrays*sizeof(struct sarray);
593   printf("buckets: %d = %ld bytes\n", nbuckets, 
594          (int)nbuckets*sizeof(struct sbucket));
595   total += nbuckets*sizeof(struct sbucket);
596
597   printf("idxtables: %d = %ld bytes\n", idxsize, (int)idxsize*sizeof(void*));
598   total += idxsize*sizeof(void*);
599   printf("-----------------------------------\n");
600   printf("total: %d bytes\n", total);
601   printf("===================================\n");
602
603   objc_mutex_unlock(__objc_runtime_mutex);
604 }
605
606 /* Returns the dispatch table */
607 __inline__
608 struct sarray* 
609 objc_get_uninstalled_dtable()
610 {
611   return __objc_uninstalled_dtable;
612 }