OSDN Git Service

0a2640a4fd9fb9040747033739fd7015d8f00bfe
[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 /* Various return functions that are used based upon the
170    return type for the selector.
171    __objc_block_return for structures.
172    __objc_double_return for floats/doubles.
173    __objc_word_return for pointers or types that fit in registers.
174    */
175 #if INVISIBLE_STRUCT_RETURN
176 static __big
177 #else
178 static id
179 #endif
180 __objc_block_return(IMP imp, void * args)
181 {
182   void * result = __builtin_apply((apply_t)imp, args, 96);
183   if (result)
184     __builtin_return (result);
185   else
186     return;
187 }
188
189 static id
190 __objc_word_return(IMP imp, void * args)
191 {
192   void * result = __builtin_apply((apply_t)imp, args, 96);
193   if (result)
194     __builtin_return (result);
195   else
196     return;
197 }
198  
199 static double
200 __objc_double_return(IMP imp, void * args)
201 {
202   void * result = __builtin_apply((apply_t)imp, args, 96);
203   if (result)
204     __builtin_return (result);
205   else
206     return;
207 }
208
209 /* This one is a bit hairy.  This function is installed in the 
210    premature dispatch table, and thus called once for each class,
211    namely when the very first message is send to it.  */
212
213 static void __objc_init_install_dtable(id receiver, SEL op)
214 {
215   __label__ already_initialized;
216   IMP imp;
217   void* args;
218   void* result;
219   const char *t;
220
221   /* This may happen, if the programmer has taken the address of a 
222      method before the dtable was initialized... too bad for him! */
223   if(receiver->class_pointer->dtable != __objc_uninstalled_dtable)
224     goto already_initialized;
225
226   objc_mutex_lock(__objc_runtime_mutex);
227
228   if(CLS_ISCLASS(receiver->class_pointer))
229     {
230       /* receiver is an ordinary object */
231       assert(CLS_ISCLASS(receiver->class_pointer));
232
233       /* install instance methods table */
234       __objc_install_dispatch_table_for_class (receiver->class_pointer);
235
236       /* call +initialize -- this will in turn install the factory 
237          dispatch table if not already done :-) */
238       __objc_send_initialize(receiver->class_pointer);
239     }
240   else
241     {
242       /* receiver is a class object */
243       assert(CLS_ISCLASS((Class)receiver));
244       assert(CLS_ISMETA(receiver->class_pointer));
245
246       /* Install real dtable for factory methods */
247       __objc_install_dispatch_table_for_class (receiver->class_pointer);
248
249       if (strcmp (sel_get_name (op), "initialize"))
250         __objc_send_initialize((Class)receiver);
251       else
252         CLS_SETINITIALIZED((Class)receiver);
253     }
254   objc_mutex_unlock(__objc_runtime_mutex);
255
256 already_initialized:
257   
258   /* Get real method for this in newly installed dtable */
259   imp = get_imp(receiver->class_pointer, op);
260
261   /* Perform the appropriate return based upon the method return type */
262   args = __builtin_apply_args();
263   t = op->sel_types;
264   if (t && (*t == '[' || *t == '(' || *t == '{'))
265     ((id(*)())__objc_block_return)(imp, args);
266   else if (t && (*t == 'f' || *t == 'd'))
267     ((id(*)())__objc_double_return)(imp, args);
268   else
269     __objc_word_return(imp, args);
270 }
271
272 /* Install dummy table for class which causes the first message to
273    that class (or instances hereof) to be initialized properly */
274 void __objc_install_premature_dtable(Class class)
275 {
276   assert(__objc_uninstalled_dtable);
277   class->dtable = __objc_uninstalled_dtable;
278 }   
279
280 /* Send +initialize to class if not already done */
281 static void __objc_send_initialize(Class class)
282 {
283   /* This *must* be a class object */
284   assert(CLS_ISCLASS(class));
285   assert(!CLS_ISMETA(class));
286
287   if (!CLS_ISINITIALIZED(class))
288     {
289       CLS_SETINITIALIZED(class);
290       CLS_SETINITIALIZED(class->class_pointer);
291       
292       if(class->super_class)
293         __objc_send_initialize(class->super_class);
294
295       {
296         SEL     op = sel_register_name ("initialize");
297         Class   tmpclass = class;
298         IMP     imp = 0;
299
300         while (!imp && tmpclass) {
301           MethodList_t method_list = tmpclass->class_pointer->methods;
302
303           while(!imp && method_list) {
304             int i;
305             Method_t method;
306
307             for (i=0;i<method_list->method_count;i++) {
308               method = &(method_list->method_list[i]);
309               if (method->method_name
310                   && method->method_name->sel_id == op->sel_id) {
311                 imp = method->method_imp;
312                 break;
313               }
314             }
315
316             method_list = method_list->method_next;
317
318           }
319
320           tmpclass = tmpclass->super_class;
321         }
322         if (imp)
323             (*imp)((id)class, op);
324                 
325       }
326     }
327 }
328
329 /* Walk on the methods list of class and install the methods in the reverse
330    order of the lists. Since methods added by categories are before the methods
331    of class in the methods list, this allows categories to substitute methods
332    declared in class. However if more than one category replace the same method
333    nothing is guarranteed about what method will be used.
334    Assumes that __objc_runtime_mutex is locked down. */
335 static void
336 __objc_install_methods_in_dtable (Class class, MethodList_t method_list)
337 {
338   int i;
339
340   if (!method_list)
341     return;
342
343   if (method_list->method_next)
344     __objc_install_methods_in_dtable (class, method_list->method_next);
345
346   for (i = 0; i < method_list->method_count; i++)
347     {
348       Method_t method = &(method_list->method_list[i]);
349       sarray_at_put_safe (class->dtable,
350                           (sidx) method->method_name->sel_id,
351                           method->method_imp);
352     }
353 }
354
355 /* Assumes that __objc_runtime_mutex is locked down. */
356 static void
357 __objc_install_dispatch_table_for_class (Class class)
358 {
359   Class super;
360   int counter;
361
362   /* If the class has not yet had it's class links resolved, we must 
363      re-compute all class links */
364   if(!CLS_ISRESOLV(class))
365     __objc_resolve_class_links();
366
367   super = class->super_class;
368
369   if (super != 0 && (super->dtable == __objc_uninstalled_dtable))
370     __objc_install_dispatch_table_for_class (super);
371
372   /* Allocate dtable if necessary */
373   if (super == 0)
374     {
375       objc_mutex_lock(__objc_runtime_mutex);
376       class->dtable = sarray_new (__objc_selector_max_index, 0);
377       objc_mutex_unlock(__objc_runtime_mutex);
378     }
379   else
380     class->dtable = sarray_lazy_copy (super->dtable);
381
382   __objc_install_methods_in_dtable (class, class->methods);
383 }
384
385 void __objc_update_dispatch_table_for_class (Class class)
386 {
387   Class next;
388   struct sarray *arr;
389
390   /* not yet installed -- skip it */
391   if (class->dtable == __objc_uninstalled_dtable) 
392     return;
393
394   objc_mutex_lock(__objc_runtime_mutex);
395
396   arr = class->dtable;
397   __objc_install_premature_dtable (class); /* someone might require it... */
398   sarray_free (arr);                       /* release memory */
399
400   /* could have been lazy... */
401   __objc_install_dispatch_table_for_class (class); 
402
403   if (class->subclass_list)     /* Traverse subclasses */
404     for (next = class->subclass_list; next; next = next->sibling_class)
405       __objc_update_dispatch_table_for_class (next);
406
407   objc_mutex_unlock(__objc_runtime_mutex);
408 }
409
410
411 /* This function adds a method list to a class.  This function is
412    typically called by another function specific to the run-time.  As
413    such this function does not worry about thread safe issues.
414
415    This one is only called for categories. Class objects have their
416    methods installed right away, and their selectors are made into
417    SEL's by the function __objc_register_selectors_from_class. */ 
418 void
419 class_add_method_list (Class class, MethodList_t list)
420 {
421   int i;
422
423   /* Passing of a linked list is not allowed.  Do multiple calls.  */
424   assert (!list->method_next);
425
426   /* Check for duplicates.  */
427   for (i = 0; i < list->method_count; ++i)
428     {
429       Method_t method = &list->method_list[i];
430
431       if (method->method_name)  /* Sometimes these are NULL */
432         {
433           /* This is where selector names are transmogrified to SEL's */
434           method->method_name = 
435             sel_register_typed_name ((const char*)method->method_name,
436                                      method->method_types);
437         }
438     }
439
440   /* Add the methods to the class's method list.  */
441   list->method_next = class->methods;
442   class->methods = list;
443
444   /* Update the dispatch table of class */
445   __objc_update_dispatch_table_for_class (class);
446 }
447
448 Method_t
449 class_get_instance_method(Class class, SEL op)
450 {
451   return search_for_method_in_hierarchy(class, op);
452 }
453
454 Method_t
455 class_get_class_method(MetaClass class, SEL op)
456 {
457   return search_for_method_in_hierarchy(class, op);
458 }
459
460
461 /* Search for a method starting from the current class up its hierarchy.
462    Return a pointer to the method's method structure if found.  NULL
463    otherwise. */   
464
465 static Method_t
466 search_for_method_in_hierarchy (Class cls, SEL sel)
467 {
468   Method_t method = NULL;
469   Class class;
470
471   if (! sel_is_mapped (sel))
472     return NULL;
473
474   /* Scan the method list of the class.  If the method isn't found in the
475      list then step to its super class. */
476   for (class = cls; ((! method) && class); class = class->super_class)
477     method = search_for_method_in_list (class->methods, sel);
478
479   return method;
480 }
481
482
483
484 /* Given a linked list of method and a method's name.  Search for the named
485    method's method structure.  Return a pointer to the method's method
486    structure if found.  NULL otherwise. */  
487 static Method_t
488 search_for_method_in_list (MethodList_t list, SEL op)
489 {
490   MethodList_t method_list = list;
491
492   if (! sel_is_mapped (op))
493     return NULL;
494
495   /* If not found then we'll search the list.  */
496   while (method_list)
497     {
498       int i;
499
500       /* Search the method list.  */
501       for (i = 0; i < method_list->method_count; ++i)
502         {
503           Method_t method = &method_list->method_list[i];
504
505           if (method->method_name)
506             if (method->method_name->sel_id == op->sel_id)
507               return method;
508         }
509
510       /* The method wasn't found.  Follow the link to the next list of
511          methods.  */
512       method_list = method_list->method_next;
513     }
514
515   return NULL;
516 }
517
518 static retval_t __objc_forward (id object, SEL sel, arglist_t args);
519
520 /* Forwarding pointers/integers through the normal registers */
521 static id
522 __objc_word_forward (id rcv, SEL op, ...)
523 {
524   void *args, *res;
525
526   args = __builtin_apply_args ();
527   res = __objc_forward (rcv, op, args);
528   if (res)
529     __builtin_return (res);
530   else
531     return res;
532 }
533
534 /* Specific routine for forwarding floats/double because of
535    architectural differences on some processors.  i386s for
536    example which uses a floating point stack versus general
537    registers for floating point numbers.  This forward routine 
538    makes sure that GCC restores the proper return values */
539 static double
540 __objc_double_forward (id rcv, SEL op, ...)
541 {
542   void *args, *res;
543
544   args = __builtin_apply_args ();
545   res = __objc_forward (rcv, op, args);
546   __builtin_return (res);
547 }
548
549 #if INVISIBLE_STRUCT_RETURN
550 static __big
551 #else
552 static id
553 #endif
554 __objc_block_forward (id rcv, SEL op, ...)
555 {
556   void *args, *res;
557
558   args = __builtin_apply_args ();
559   res = __objc_forward (rcv, op, args);
560   if (res)
561     __builtin_return (res);
562 }
563
564
565 /* This function is installed in the dispatch table for all methods which are
566    not implemented.  Thus, it is called when a selector is not recognized. */
567 static retval_t
568 __objc_forward (id object, SEL sel, arglist_t args)
569 {
570   IMP imp;
571   static SEL frwd_sel = 0;                      /* !T:SAFE2 */
572   SEL err_sel;
573
574   /* first try if the object understands forward:: */
575   if (!frwd_sel)
576     frwd_sel = sel_get_any_uid("forward::");
577
578   if (__objc_responds_to (object, frwd_sel))
579     {
580       imp = get_imp(object->class_pointer, frwd_sel);
581       return (*imp)(object, frwd_sel, sel, args);
582     }
583
584   /* If the object recognizes the doesNotRecognize: method then we're going
585      to send it. */
586   err_sel = sel_get_any_uid ("doesNotRecognize:");
587   if (__objc_responds_to (object, err_sel))
588     {
589       imp = get_imp (object->class_pointer, err_sel);
590       return (*imp) (object, err_sel, sel);
591     }
592   
593   /* The object doesn't recognize the method.  Check for responding to
594      error:.  If it does then sent it. */
595   {
596     size_t strlen (const char*);
597     char msg[256 + strlen ((const char*)sel_get_name (sel))
598              + strlen ((const char*)object->class_pointer->name)];
599
600     sprintf (msg, "(%s) %s does not recognize %s",
601              (CLS_ISMETA(object->class_pointer)
602               ? "class"
603               : "instance" ),
604              object->class_pointer->name, sel_get_name (sel));
605
606     err_sel = sel_get_any_uid ("error:");
607     if (__objc_responds_to (object, err_sel))
608       {
609         imp = get_imp (object->class_pointer, err_sel);
610         return (*imp) (object, sel_get_any_uid ("error:"), msg);
611       }
612
613     /* The object doesn't respond to doesNotRecognize: or error:;  Therefore,
614        a default action is taken. */
615     objc_error (object, OBJC_ERR_UNIMPLEMENTED, "%s\n", msg);
616   }
617 }
618
619 void __objc_print_dtable_stats()
620 {
621   int total = 0;
622
623   objc_mutex_lock(__objc_runtime_mutex);
624
625   printf("memory usage: (%s)\n",
626 #ifdef OBJC_SPARSE2
627          "2-level sparse arrays"
628 #else
629          "3-level sparse arrays"
630 #endif
631          );
632
633   printf("arrays: %d = %ld bytes\n", narrays, 
634          (int)narrays*sizeof(struct sarray));
635   total += narrays*sizeof(struct sarray);
636   printf("buckets: %d = %ld bytes\n", nbuckets, 
637          (int)nbuckets*sizeof(struct sbucket));
638   total += nbuckets*sizeof(struct sbucket);
639
640   printf("idxtables: %d = %ld bytes\n", idxsize, (int)idxsize*sizeof(void*));
641   total += idxsize*sizeof(void*);
642   printf("-----------------------------------\n");
643   printf("total: %d bytes\n", total);
644   printf("===================================\n");
645
646   objc_mutex_unlock(__objc_runtime_mutex);
647 }
648
649 /* Returns the dispatch table */
650 __inline__
651 struct sarray* 
652 objc_get_uninstalled_dtable()
653 {
654   return __objc_uninstalled_dtable;
655 }