OSDN Git Service

2010-04-12 Kai Tietz <kai.tietz@onevision.com>
[pf3gnuchains/gcc-fork.git] / gcc / config / darwin.c
1 /* Functions for generic Darwin as target machine for GNU C compiler.
2    Copyright (C) 1989, 1990, 1991, 1992, 1993, 2000, 2001, 2002, 2003, 2004,
3    2005, 2006, 2007, 2008, 2009, 2010
4    Free Software Foundation, Inc.
5    Contributed by Apple Computer Inc.
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
13
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "tm.h"
27 #include "rtl.h"
28 #include "regs.h"
29 #include "hard-reg-set.h"
30 #include "insn-config.h"
31 #include "conditions.h"
32 #include "insn-flags.h"
33 #include "output.h"
34 #include "insn-attr.h"
35 #include "flags.h"
36 #include "tree.h"
37 #include "expr.h"
38 #include "reload.h"
39 #include "function.h"
40 #include "ggc.h"
41 #include "langhooks.h"
42 #include "target.h"
43 #include "tm_p.h"
44 #include "toplev.h"
45 #include "hashtab.h"
46 #include "df.h"
47 #include "debug.h"
48 #include "obstack.h"
49 #include "lto-streamer.h"
50
51 /* Darwin supports a feature called fix-and-continue, which is used
52    for rapid turn around debugging.  When code is compiled with the
53    -mfix-and-continue flag, two changes are made to the generated code
54    that allow the system to do things that it would normally not be
55    able to do easily.  These changes allow gdb to load in
56    recompilation of a translation unit that has been changed into a
57    running program and replace existing functions and methods of that
58    translation unit with versions of those functions and methods
59    from the newly compiled translation unit.  The new functions access
60    the existing static symbols from the old translation unit, if the
61    symbol existed in the unit to be replaced, and from the new
62    translation unit, otherwise.
63
64    The changes are to insert 5 nops at the beginning of all functions
65    and to use indirection to get at static symbols.  The 5 nops
66    are required by consumers of the generated code.  Currently, gdb
67    uses this to patch in a jump to the overriding function, this
68    allows all uses of the old name to forward to the replacement,
69    including existing function pointers and virtual methods.  See
70    rs6000_emit_prologue for the code that handles the nop insertions.
71
72    The added indirection allows gdb to redirect accesses to static
73    symbols from the newly loaded translation unit to the existing
74    symbol, if any.  @code{static} symbols are special and are handled by
75    setting the second word in the .non_lazy_symbol_pointer data
76    structure to symbol.  See indirect_data for the code that handles
77    the extra indirection, and machopic_output_indirection and its use
78    of MACHO_SYMBOL_STATIC for the code that handles @code{static}
79    symbol indirection.  */
80
81 /* Section names.  */
82 section * darwin_sections[NUM_DARWIN_SECTIONS];
83
84 /* True if we're setting __attribute__ ((ms_struct)).  */
85 int darwin_ms_struct = false;
86
87 /* A get_unnamed_section callback used to switch to an ObjC section.
88    DIRECTIVE is as for output_section_asm_op.  */
89
90 static void
91 output_objc_section_asm_op (const void *directive)
92 {
93   static bool been_here = false;
94
95   if (! been_here)
96     {
97       static const enum darwin_section_enum tomark[] =
98         {
99           /* written, cold -> hot */
100           objc_cat_cls_meth_section,
101           objc_cat_inst_meth_section,
102           objc_string_object_section,
103           objc_constant_string_object_section,
104           objc_selector_refs_section,
105           objc_selector_fixup_section,
106           objc_cls_refs_section,
107           objc_class_section,
108           objc_meta_class_section,
109           /* shared, hot -> cold */
110           objc_cls_meth_section,
111           objc_inst_meth_section,
112           objc_protocol_section,
113           objc_class_names_section,
114           objc_meth_var_types_section,
115           objc_meth_var_names_section,
116           objc_category_section,
117           objc_class_vars_section,
118           objc_instance_vars_section,
119           objc_module_info_section,
120           objc_symbols_section
121         };
122       size_t i;
123
124       been_here = true;
125       for (i = 0; i < ARRAY_SIZE (tomark); i++)
126         switch_to_section (darwin_sections[tomark[i]]);
127     }
128   output_section_asm_op (directive);
129 }
130
131 /* Implement TARGET_ASM_INIT_SECTIONS.  */
132
133 void
134 darwin_init_sections (void)
135 {
136 #define DEF_SECTION(NAME, FLAGS, DIRECTIVE, OBJC)               \
137   darwin_sections[NAME] =                                       \
138     get_unnamed_section (FLAGS, (OBJC                           \
139                                  ? output_objc_section_asm_op   \
140                                  : output_section_asm_op),      \
141                          "\t" DIRECTIVE);
142 #include "config/darwin-sections.def"
143 #undef DEF_SECTION
144
145   readonly_data_section = darwin_sections[const_section];
146   exception_section = darwin_sections[darwin_exception_section];
147   eh_frame_section = darwin_sections[darwin_eh_frame_section];
148 }
149
150 int
151 name_needs_quotes (const char *name)
152 {
153   int c;
154   while ((c = *name++) != '\0')
155     if (! ISIDNUM (c) && c != '.' && c != '$')
156       return 1;
157   return 0;
158 }
159
160 /* Return true if SYM_REF can be used without an indirection.  */
161 static int
162 machopic_symbol_defined_p (rtx sym_ref)
163 {
164   if (SYMBOL_REF_FLAGS (sym_ref) & MACHO_SYMBOL_FLAG_DEFINED)
165     return true;
166
167   /* If a symbol references local and is not an extern to this
168      file, then the symbol might be able to declared as defined.  */
169   if (SYMBOL_REF_LOCAL_P (sym_ref) && ! SYMBOL_REF_EXTERNAL_P (sym_ref))
170     {
171       /* If the symbol references a variable and the variable is a
172          common symbol, then this symbol is not defined.  */
173       if (SYMBOL_REF_FLAGS (sym_ref) & MACHO_SYMBOL_FLAG_VARIABLE)
174         {
175           tree decl = SYMBOL_REF_DECL (sym_ref);
176           if (!decl)
177             return true;
178           if (DECL_COMMON (decl))
179             return false;
180         }
181       return true;
182     }
183   return false;
184 }
185
186 /* This module assumes that (const (symbol_ref "foo")) is a legal pic
187    reference, which will not be changed.  */
188
189 enum machopic_addr_class
190 machopic_classify_symbol (rtx sym_ref)
191 {
192   bool function_p;
193
194   function_p = SYMBOL_REF_FUNCTION_P (sym_ref);
195   if (machopic_symbol_defined_p (sym_ref))
196     return (function_p
197             ? MACHOPIC_DEFINED_FUNCTION : MACHOPIC_DEFINED_DATA);
198   else
199     return (function_p
200             ? MACHOPIC_UNDEFINED_FUNCTION : MACHOPIC_UNDEFINED_DATA);
201 }
202
203 #ifndef TARGET_FIX_AND_CONTINUE
204 #define TARGET_FIX_AND_CONTINUE 0
205 #endif
206
207 /* Indicate when fix-and-continue style code generation is being used
208    and when a reference to data should be indirected so that it can be
209    rebound in a new translation unit to reference the original instance
210    of that data.  Symbol names that are for code generation local to
211    the translation unit are bound to the new translation unit;
212    currently this means symbols that begin with L or _OBJC_;
213    otherwise, we indicate that an indirect reference should be made to
214    permit the runtime to rebind new instances of the translation unit
215    to the original instance of the data.  */
216
217 static int
218 indirect_data (rtx sym_ref)
219 {
220   int lprefix;
221   const char *name;
222
223   /* If we aren't generating fix-and-continue code, don't do anything
224      special.  */
225   if (TARGET_FIX_AND_CONTINUE == 0)
226     return 0;
227
228   /* Otherwise, all symbol except symbols that begin with L or _OBJC_
229      are indirected.  Symbols that begin with L and _OBJC_ are always
230      bound to the current translation unit as they are used for
231      generated local data of the translation unit.  */
232
233   name = XSTR (sym_ref, 0);
234
235   lprefix = (((name[0] == '*' || name[0] == '&')
236               && (name[1] == 'L' || (name[1] == '"' && name[2] == 'L')))
237              || (strncmp (name, "_OBJC_", 6) == 0));
238
239   return ! lprefix;
240 }
241
242
243 static int
244 machopic_data_defined_p (rtx sym_ref)
245 {
246   if (indirect_data (sym_ref))
247     return 0;
248
249   switch (machopic_classify_symbol (sym_ref))
250     {
251     case MACHOPIC_DEFINED_DATA:
252     case MACHOPIC_DEFINED_FUNCTION:
253       return 1;
254     default:
255       return 0;
256     }
257 }
258
259 void
260 machopic_define_symbol (rtx mem)
261 {
262   rtx sym_ref;
263
264   gcc_assert (GET_CODE (mem) == MEM);
265   sym_ref = XEXP (mem, 0);
266   SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_DEFINED;
267 }
268
269 /* Return either ORIG or:
270
271      (const:P (unspec:P [ORIG] UNSPEC_MACHOPIC_OFFSET))
272
273    depending on MACHO_DYNAMIC_NO_PIC_P.  */
274 rtx
275 machopic_gen_offset (rtx orig)
276 {
277   if (MACHO_DYNAMIC_NO_PIC_P)
278     return orig;
279   else
280     {
281       /* Play games to avoid marking the function as needing pic if we
282          are being called as part of the cost-estimation process.  */
283       if (current_ir_type () != IR_GIMPLE || currently_expanding_to_rtl)
284         crtl->uses_pic_offset_table = 1;
285       orig = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, orig),
286                              UNSPEC_MACHOPIC_OFFSET);
287       return gen_rtx_CONST (Pmode, orig);
288     }
289 }
290
291 static GTY(()) const char * function_base_func_name;
292 static GTY(()) int current_pic_label_num;
293
294 void
295 machopic_output_function_base_name (FILE *file)
296 {
297   const char *current_name;
298
299   /* If dynamic-no-pic is on, we should not get here.  */
300   gcc_assert (!MACHO_DYNAMIC_NO_PIC_P);
301   current_name =
302     IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (current_function_decl));
303   if (function_base_func_name != current_name)
304     {
305       ++current_pic_label_num;
306       function_base_func_name = current_name;
307     }
308   fprintf (file, "\"L%011d$pb\"", current_pic_label_num);
309 }
310
311 /* The suffix attached to non-lazy pointer symbols.  */
312 #define NON_LAZY_POINTER_SUFFIX "$non_lazy_ptr"
313 /* The suffix attached to stub symbols.  */
314 #define STUB_SUFFIX "$stub"
315
316 typedef struct GTY (()) machopic_indirection
317 {
318   /* The SYMBOL_REF for the entity referenced.  */
319   rtx symbol;
320   /* The name of the stub or non-lazy pointer.  */
321   const char * ptr_name;
322   /* True iff this entry is for a stub (as opposed to a non-lazy
323      pointer).  */
324   bool stub_p;
325   /* True iff this stub or pointer pointer has been referenced.  */
326   bool used;
327 } machopic_indirection;
328
329 /* A table mapping stub names and non-lazy pointer names to
330    SYMBOL_REFs for the stubbed-to and pointed-to entities.  */
331
332 static GTY ((param_is (struct machopic_indirection))) htab_t
333   machopic_indirections;
334
335 /* Return a hash value for a SLOT in the indirections hash table.  */
336
337 static hashval_t
338 machopic_indirection_hash (const void *slot)
339 {
340   const machopic_indirection *p = (const machopic_indirection *) slot;
341   return htab_hash_string (p->ptr_name);
342 }
343
344 /* Returns true if the KEY is the same as that associated with
345    SLOT.  */
346
347 static int
348 machopic_indirection_eq (const void *slot, const void *key)
349 {
350   return strcmp (((const machopic_indirection *) slot)->ptr_name,
351                  (const char *) key) == 0;
352 }
353
354 /* Return the name of the non-lazy pointer (if STUB_P is false) or
355    stub (if STUB_B is true) corresponding to the given name.  */
356
357 const char *
358 machopic_indirection_name (rtx sym_ref, bool stub_p)
359 {
360   char *buffer;
361   const char *name = XSTR (sym_ref, 0);
362   size_t namelen = strlen (name);
363   machopic_indirection *p;
364   void ** slot;
365   bool needs_quotes;
366   const char *suffix;
367   const char *prefix = user_label_prefix;
368   const char *quote = "";
369   tree id;
370
371   id = maybe_get_identifier (name);
372   if (id)
373     {
374       tree id_orig = id;
375
376       while (IDENTIFIER_TRANSPARENT_ALIAS (id))
377         id = TREE_CHAIN (id);
378       if (id != id_orig)
379         {
380           name = IDENTIFIER_POINTER (id);
381           namelen = strlen (name);
382         }
383     }
384
385   if (name[0] == '*')
386     {
387       prefix = "";
388       ++name;
389       --namelen;
390     }
391
392   needs_quotes = name_needs_quotes (name);
393   if (needs_quotes)
394     {
395       quote = "\"";
396     }
397
398   if (stub_p)
399     suffix = STUB_SUFFIX;
400   else
401     suffix = NON_LAZY_POINTER_SUFFIX;
402
403   buffer = XALLOCAVEC (char, strlen ("&L")
404                    + strlen (prefix)
405                    + namelen
406                    + strlen (suffix)
407                    + 2 * strlen (quote)
408                    + 1 /* '\0' */);
409
410   /* Construct the name of the non-lazy pointer or stub.  */
411   sprintf (buffer, "&%sL%s%s%s%s", quote, prefix, name, suffix, quote);
412
413   if (!machopic_indirections)
414     machopic_indirections = htab_create_ggc (37,
415                                              machopic_indirection_hash,
416                                              machopic_indirection_eq,
417                                              /*htab_del=*/NULL);
418
419   slot = htab_find_slot_with_hash (machopic_indirections, buffer,
420                                    htab_hash_string (buffer), INSERT);
421   if (*slot)
422     {
423       p = (machopic_indirection *) *slot;
424     }
425   else
426     {
427       p = (machopic_indirection *) ggc_alloc (sizeof (machopic_indirection));
428       p->symbol = sym_ref;
429       p->ptr_name = xstrdup (buffer);
430       p->stub_p = stub_p;
431       p->used = false;
432       *slot = p;
433     }
434
435   return p->ptr_name;
436 }
437
438 /* Return the name of the stub for the mcount function.  */
439
440 const char*
441 machopic_mcount_stub_name (void)
442 {
443   rtx symbol = gen_rtx_SYMBOL_REF (Pmode, "*mcount");
444   return machopic_indirection_name (symbol, /*stub_p=*/true);
445 }
446
447 /* If NAME is the name of a stub or a non-lazy pointer , mark the stub
448    or non-lazy pointer as used -- and mark the object to which the
449    pointer/stub refers as used as well, since the pointer/stub will
450    emit a reference to it.  */
451
452 void
453 machopic_validate_stub_or_non_lazy_ptr (const char *name)
454 {
455   machopic_indirection *p;
456
457   p = ((machopic_indirection *)
458        (htab_find_with_hash (machopic_indirections, name,
459                              htab_hash_string (name))));
460   if (p && ! p->used)
461     {
462       const char *real_name;
463       tree id;
464
465       p->used = true;
466
467       /* Do what output_addr_const will do when we actually call it.  */
468       if (SYMBOL_REF_DECL (p->symbol))
469         mark_decl_referenced (SYMBOL_REF_DECL (p->symbol));
470
471       real_name = targetm.strip_name_encoding (XSTR (p->symbol, 0));
472
473       id = maybe_get_identifier (real_name);
474       if (id)
475         mark_referenced (id);
476     }
477 }
478
479 /* Transform ORIG, which may be any data source, to the corresponding
480    source using indirections.  */
481
482 rtx
483 machopic_indirect_data_reference (rtx orig, rtx reg)
484 {
485   rtx ptr_ref = orig;
486
487   if (! MACHOPIC_INDIRECT)
488     return orig;
489
490   if (GET_CODE (orig) == SYMBOL_REF)
491     {
492       int defined = machopic_data_defined_p (orig);
493
494       if (defined && MACHO_DYNAMIC_NO_PIC_P)
495         {
496 #if defined (TARGET_TOC)
497           /* Create a new register for CSE opportunities.  */
498           rtx hi_reg = (!can_create_pseudo_p () ? reg : gen_reg_rtx (Pmode));
499           emit_insn (gen_macho_high (hi_reg, orig));
500           emit_insn (gen_macho_low (reg, hi_reg, orig));
501 #else
502            /* some other cpu -- writeme!  */
503            gcc_unreachable ();
504 #endif
505            return reg;
506         }
507       else if (defined)
508         {
509 #if defined (TARGET_TOC) || defined (HAVE_lo_sum)
510           rtx offset = machopic_gen_offset (orig);
511 #endif
512
513 #if defined (TARGET_TOC) /* i.e., PowerPC */
514           rtx hi_sum_reg = (!can_create_pseudo_p ()
515                             ? reg
516                             : gen_reg_rtx (Pmode));
517
518           gcc_assert (reg);
519
520           emit_insn (gen_rtx_SET (Pmode, hi_sum_reg,
521                               gen_rtx_PLUS (Pmode, pic_offset_table_rtx,
522                                        gen_rtx_HIGH (Pmode, offset))));
523           emit_insn (gen_rtx_SET (Pmode, reg,
524                                   gen_rtx_LO_SUM (Pmode, hi_sum_reg,
525                                                   copy_rtx (offset))));
526
527           orig = reg;
528 #else
529 #if defined (HAVE_lo_sum)
530           gcc_assert (reg);
531
532           emit_insn (gen_rtx_SET (VOIDmode, reg,
533                                   gen_rtx_HIGH (Pmode, offset)));
534           emit_insn (gen_rtx_SET (VOIDmode, reg,
535                                   gen_rtx_LO_SUM (Pmode, reg,
536                                                   copy_rtx (offset))));
537           emit_use (pic_offset_table_rtx);
538
539           orig = gen_rtx_PLUS (Pmode, pic_offset_table_rtx, reg);
540 #endif
541 #endif
542           return orig;
543         }
544
545       ptr_ref = (gen_rtx_SYMBOL_REF
546                  (Pmode,
547                   machopic_indirection_name (orig, /*stub_p=*/false)));
548
549       SYMBOL_REF_DATA (ptr_ref) = SYMBOL_REF_DATA (orig);
550
551       ptr_ref = gen_const_mem (Pmode, ptr_ref);
552       machopic_define_symbol (ptr_ref);
553
554       return ptr_ref;
555     }
556   else if (GET_CODE (orig) == CONST)
557     {
558       rtx base, result;
559
560       /* legitimize both operands of the PLUS */
561       if (GET_CODE (XEXP (orig, 0)) == PLUS)
562         {
563           base = machopic_indirect_data_reference (XEXP (XEXP (orig, 0), 0),
564                                                    reg);
565           orig = machopic_indirect_data_reference (XEXP (XEXP (orig, 0), 1),
566                                                    (base == reg ? 0 : reg));
567         }
568       else
569         return orig;
570
571       if (MACHOPIC_PURE && GET_CODE (orig) == CONST_INT)
572         result = plus_constant (base, INTVAL (orig));
573       else
574         result = gen_rtx_PLUS (Pmode, base, orig);
575
576       if (MACHOPIC_JUST_INDIRECT && GET_CODE (base) == MEM)
577         {
578           if (reg)
579             {
580               emit_move_insn (reg, result);
581               result = reg;
582             }
583           else
584             {
585               result = force_reg (GET_MODE (result), result);
586             }
587         }
588
589       return result;
590
591     }
592   else if (GET_CODE (orig) == MEM)
593     XEXP (ptr_ref, 0) = machopic_indirect_data_reference (XEXP (orig, 0), reg);
594   /* When the target is i386, this code prevents crashes due to the
595      compiler's ignorance on how to move the PIC base register to
596      other registers.  (The reload phase sometimes introduces such
597      insns.)  */
598   else if (GET_CODE (orig) == PLUS
599            && GET_CODE (XEXP (orig, 0)) == REG
600            && REGNO (XEXP (orig, 0)) == PIC_OFFSET_TABLE_REGNUM
601 #ifdef I386
602            /* Prevent the same register from being erroneously used
603               as both the base and index registers.  */
604            && GET_CODE (XEXP (orig, 1)) == CONST
605 #endif
606            && reg)
607     {
608       emit_move_insn (reg, XEXP (orig, 0));
609       XEXP (ptr_ref, 0) = reg;
610     }
611   return ptr_ref;
612 }
613
614 /* Transform TARGET (a MEM), which is a function call target, to the
615    corresponding symbol_stub if necessary.  Return a new MEM.  */
616
617 rtx
618 machopic_indirect_call_target (rtx target)
619 {
620   if (GET_CODE (target) != MEM)
621     return target;
622
623   if (MACHOPIC_INDIRECT
624       && GET_CODE (XEXP (target, 0)) == SYMBOL_REF
625       && !(SYMBOL_REF_FLAGS (XEXP (target, 0))
626            & MACHO_SYMBOL_FLAG_DEFINED))
627     {
628       rtx sym_ref = XEXP (target, 0);
629       const char *stub_name = machopic_indirection_name (sym_ref,
630                                                          /*stub_p=*/true);
631       enum machine_mode mode = GET_MODE (sym_ref);
632
633       XEXP (target, 0) = gen_rtx_SYMBOL_REF (mode, stub_name);
634       SYMBOL_REF_DATA (XEXP (target, 0)) = SYMBOL_REF_DATA (sym_ref);
635       MEM_READONLY_P (target) = 1;
636       MEM_NOTRAP_P (target) = 1;
637     }
638
639   return target;
640 }
641
642 rtx
643 machopic_legitimize_pic_address (rtx orig, enum machine_mode mode, rtx reg)
644 {
645   rtx pic_ref = orig;
646
647   if (! MACHOPIC_INDIRECT)
648     return orig;
649
650   /* First handle a simple SYMBOL_REF or LABEL_REF */
651   if (GET_CODE (orig) == LABEL_REF
652       || (GET_CODE (orig) == SYMBOL_REF
653           ))
654     {
655       /* addr(foo) = &func+(foo-func) */
656       orig = machopic_indirect_data_reference (orig, reg);
657
658       if (GET_CODE (orig) == PLUS
659           && GET_CODE (XEXP (orig, 0)) == REG)
660         {
661           if (reg == 0)
662             return force_reg (mode, orig);
663
664           emit_move_insn (reg, orig);
665           return reg;
666         }
667
668       if (GET_CODE (orig) == MEM)
669         {
670           if (reg == 0)
671             {
672               gcc_assert (!reload_in_progress);
673               reg = gen_reg_rtx (Pmode);
674             }
675
676 #ifdef HAVE_lo_sum
677           if (MACHO_DYNAMIC_NO_PIC_P
678               && (GET_CODE (XEXP (orig, 0)) == SYMBOL_REF
679                   || GET_CODE (XEXP (orig, 0)) == LABEL_REF))
680             {
681 #if defined (TARGET_TOC)        /* ppc  */
682               rtx temp_reg = (!can_create_pseudo_p ()
683                               ? reg :
684                               gen_reg_rtx (Pmode));
685               rtx asym = XEXP (orig, 0);
686               rtx mem;
687
688               emit_insn (gen_macho_high (temp_reg, asym));
689               mem = gen_const_mem (GET_MODE (orig),
690                                    gen_rtx_LO_SUM (Pmode, temp_reg,
691                                                    copy_rtx (asym)));
692               emit_insn (gen_rtx_SET (VOIDmode, reg, mem));
693 #else
694               /* Some other CPU -- WriteMe! but right now there are no other
695                  platforms that can use dynamic-no-pic  */
696               gcc_unreachable ();
697 #endif
698               pic_ref = reg;
699             }
700           else
701           if (GET_CODE (XEXP (orig, 0)) == SYMBOL_REF
702               || GET_CODE (XEXP (orig, 0)) == LABEL_REF)
703             {
704               rtx offset = machopic_gen_offset (XEXP (orig, 0));
705 #if defined (TARGET_TOC) /* i.e., PowerPC */
706               /* Generating a new reg may expose opportunities for
707                  common subexpression elimination.  */
708               rtx hi_sum_reg = (!can_create_pseudo_p ()
709                                 ? reg
710                                 : gen_reg_rtx (Pmode));
711               rtx mem;
712               rtx insn;
713               rtx sum;
714
715               sum = gen_rtx_HIGH (Pmode, offset);
716               if (! MACHO_DYNAMIC_NO_PIC_P)
717                 sum = gen_rtx_PLUS (Pmode, pic_offset_table_rtx, sum);
718
719               emit_insn (gen_rtx_SET (Pmode, hi_sum_reg, sum));
720
721               mem = gen_const_mem (GET_MODE (orig),
722                                   gen_rtx_LO_SUM (Pmode,
723                                                   hi_sum_reg,
724                                                   copy_rtx (offset)));
725               insn = emit_insn (gen_rtx_SET (VOIDmode, reg, mem));
726               set_unique_reg_note (insn, REG_EQUAL, pic_ref);
727
728               pic_ref = reg;
729 #else
730               emit_use (gen_rtx_REG (Pmode, PIC_OFFSET_TABLE_REGNUM));
731
732               emit_insn (gen_rtx_SET (VOIDmode, reg,
733                                       gen_rtx_HIGH (Pmode,
734                                                     gen_rtx_CONST (Pmode,
735                                                                    offset))));
736               emit_insn (gen_rtx_SET (VOIDmode, reg,
737                                   gen_rtx_LO_SUM (Pmode, reg,
738                                            gen_rtx_CONST (Pmode,
739                                                           copy_rtx (offset)))));
740               pic_ref = gen_rtx_PLUS (Pmode,
741                                       pic_offset_table_rtx, reg);
742 #endif
743             }
744           else
745 #endif  /* HAVE_lo_sum */
746             {
747               rtx pic = pic_offset_table_rtx;
748               if (GET_CODE (pic) != REG)
749                 {
750                   emit_move_insn (reg, pic);
751                   pic = reg;
752                 }
753 #if 0
754               emit_use (gen_rtx_REG (Pmode, PIC_OFFSET_TABLE_REGNUM));
755 #endif
756
757               if (reload_in_progress)
758                 df_set_regs_ever_live (REGNO (pic), true);
759               pic_ref = gen_rtx_PLUS (Pmode, pic,
760                                       machopic_gen_offset (XEXP (orig, 0)));
761             }
762
763 #if !defined (TARGET_TOC)
764           emit_move_insn (reg, pic_ref);
765           pic_ref = gen_const_mem (GET_MODE (orig), reg);
766 #endif
767         }
768       else
769         {
770
771 #ifdef HAVE_lo_sum
772           if (GET_CODE (orig) == SYMBOL_REF
773               || GET_CODE (orig) == LABEL_REF)
774             {
775               rtx offset = machopic_gen_offset (orig);
776 #if defined (TARGET_TOC) /* i.e., PowerPC */
777               rtx hi_sum_reg;
778
779               if (reg == 0)
780                 {
781                   gcc_assert (!reload_in_progress);
782                   reg = gen_reg_rtx (Pmode);
783                 }
784
785               hi_sum_reg = reg;
786
787               emit_insn (gen_rtx_SET (Pmode, hi_sum_reg,
788                                       (MACHO_DYNAMIC_NO_PIC_P)
789                                       ? gen_rtx_HIGH (Pmode, offset)
790                                       : gen_rtx_PLUS (Pmode,
791                                                       pic_offset_table_rtx,
792                                                       gen_rtx_HIGH (Pmode,
793                                                                     offset))));
794               emit_insn (gen_rtx_SET (VOIDmode, reg,
795                                       gen_rtx_LO_SUM (Pmode,
796                                                       hi_sum_reg,
797                                                       copy_rtx (offset))));
798               pic_ref = reg;
799 #else
800               emit_insn (gen_rtx_SET (VOIDmode, reg,
801                                       gen_rtx_HIGH (Pmode, offset)));
802               emit_insn (gen_rtx_SET (VOIDmode, reg,
803                                       gen_rtx_LO_SUM (Pmode, reg,
804                                                       copy_rtx (offset))));
805               pic_ref = gen_rtx_PLUS (Pmode,
806                                       pic_offset_table_rtx, reg);
807 #endif
808             }
809           else
810 #endif  /*  HAVE_lo_sum  */
811             {
812               if (REG_P (orig)
813                   || GET_CODE (orig) == SUBREG)
814                 {
815                   return orig;
816                 }
817               else
818                 {
819                   rtx pic = pic_offset_table_rtx;
820                   if (GET_CODE (pic) != REG)
821                     {
822                       emit_move_insn (reg, pic);
823                       pic = reg;
824                     }
825 #if 0
826                   emit_use (pic_offset_table_rtx);
827 #endif
828                   if (reload_in_progress)
829                     df_set_regs_ever_live (REGNO (pic), true);
830                   pic_ref = gen_rtx_PLUS (Pmode,
831                                           pic,
832                                           machopic_gen_offset (orig));
833                 }
834             }
835         }
836
837       if (GET_CODE (pic_ref) != REG)
838         {
839           if (reg != 0)
840             {
841               emit_move_insn (reg, pic_ref);
842               return reg;
843             }
844           else
845             {
846               return force_reg (mode, pic_ref);
847             }
848         }
849       else
850         {
851           return pic_ref;
852         }
853     }
854
855   else if (GET_CODE (orig) == SYMBOL_REF)
856     return orig;
857
858   else if (GET_CODE (orig) == PLUS
859            && (GET_CODE (XEXP (orig, 0)) == MEM
860                || GET_CODE (XEXP (orig, 0)) == SYMBOL_REF
861                || GET_CODE (XEXP (orig, 0)) == LABEL_REF)
862            && XEXP (orig, 0) != pic_offset_table_rtx
863            && GET_CODE (XEXP (orig, 1)) != REG)
864
865     {
866       rtx base;
867       int is_complex = (GET_CODE (XEXP (orig, 0)) == MEM);
868
869       base = machopic_legitimize_pic_address (XEXP (orig, 0), Pmode, reg);
870       orig = machopic_legitimize_pic_address (XEXP (orig, 1),
871                                               Pmode, (base == reg ? 0 : reg));
872       if (GET_CODE (orig) == CONST_INT)
873         {
874           pic_ref = plus_constant (base, INTVAL (orig));
875           is_complex = 1;
876         }
877       else
878         pic_ref = gen_rtx_PLUS (Pmode, base, orig);
879
880       if (reg && is_complex)
881         {
882           emit_move_insn (reg, pic_ref);
883           pic_ref = reg;
884         }
885       /* Likewise, should we set special REG_NOTEs here?  */
886     }
887
888   else if (GET_CODE (orig) == CONST)
889     {
890       return machopic_legitimize_pic_address (XEXP (orig, 0), Pmode, reg);
891     }
892
893   else if (GET_CODE (orig) == MEM
894            && GET_CODE (XEXP (orig, 0)) == SYMBOL_REF)
895     {
896       rtx addr = machopic_legitimize_pic_address (XEXP (orig, 0), Pmode, reg);
897       addr = replace_equiv_address (orig, addr);
898       emit_move_insn (reg, addr);
899       pic_ref = reg;
900     }
901
902   return pic_ref;
903 }
904
905 /* Output the stub or non-lazy pointer in *SLOT, if it has been used.
906    DATA is the FILE* for assembly output.  Called from
907    htab_traverse.  */
908
909 static int
910 machopic_output_indirection (void **slot, void *data)
911 {
912   machopic_indirection *p = *((machopic_indirection **) slot);
913   FILE *asm_out_file = (FILE *) data;
914   rtx symbol;
915   const char *sym_name;
916   const char *ptr_name;
917
918   if (!p->used)
919     return 1;
920
921   symbol = p->symbol;
922   sym_name = XSTR (symbol, 0);
923   ptr_name = p->ptr_name;
924
925   if (p->stub_p)
926     {
927       char *sym;
928       char *stub;
929       tree id;
930
931       id = maybe_get_identifier (sym_name);
932       if (id)
933         {
934           tree id_orig = id;
935
936           while (IDENTIFIER_TRANSPARENT_ALIAS (id))
937             id = TREE_CHAIN (id);
938           if (id != id_orig)
939             sym_name = IDENTIFIER_POINTER (id);
940         }
941
942       sym = XALLOCAVEC (char, strlen (sym_name) + 2);
943       if (sym_name[0] == '*' || sym_name[0] == '&')
944         strcpy (sym, sym_name + 1);
945       else if (sym_name[0] == '-' || sym_name[0] == '+')
946         strcpy (sym, sym_name);
947       else
948         sprintf (sym, "%s%s", user_label_prefix, sym_name);
949
950       stub = XALLOCAVEC (char, strlen (ptr_name) + 2);
951       if (ptr_name[0] == '*' || ptr_name[0] == '&')
952         strcpy (stub, ptr_name + 1);
953       else
954         sprintf (stub, "%s%s", user_label_prefix, ptr_name);
955
956       machopic_output_stub (asm_out_file, sym, stub);
957     }
958   else if (! indirect_data (symbol)
959            && (machopic_symbol_defined_p (symbol)
960                || SYMBOL_REF_LOCAL_P (symbol)))
961     {
962       switch_to_section (data_section);
963       assemble_align (GET_MODE_ALIGNMENT (Pmode));
964       assemble_label (ptr_name);
965       assemble_integer (gen_rtx_SYMBOL_REF (Pmode, sym_name),
966                         GET_MODE_SIZE (Pmode),
967                         GET_MODE_ALIGNMENT (Pmode), 1);
968     }
969   else
970     {
971       rtx init = const0_rtx;
972
973       switch_to_section (darwin_sections[machopic_nl_symbol_ptr_section]);
974
975       /* Mach-O symbols are passed around in code through indirect
976          references and the original symbol_ref hasn't passed through
977          the generic handling and reference-catching in
978          output_operand, so we need to manually mark weak references
979          as such.  */
980       if (SYMBOL_REF_WEAK (symbol))
981         {
982           tree decl = SYMBOL_REF_DECL (symbol);
983           gcc_assert (DECL_P (decl));
984
985           if (decl != NULL_TREE
986               && DECL_EXTERNAL (decl) && TREE_PUBLIC (decl)
987               /* Handle only actual external-only definitions, not
988                  e.g. extern inline code or variables for which
989                  storage has been allocated.  */
990               && !TREE_STATIC (decl))
991             {
992               fputs ("\t.weak_reference ", asm_out_file);
993               assemble_name (asm_out_file, sym_name);
994               fputc ('\n', asm_out_file);
995             }
996         }
997
998       assemble_name (asm_out_file, ptr_name);
999       fprintf (asm_out_file, ":\n");
1000
1001       fprintf (asm_out_file, "\t.indirect_symbol ");
1002       assemble_name (asm_out_file, sym_name);
1003       fprintf (asm_out_file, "\n");
1004
1005       /* Variables that are marked with MACHO_SYMBOL_STATIC need to
1006          have their symbol name instead of 0 in the second entry of
1007          the non-lazy symbol pointer data structure when they are
1008          defined.  This allows the runtime to rebind newer instances
1009          of the translation unit with the original instance of the
1010          symbol.  */
1011
1012       if ((SYMBOL_REF_FLAGS (symbol) & MACHO_SYMBOL_STATIC)
1013           && machopic_symbol_defined_p (symbol))
1014         init = gen_rtx_SYMBOL_REF (Pmode, sym_name);
1015
1016       assemble_integer (init, GET_MODE_SIZE (Pmode),
1017                         GET_MODE_ALIGNMENT (Pmode), 1);
1018     }
1019
1020   return 1;
1021 }
1022
1023 void
1024 machopic_finish (FILE *asm_out_file)
1025 {
1026   if (machopic_indirections)
1027     htab_traverse_noresize (machopic_indirections,
1028                             machopic_output_indirection,
1029                             asm_out_file);
1030 }
1031
1032 int
1033 machopic_operand_p (rtx op)
1034 {
1035   if (MACHOPIC_JUST_INDIRECT)
1036     return (GET_CODE (op) == SYMBOL_REF
1037             && machopic_symbol_defined_p (op));
1038   else
1039     return (GET_CODE (op) == CONST
1040             && GET_CODE (XEXP (op, 0)) == UNSPEC
1041             && XINT (XEXP (op, 0), 1) == UNSPEC_MACHOPIC_OFFSET);
1042 }
1043
1044 /* This function records whether a given name corresponds to a defined
1045    or undefined function or variable, for machopic_classify_ident to
1046    use later.  */
1047
1048 void
1049 darwin_encode_section_info (tree decl, rtx rtl, int first ATTRIBUTE_UNUSED)
1050 {
1051   rtx sym_ref;
1052
1053   /* Do the standard encoding things first.  */
1054   default_encode_section_info (decl, rtl, first);
1055
1056   if (TREE_CODE (decl) != FUNCTION_DECL && TREE_CODE (decl) != VAR_DECL)
1057     return;
1058
1059   sym_ref = XEXP (rtl, 0);
1060   if (TREE_CODE (decl) == VAR_DECL)
1061     SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_VARIABLE;
1062
1063   if (!DECL_EXTERNAL (decl)
1064       && (!TREE_PUBLIC (decl) || !DECL_WEAK (decl))
1065       && ! lookup_attribute ("weakref", DECL_ATTRIBUTES (decl))
1066       && ((TREE_STATIC (decl)
1067            && (!DECL_COMMON (decl) || !TREE_PUBLIC (decl)))
1068           || (!DECL_COMMON (decl) && DECL_INITIAL (decl)
1069               && DECL_INITIAL (decl) != error_mark_node)))
1070     SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_DEFINED;
1071
1072   if (! TREE_PUBLIC (decl))
1073     SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_STATIC;
1074 }
1075
1076 void
1077 darwin_mark_decl_preserved (const char *name)
1078 {
1079   fprintf (asm_out_file, ".no_dead_strip ");
1080   assemble_name (asm_out_file, name);
1081   fputc ('\n', asm_out_file);
1082 }
1083
1084 static section *
1085 darwin_text_section (int reloc, int weak)
1086 {
1087   if (reloc)
1088     return (weak
1089             ? darwin_sections[text_unlikely_coal_section]
1090             : unlikely_text_section ());
1091   else
1092     return (weak
1093             ? darwin_sections[text_coal_section]
1094             : text_section);
1095 }
1096
1097 static section *
1098 darwin_rodata_section (int weak)
1099 {
1100   return (weak
1101           ? darwin_sections[const_coal_section]
1102           : darwin_sections[const_section]);
1103 }
1104
1105 static section *
1106 darwin_mergeable_string_section (tree exp,
1107                                  unsigned HOST_WIDE_INT align)
1108 {
1109   if (flag_merge_constants
1110       && TREE_CODE (exp) == STRING_CST
1111       && TREE_CODE (TREE_TYPE (exp)) == ARRAY_TYPE
1112       && align <= 256
1113       && (int_size_in_bytes (TREE_TYPE (exp))
1114           == TREE_STRING_LENGTH (exp))
1115       && ((size_t) TREE_STRING_LENGTH (exp)
1116           == strlen (TREE_STRING_POINTER (exp)) + 1))
1117     return darwin_sections[cstring_section];
1118
1119   return readonly_data_section;
1120 }
1121
1122 #ifndef HAVE_GAS_LITERAL16
1123 #define HAVE_GAS_LITERAL16 0
1124 #endif
1125
1126 static section *
1127 darwin_mergeable_constant_section (tree exp,
1128                                    unsigned HOST_WIDE_INT align)
1129 {
1130   enum machine_mode mode = DECL_MODE (exp);
1131   unsigned int modesize = GET_MODE_BITSIZE (mode);
1132
1133   if (flag_merge_constants
1134       && mode != VOIDmode
1135       && mode != BLKmode
1136       && modesize <= align
1137       && align >= 8
1138       && align <= 256
1139       && (align & (align -1)) == 0)
1140     {
1141       tree size = TYPE_SIZE_UNIT (TREE_TYPE (exp));
1142
1143       if (TREE_CODE (size) == INTEGER_CST
1144           && TREE_INT_CST_LOW (size) == 4
1145           && TREE_INT_CST_HIGH (size) == 0)
1146         return darwin_sections[literal4_section];
1147       else if (TREE_CODE (size) == INTEGER_CST
1148                && TREE_INT_CST_LOW (size) == 8
1149                && TREE_INT_CST_HIGH (size) == 0)
1150         return darwin_sections[literal8_section];
1151       else if (HAVE_GAS_LITERAL16
1152                && TARGET_64BIT
1153                && TREE_CODE (size) == INTEGER_CST
1154                && TREE_INT_CST_LOW (size) == 16
1155                && TREE_INT_CST_HIGH (size) == 0)
1156         return darwin_sections[literal16_section];
1157       else
1158         return readonly_data_section;
1159     }
1160
1161   return readonly_data_section;
1162 }
1163
1164 int
1165 machopic_reloc_rw_mask (void)
1166 {
1167   return MACHOPIC_INDIRECT ? 3 : 0;
1168 }
1169
1170 section *
1171 machopic_select_section (tree decl,
1172                          int reloc,
1173                          unsigned HOST_WIDE_INT align)
1174 {
1175   bool weak = (DECL_P (decl)
1176                && DECL_WEAK (decl)
1177                && !lookup_attribute ("weak_import",
1178                                      DECL_ATTRIBUTES (decl)));
1179   section *base_section;
1180
1181   switch (categorize_decl_for_section (decl, reloc))
1182     {
1183     case SECCAT_TEXT:
1184       base_section = darwin_text_section (reloc, weak);
1185       break;
1186
1187     case SECCAT_RODATA:
1188     case SECCAT_SRODATA:
1189       base_section = darwin_rodata_section (weak);
1190       break;
1191
1192     case SECCAT_RODATA_MERGE_STR:
1193       base_section = darwin_mergeable_string_section (decl, align);
1194       break;
1195
1196     case SECCAT_RODATA_MERGE_STR_INIT:
1197       base_section = darwin_mergeable_string_section (DECL_INITIAL (decl), align);
1198       break;
1199
1200     case SECCAT_RODATA_MERGE_CONST:
1201       base_section =  darwin_mergeable_constant_section (decl, align);
1202       break;
1203
1204     case SECCAT_DATA:
1205     case SECCAT_DATA_REL:
1206     case SECCAT_DATA_REL_LOCAL:
1207     case SECCAT_DATA_REL_RO:
1208     case SECCAT_DATA_REL_RO_LOCAL:
1209     case SECCAT_SDATA:
1210     case SECCAT_TDATA:
1211     case SECCAT_BSS:
1212     case SECCAT_SBSS:
1213     case SECCAT_TBSS:
1214       if (TREE_READONLY (decl) || TREE_CONSTANT (decl))
1215         base_section = weak ? darwin_sections[const_data_coal_section]
1216                             : darwin_sections[const_data_section];
1217       else
1218         base_section = weak ? darwin_sections[data_coal_section] : data_section;
1219       break;
1220
1221     default:
1222       gcc_unreachable ();
1223     }
1224
1225   /* Darwin weird special cases.  */
1226   if (TREE_CODE (decl) == CONSTRUCTOR
1227       && TREE_TYPE (decl)
1228       && TREE_CODE (TREE_TYPE (decl)) == RECORD_TYPE
1229       && TYPE_NAME (TREE_TYPE (decl)))
1230     {
1231       tree name = TYPE_NAME (TREE_TYPE (decl));
1232       if (TREE_CODE (name) == TYPE_DECL)
1233         name = DECL_NAME (name);
1234
1235       if (!strcmp (IDENTIFIER_POINTER (name), "__builtin_ObjCString"))
1236         {
1237           if (flag_next_runtime)
1238             return darwin_sections[objc_constant_string_object_section];
1239           else
1240             return darwin_sections[objc_string_object_section];
1241         }
1242       else
1243         return base_section;
1244     }
1245   else if (TREE_CODE (decl) == VAR_DECL
1246            && DECL_NAME (decl)
1247            && TREE_CODE (DECL_NAME (decl)) == IDENTIFIER_NODE
1248            && IDENTIFIER_POINTER (DECL_NAME (decl))
1249            && !strncmp (IDENTIFIER_POINTER (DECL_NAME (decl)), "_OBJC_", 6))
1250     {
1251       const char *name = IDENTIFIER_POINTER (DECL_NAME (decl));
1252
1253       if (!strncmp (name, "_OBJC_CLASS_METHODS_", 20))
1254         return darwin_sections[objc_cls_meth_section];
1255       else if (!strncmp (name, "_OBJC_INSTANCE_METHODS_", 23))
1256         return darwin_sections[objc_inst_meth_section];
1257       else if (!strncmp (name, "_OBJC_CATEGORY_CLASS_METHODS_", 20))
1258         return darwin_sections[objc_cat_cls_meth_section];
1259       else if (!strncmp (name, "_OBJC_CATEGORY_INSTANCE_METHODS_", 23))
1260         return darwin_sections[objc_cat_inst_meth_section];
1261       else if (!strncmp (name, "_OBJC_CLASS_VARIABLES_", 22))
1262         return darwin_sections[objc_class_vars_section];
1263       else if (!strncmp (name, "_OBJC_INSTANCE_VARIABLES_", 25))
1264         return darwin_sections[objc_instance_vars_section];
1265       else if (!strncmp (name, "_OBJC_CLASS_PROTOCOLS_", 22))
1266         return darwin_sections[objc_cat_cls_meth_section];
1267       else if (!strncmp (name, "_OBJC_CLASS_NAME_", 17))
1268         return darwin_sections[objc_class_names_section];
1269       else if (!strncmp (name, "_OBJC_METH_VAR_NAME_", 20))
1270         return darwin_sections[objc_meth_var_names_section];
1271       else if (!strncmp (name, "_OBJC_METH_VAR_TYPE_", 20))
1272         return darwin_sections[objc_meth_var_types_section];
1273       else if (!strncmp (name, "_OBJC_CLASS_REFERENCES", 22))
1274         return darwin_sections[objc_cls_refs_section];
1275       else if (!strncmp (name, "_OBJC_CLASS_", 12))
1276         return darwin_sections[objc_class_section];
1277       else if (!strncmp (name, "_OBJC_METACLASS_", 16))
1278         return darwin_sections[objc_meta_class_section];
1279       else if (!strncmp (name, "_OBJC_CATEGORY_", 15))
1280         return darwin_sections[objc_category_section];
1281       else if (!strncmp (name, "_OBJC_SELECTOR_REFERENCES", 25))
1282         return darwin_sections[objc_selector_refs_section];
1283       else if (!strncmp (name, "_OBJC_SELECTOR_FIXUP", 20))
1284         return darwin_sections[objc_selector_fixup_section];
1285       else if (!strncmp (name, "_OBJC_SYMBOLS", 13))
1286         return darwin_sections[objc_symbols_section];
1287       else if (!strncmp (name, "_OBJC_MODULES", 13))
1288         return darwin_sections[objc_module_info_section];
1289       else if (!strncmp (name, "_OBJC_IMAGE_INFO", 16))
1290         return darwin_sections[objc_image_info_section];
1291       else if (!strncmp (name, "_OBJC_PROTOCOL_INSTANCE_METHODS_", 32))
1292         return darwin_sections[objc_cat_inst_meth_section];
1293       else if (!strncmp (name, "_OBJC_PROTOCOL_CLASS_METHODS_", 29))
1294         return darwin_sections[objc_cat_cls_meth_section];
1295       else if (!strncmp (name, "_OBJC_PROTOCOL_REFS_", 20))
1296         return darwin_sections[objc_cat_cls_meth_section];
1297       else if (!strncmp (name, "_OBJC_PROTOCOL_", 15))
1298         return darwin_sections[objc_protocol_section];
1299       else
1300         return base_section;
1301     }
1302
1303   return base_section;
1304 }
1305
1306 /* This can be called with address expressions as "rtx".
1307    They must go in "const".  */
1308
1309 section *
1310 machopic_select_rtx_section (enum machine_mode mode, rtx x,
1311                              unsigned HOST_WIDE_INT align ATTRIBUTE_UNUSED)
1312 {
1313   if (GET_MODE_SIZE (mode) == 8
1314       && (GET_CODE (x) == CONST_INT
1315           || GET_CODE (x) == CONST_DOUBLE))
1316     return darwin_sections[literal8_section];
1317   else if (GET_MODE_SIZE (mode) == 4
1318            && (GET_CODE (x) == CONST_INT
1319                || GET_CODE (x) == CONST_DOUBLE))
1320     return darwin_sections[literal4_section];
1321   else if (HAVE_GAS_LITERAL16
1322            && TARGET_64BIT
1323            && GET_MODE_SIZE (mode) == 16
1324            && (GET_CODE (x) == CONST_INT
1325                || GET_CODE (x) == CONST_DOUBLE
1326                || GET_CODE (x) == CONST_VECTOR))
1327     return darwin_sections[literal16_section];
1328   else if (MACHOPIC_INDIRECT
1329            && (GET_CODE (x) == SYMBOL_REF
1330                || GET_CODE (x) == CONST
1331                || GET_CODE (x) == LABEL_REF))
1332     return darwin_sections[const_data_section];
1333   else
1334     return darwin_sections[const_section];
1335 }
1336
1337 void
1338 machopic_asm_out_constructor (rtx symbol, int priority ATTRIBUTE_UNUSED)
1339 {
1340   if (MACHOPIC_INDIRECT)
1341     switch_to_section (darwin_sections[mod_init_section]);
1342   else
1343     switch_to_section (darwin_sections[constructor_section]);
1344   assemble_align (POINTER_SIZE);
1345   assemble_integer (symbol, POINTER_SIZE / BITS_PER_UNIT, POINTER_SIZE, 1);
1346
1347   if (! MACHOPIC_INDIRECT)
1348     fprintf (asm_out_file, ".reference .constructors_used\n");
1349 }
1350
1351 void
1352 machopic_asm_out_destructor (rtx symbol, int priority ATTRIBUTE_UNUSED)
1353 {
1354   if (MACHOPIC_INDIRECT)
1355     switch_to_section (darwin_sections[mod_term_section]);
1356   else
1357     switch_to_section (darwin_sections[destructor_section]);
1358   assemble_align (POINTER_SIZE);
1359   assemble_integer (symbol, POINTER_SIZE / BITS_PER_UNIT, POINTER_SIZE, 1);
1360
1361   if (! MACHOPIC_INDIRECT)
1362     fprintf (asm_out_file, ".reference .destructors_used\n");
1363 }
1364
1365 void
1366 darwin_globalize_label (FILE *stream, const char *name)
1367 {
1368   if (!!strncmp (name, "_OBJC_", 6))
1369     default_globalize_label (stream, name);
1370 }
1371
1372 /* This routine returns non-zero if 'name' starts with the special objective-c 
1373    anonymous file-scope static name.  It accommodates c++'s mangling of such 
1374    symbols (in this case the symbols will have form _ZL{d}*_OBJC_* d=digit).  */
1375    
1376 int 
1377 darwin_label_is_anonymous_local_objc_name (const char *name)
1378 {
1379   const unsigned char *p = (const unsigned char *) name;
1380   if (*p != '_')
1381     return 0;
1382   if (p[1] == 'Z' && p[2] == 'L')
1383   {
1384     p += 3;
1385     while (*p >= '0' && *p <= '9')
1386       p++;
1387   }
1388   return (!strncmp ((const char *)p, "_OBJC_", 6));
1389 }
1390
1391 /* LTO support for Mach-O.  */
1392
1393 /* Section names for LTO sections.  */
1394 static unsigned int lto_section_names_offset = 0;
1395
1396 /* This is the obstack which we use to allocate the many strings.  */
1397 static struct obstack lto_section_names_obstack;
1398
1399 /* Segment name for LTO sections.  */
1400 #define LTO_SEGMENT_NAME "__GNU_LTO"
1401
1402 /* Section name for LTO section names section.  */
1403 #define LTO_NAMES_SECTION "__section_names"
1404
1405 /* File to temporarily store LTO data.  This is appended to asm_out_file
1406    in darwin_end_file.  */
1407 static FILE *lto_asm_out_file, *saved_asm_out_file;
1408 static char *lto_asm_out_name;
1409
1410 /* Prepare asm_out_file for LTO output.  For darwin, this means hiding
1411    asm_out_file and switching to an alternative output file.  */
1412 void
1413 darwin_asm_lto_start (void)
1414 {
1415   gcc_assert (! saved_asm_out_file);
1416   saved_asm_out_file = asm_out_file;
1417   if (! lto_asm_out_name)
1418     lto_asm_out_name = make_temp_file (".lto.s");
1419   lto_asm_out_file = fopen (lto_asm_out_name, "a");
1420   if (lto_asm_out_file == NULL)
1421     fatal_error ("failed to open temporary file %s for LTO output",
1422                  lto_asm_out_name);
1423   asm_out_file = lto_asm_out_file;
1424 }
1425
1426 /* Restore asm_out_file.  */
1427 void
1428 darwin_asm_lto_end (void)
1429 {
1430   gcc_assert (saved_asm_out_file);
1431   fclose (lto_asm_out_file);
1432   asm_out_file = saved_asm_out_file;
1433   saved_asm_out_file = NULL;
1434 }
1435
1436 void
1437 darwin_asm_named_section (const char *name,
1438                           unsigned int flags,
1439                           tree decl ATTRIBUTE_UNUSED)
1440 {
1441   /* LTO sections go in a special segment __GNU_LTO.  We want to replace the
1442      section name with something we can use to represent arbitrary-length
1443      names (section names in Mach-O are at most 16 characters long).  */
1444   if (strncmp (name, LTO_SECTION_NAME_PREFIX,
1445                strlen (LTO_SECTION_NAME_PREFIX)) == 0)
1446     {
1447       /* We expect certain flags to be set...  */
1448       gcc_assert ((flags & (SECTION_DEBUG | SECTION_NAMED))
1449                   == (SECTION_DEBUG | SECTION_NAMED));
1450
1451       /* Add the section name to the things to output when we end the
1452          current assembler output file.
1453          This is all not very efficient, but that doesn't matter -- this
1454          shouldn't be a hot path in the compiler...  */
1455       obstack_1grow (&lto_section_names_obstack, '\t');
1456       obstack_grow (&lto_section_names_obstack, ".ascii ", 7);
1457       obstack_1grow (&lto_section_names_obstack, '"');
1458       obstack_grow (&lto_section_names_obstack, name, strlen (name));
1459       obstack_grow (&lto_section_names_obstack, "\\0\"\n", 4);
1460
1461       /* Output the dummy section name.  */
1462       fprintf (asm_out_file, "\t# %s\n", name);
1463       fprintf (asm_out_file, "\t.section %s,__%08X,regular,debug\n",
1464                LTO_SEGMENT_NAME, lto_section_names_offset);
1465
1466       /* Update the offset for the next section name.  Make sure we stay
1467          within reasonable length.  */  
1468       lto_section_names_offset += strlen (name) + 1;
1469       gcc_assert (lto_section_names_offset > 0
1470                   && lto_section_names_offset < ((unsigned) 1 << 31));
1471     }
1472   else
1473     fprintf (asm_out_file, "\t.section %s\n", name);
1474 }
1475
1476 void
1477 darwin_unique_section (tree decl ATTRIBUTE_UNUSED, int reloc ATTRIBUTE_UNUSED)
1478 {
1479   /* Darwin does not use unique sections.  */
1480 }
1481
1482 /* Handle __attribute__ ((apple_kext_compatibility)).
1483    This only applies to darwin kexts for 2.95 compatibility -- it shrinks the
1484    vtable for classes with this attribute (and their descendants) by not
1485    outputting the new 3.0 nondeleting destructor.  This means that such
1486    objects CANNOT be allocated on the stack or as globals UNLESS they have
1487    a completely empty `operator delete'.
1488    Luckily, this fits in with the Darwin kext model.
1489
1490    This attribute also disables gcc3's potential overlaying of derived
1491    class data members on the padding at the end of the base class.  */
1492
1493 tree
1494 darwin_handle_kext_attribute (tree *node, tree name,
1495                               tree args ATTRIBUTE_UNUSED,
1496                               int flags ATTRIBUTE_UNUSED,
1497                               bool *no_add_attrs)
1498 {
1499   /* APPLE KEXT stuff -- only applies with pure static C++ code.  */
1500   if (! TARGET_KEXTABI)
1501     {
1502       warning (0, "%qE 2.95 vtable-compatibility attribute applies "
1503                "only when compiling a kext", name);
1504
1505       *no_add_attrs = true;
1506     }
1507   else if (TREE_CODE (*node) != RECORD_TYPE)
1508     {
1509       warning (0, "%qE 2.95 vtable-compatibility attribute applies "
1510                "only to C++ classes", name);
1511
1512       *no_add_attrs = true;
1513     }
1514
1515   return NULL_TREE;
1516 }
1517
1518 /* Handle a "weak_import" attribute; arguments as in
1519    struct attribute_spec.handler.  */
1520
1521 tree
1522 darwin_handle_weak_import_attribute (tree *node, tree name,
1523                                      tree ARG_UNUSED (args),
1524                                      int ARG_UNUSED (flags),
1525                                      bool * no_add_attrs)
1526 {
1527   if (TREE_CODE (*node) != FUNCTION_DECL && TREE_CODE (*node) != VAR_DECL)
1528     {
1529       warning (OPT_Wattributes, "%qE attribute ignored",
1530                name);
1531       *no_add_attrs = true;
1532     }
1533   else
1534     declare_weak (*node);
1535
1536   return NULL_TREE;
1537 }
1538
1539 /* Emit a label for an FDE, making it global and/or weak if appropriate.
1540    The third parameter is nonzero if this is for exception handling.
1541    The fourth parameter is nonzero if this is just a placeholder for an
1542    FDE that we are omitting. */
1543
1544 void
1545 darwin_emit_unwind_label (FILE *file, tree decl, int for_eh, int empty)
1546 {
1547   char *lab;
1548
1549   if (! for_eh)
1550     return;
1551
1552   lab = concat (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl)), ".eh", NULL);
1553
1554   if (TREE_PUBLIC (decl))
1555     {
1556       targetm.asm_out.globalize_label (file, lab);
1557       if (DECL_VISIBILITY (decl) == VISIBILITY_HIDDEN)
1558         {
1559           fputs ("\t.private_extern ", file);
1560           assemble_name (file, lab);
1561           fputc ('\n', file);
1562         }
1563     }
1564
1565   if (DECL_WEAK (decl))
1566     {
1567       fputs ("\t.weak_definition ", file);
1568       assemble_name (file, lab);
1569       fputc ('\n', file);
1570     }
1571
1572   assemble_name (file, lab);
1573   if (empty)
1574     {
1575       fputs (" = 0\n", file);
1576
1577       /* Mark the absolute .eh and .eh1 style labels as needed to
1578          ensure that we don't dead code strip them and keep such
1579          labels from another instantiation point until we can fix this
1580          properly with group comdat support.  */
1581       darwin_mark_decl_preserved (lab);
1582     }
1583   else
1584     fputs (":\n", file);
1585
1586   free (lab);
1587 }
1588
1589 static GTY(()) unsigned long except_table_label_num;
1590
1591 void
1592 darwin_emit_except_table_label (FILE *file)
1593 {
1594   char section_start_label[30];
1595
1596   ASM_GENERATE_INTERNAL_LABEL (section_start_label, "GCC_except_table",
1597                                except_table_label_num++);
1598   ASM_OUTPUT_LABEL (file, section_start_label);
1599 }
1600 /* Generate a PC-relative reference to a Mach-O non-lazy-symbol.  */
1601
1602 void
1603 darwin_non_lazy_pcrel (FILE *file, rtx addr)
1604 {
1605   const char *nlp_name;
1606
1607   gcc_assert (GET_CODE (addr) == SYMBOL_REF);
1608
1609   nlp_name = machopic_indirection_name (addr, /*stub_p=*/false);
1610   fputs ("\t.long\t", file);
1611   ASM_OUTPUT_LABELREF (file, nlp_name);
1612   fputs ("-.", file);
1613 }
1614
1615 /* Emit an assembler directive to set visibility for a symbol.  The
1616    only supported visibilities are VISIBILITY_DEFAULT and
1617    VISIBILITY_HIDDEN; the latter corresponds to Darwin's "private
1618    extern".  There is no MACH-O equivalent of ELF's
1619    VISIBILITY_INTERNAL or VISIBILITY_PROTECTED. */
1620
1621 void
1622 darwin_assemble_visibility (tree decl, int vis)
1623 {
1624   if (vis == VISIBILITY_DEFAULT)
1625     ;
1626   else if (vis == VISIBILITY_HIDDEN)
1627     {
1628       fputs ("\t.private_extern ", asm_out_file);
1629       assemble_name (asm_out_file,
1630                      (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl))));
1631       fputs ("\n", asm_out_file);
1632     }
1633   else
1634     warning (OPT_Wattributes, "internal and protected visibility attributes "
1635              "not supported in this configuration; ignored");
1636 }
1637
1638 /* Output a difference of two labels that will be an assembly time
1639    constant if the two labels are local.  (.long lab1-lab2 will be
1640    very different if lab1 is at the boundary between two sections; it
1641    will be relocated according to the second section, not the first,
1642    so one ends up with a difference between labels in different
1643    sections, which is bad in the dwarf2 eh context for instance.)  */
1644
1645 static int darwin_dwarf_label_counter;
1646
1647 void
1648 darwin_asm_output_dwarf_delta (FILE *file, int size,
1649                                const char *lab1, const char *lab2)
1650 {
1651   int islocaldiff = (lab1[0] == '*' && lab1[1] == 'L'
1652                      && lab2[0] == '*' && lab2[1] == 'L');
1653   const char *directive = (size == 8 ? ".quad" : ".long");
1654
1655   if (islocaldiff)
1656     fprintf (file, "\t.set L$set$%d,", darwin_dwarf_label_counter);
1657   else
1658     fprintf (file, "\t%s\t", directive);
1659   assemble_name_raw (file, lab1);
1660   fprintf (file, "-");
1661   assemble_name_raw (file, lab2);
1662   if (islocaldiff)
1663     fprintf (file, "\n\t%s L$set$%d", directive, darwin_dwarf_label_counter++);
1664 }
1665
1666 /* Output labels for the start of the DWARF sections if necessary.
1667    Initialize the stuff we need for LTO long section names support.  */
1668 void
1669 darwin_file_start (void)
1670 {
1671   if (write_symbols == DWARF2_DEBUG)
1672     {
1673       static const char * const debugnames[] =
1674         {
1675           DEBUG_FRAME_SECTION,
1676           DEBUG_INFO_SECTION,
1677           DEBUG_ABBREV_SECTION,
1678           DEBUG_ARANGES_SECTION,
1679           DEBUG_MACINFO_SECTION,
1680           DEBUG_LINE_SECTION,
1681           DEBUG_LOC_SECTION,
1682           DEBUG_PUBNAMES_SECTION,
1683           DEBUG_PUBTYPES_SECTION,
1684           DEBUG_STR_SECTION,
1685           DEBUG_RANGES_SECTION
1686         };
1687       size_t i;
1688
1689       for (i = 0; i < ARRAY_SIZE (debugnames); i++)
1690         {
1691           int namelen;
1692
1693           switch_to_section (get_section (debugnames[i], SECTION_DEBUG, NULL));
1694
1695           gcc_assert (strncmp (debugnames[i], "__DWARF,", 8) == 0);
1696           gcc_assert (strchr (debugnames[i] + 8, ','));
1697
1698           namelen = strchr (debugnames[i] + 8, ',') - (debugnames[i] + 8);
1699           fprintf (asm_out_file, "Lsection%.*s:\n", namelen, debugnames[i] + 8);
1700         }
1701     }
1702
1703   /* We fill this obstack with the complete section text for the lto section
1704      names to write in darwin_file_end.  */
1705   obstack_init (&lto_section_names_obstack);
1706   lto_section_names_offset = 0;
1707 }
1708
1709 /* Output an offset in a DWARF section on Darwin.  On Darwin, DWARF section
1710    offsets are not represented using relocs in .o files; either the
1711    section never leaves the .o file, or the linker or other tool is
1712    responsible for parsing the DWARF and updating the offsets.  */
1713
1714 void
1715 darwin_asm_output_dwarf_offset (FILE *file, int size, const char * lab,
1716                                 section *base)
1717 {
1718   char sname[64];
1719   int namelen;
1720
1721   gcc_assert (base->common.flags & SECTION_NAMED);
1722   gcc_assert (strncmp (base->named.name, "__DWARF,", 8) == 0);
1723   gcc_assert (strchr (base->named.name + 8, ','));
1724
1725   namelen = strchr (base->named.name + 8, ',') - (base->named.name + 8);
1726   sprintf (sname, "*Lsection%.*s", namelen, base->named.name + 8);
1727   darwin_asm_output_dwarf_delta (file, size, lab, sname);
1728 }
1729
1730 void
1731 darwin_file_end (void)
1732 {
1733   const char *lto_section_names;
1734
1735   machopic_finish (asm_out_file);
1736   if (strcmp (lang_hooks.name, "GNU C++") == 0)
1737     {
1738       switch_to_section (darwin_sections[constructor_section]);
1739       switch_to_section (darwin_sections[destructor_section]);
1740       ASM_OUTPUT_ALIGN (asm_out_file, 1);
1741     }
1742
1743   /* If there was LTO assembler output, append it to asm_out_file.  */
1744   if (lto_asm_out_name)
1745     {
1746       int n;
1747       char *buf, *lto_asm_txt;
1748
1749       /* Shouldn't be here if we failed to switch back.  */
1750       gcc_assert (! saved_asm_out_file);
1751
1752       lto_asm_out_file = fopen (lto_asm_out_name, "r");
1753       if (lto_asm_out_file == NULL)
1754         fatal_error ("failed to open temporary file %s with LTO output",
1755                      lto_asm_out_name);
1756       fseek (lto_asm_out_file, 0, SEEK_END);
1757       n = ftell (lto_asm_out_file);
1758       if (n > 0)
1759         {
1760           fseek (lto_asm_out_file, 0, SEEK_SET);
1761           lto_asm_txt = buf = (char *) xmalloc (n + 1);
1762           while (fgets (lto_asm_txt, n, lto_asm_out_file))
1763             fputs (lto_asm_txt, asm_out_file);
1764         }
1765
1766       /* Remove the temporary file.  */
1767       fclose (lto_asm_out_file);
1768       unlink_if_ordinary (lto_asm_out_name);
1769       free (lto_asm_out_name);
1770     }
1771
1772   /* Finish the LTO section names obstack.  Don't output anything if
1773      there are no recorded section names.  */
1774   obstack_1grow (&lto_section_names_obstack, '\0');
1775   lto_section_names = XOBFINISH (&lto_section_names_obstack, const char *);
1776   if (strlen (lto_section_names) > 0)
1777     {
1778       fprintf (asm_out_file,
1779                "\t.section %s,%s,regular,debug\n",
1780                LTO_SEGMENT_NAME, LTO_NAMES_SECTION);
1781       fprintf (asm_out_file,
1782                "\t# Section names in %s are offsets into this table\n",
1783                LTO_SEGMENT_NAME);
1784       fprintf (asm_out_file, "%s\n", lto_section_names);
1785     }
1786   obstack_free (&lto_section_names_obstack, NULL);
1787
1788   fprintf (asm_out_file, "\t.subsections_via_symbols\n");
1789 }
1790
1791 /* TODO: Add a language hook for identifying if a decl is a vtable.  */
1792 #define DARWIN_VTABLE_P(DECL) 0
1793
1794 /* Cross-module name binding.  Darwin does not support overriding
1795    functions at dynamic-link time, except for vtables in kexts.  */
1796
1797 bool
1798 darwin_binds_local_p (const_tree decl)
1799 {
1800   return default_binds_local_p_1 (decl,
1801                                   TARGET_KEXTABI && DARWIN_VTABLE_P (decl));
1802 }
1803
1804 #if 0
1805 /* See TARGET_ASM_OUTPUT_ANCHOR for why we can't do this yet.  */
1806 /* The Darwin's implementation of TARGET_ASM_OUTPUT_ANCHOR.  Define the
1807    anchor relative to ".", the current section position.  We cannot use
1808    the default one because ASM_OUTPUT_DEF is wrong for Darwin.  */
1809
1810 void
1811 darwin_asm_output_anchor (rtx symbol)
1812 {
1813   fprintf (asm_out_file, "\t.set\t");
1814   assemble_name (asm_out_file, XSTR (symbol, 0));
1815   fprintf (asm_out_file, ", . + " HOST_WIDE_INT_PRINT_DEC "\n",
1816            SYMBOL_REF_BLOCK_OFFSET (symbol));
1817 }
1818 #endif
1819
1820 /* Set the darwin specific attributes on TYPE.  */
1821 void
1822 darwin_set_default_type_attributes (tree type)
1823 {
1824   if (darwin_ms_struct
1825       && TREE_CODE (type) == RECORD_TYPE)
1826     TYPE_ATTRIBUTES (type) = tree_cons (get_identifier ("ms_struct"),
1827                                         NULL_TREE,
1828                                         TYPE_ATTRIBUTES (type));
1829 }
1830
1831 /* True, iff we're generating code for loadable kernel extensions.  */
1832
1833 bool
1834 darwin_kextabi_p (void) {
1835   return flag_apple_kext;
1836 }
1837
1838 void
1839 darwin_override_options (void)
1840 {
1841   /* Don't emit DWARF3/4 unless specifically selected.  This is a 
1842      workaround for tool bugs.  */
1843   if (dwarf_strict < 0) 
1844     dwarf_strict = 1;
1845
1846   /* Disable -freorder-blocks-and-partition for darwin_emit_unwind_label.  */
1847   if (flag_reorder_blocks_and_partition 
1848       && (targetm.asm_out.unwind_label == darwin_emit_unwind_label))
1849     {
1850       inform (input_location,
1851               "-freorder-blocks-and-partition does not work with exceptions "
1852               "on this architecture");
1853       flag_reorder_blocks_and_partition = 0;
1854       flag_reorder_blocks = 1;
1855     }
1856
1857   if (flag_mkernel || flag_apple_kext)
1858     {
1859       /* -mkernel implies -fapple-kext for C++ */
1860       if (strcmp (lang_hooks.name, "GNU C++") == 0)
1861         flag_apple_kext = 1;
1862
1863       flag_no_common = 1;
1864
1865       /* No EH in kexts.  */
1866       flag_exceptions = 0;
1867       /* No -fnon-call-exceptions data in kexts.  */
1868       flag_non_call_exceptions = 0;
1869     }
1870   if (flag_var_tracking
1871       && strverscmp (darwin_macosx_version_min, "10.5") >= 0
1872       && debug_info_level >= DINFO_LEVEL_NORMAL
1873       && debug_hooks->var_location != do_nothing_debug_hooks.var_location)
1874     flag_var_tracking_uninit = 1;
1875 }
1876
1877 /* Add $LDBL128 suffix to long double builtins.  */
1878
1879 static void
1880 darwin_patch_builtin (int fncode)
1881 {
1882   tree fn = built_in_decls[fncode];
1883   tree sym;
1884   char *newname;
1885
1886   if (!fn)
1887     return;
1888
1889   sym = DECL_ASSEMBLER_NAME (fn);
1890   newname = ACONCAT (("_", IDENTIFIER_POINTER (sym), "$LDBL128", NULL));
1891
1892   set_user_assembler_name (fn, newname);
1893
1894   fn = implicit_built_in_decls[fncode];
1895   if (fn)
1896     set_user_assembler_name (fn, newname);
1897 }
1898
1899 void
1900 darwin_patch_builtins (void)
1901 {
1902   if (LONG_DOUBLE_TYPE_SIZE != 128)
1903     return;
1904
1905 #define PATCH_BUILTIN(fncode) darwin_patch_builtin (fncode);
1906 #define PATCH_BUILTIN_NO64(fncode)              \
1907   if (!TARGET_64BIT)                            \
1908     darwin_patch_builtin (fncode);
1909 #define PATCH_BUILTIN_VARIADIC(fncode)                            \
1910   if (!TARGET_64BIT                                               \
1911       && (strverscmp (darwin_macosx_version_min, "10.3.9") >= 0)) \
1912     darwin_patch_builtin (fncode);
1913 #include "darwin-ppc-ldouble-patch.def"
1914 #undef PATCH_BUILTIN
1915 #undef PATCH_BUILTIN_NO64
1916 #undef PATCH_BUILTIN_VARIADIC
1917 }
1918
1919
1920 #include "gt-darwin.h"