1 /* Functions for generic Darwin as target machine for GNU C compiler.
2    Copyright (C) 1989-2013 Free Software Foundation, Inc.
3    Contributed by Apple Computer Inc.
4 
5 This file is part of GCC.
6 
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11 
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16 
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20 
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "rtl.h"
26 #include "regs.h"
27 #include "hard-reg-set.h"
28 #include "insn-config.h"
29 #include "conditions.h"
30 #include "insn-flags.h"
31 #include "output.h"
32 #include "insn-attr.h"
33 #include "flags.h"
34 #include "tree.h"
35 #include "expr.h"
36 #include "reload.h"
37 #include "function.h"
38 #include "ggc.h"
39 #include "langhooks.h"
40 #include "target.h"
41 #include "tm_p.h"
42 #include "diagnostic-core.h"
43 #include "toplev.h"
44 #include "hashtab.h"
45 #include "df.h"
46 #include "debug.h"
47 #include "obstack.h"
48 #include "lto-streamer.h"
49 
50 /* Darwin supports a feature called fix-and-continue, which is used
51    for rapid turn around debugging.  When code is compiled with the
52    -mfix-and-continue flag, two changes are made to the generated code
53    that allow the system to do things that it would normally not be
54    able to do easily.  These changes allow gdb to load in
55    recompilation of a translation unit that has been changed into a
56    running program and replace existing functions and methods of that
57    translation unit with versions of those functions and methods
58    from the newly compiled translation unit.  The new functions access
59    the existing static symbols from the old translation unit, if the
60    symbol existed in the unit to be replaced, and from the new
61    translation unit, otherwise.
62 
63    The changes are to insert 5 nops at the beginning of all functions
64    and to use indirection to get at static symbols.  The 5 nops
65    are required by consumers of the generated code.  Currently, gdb
66    uses this to patch in a jump to the overriding function, this
67    allows all uses of the old name to forward to the replacement,
68    including existing function pointers and virtual methods.  See
69    rs6000_emit_prologue for the code that handles the nop insertions.
70 
71    The added indirection allows gdb to redirect accesses to static
72    symbols from the newly loaded translation unit to the existing
73    symbol, if any.  @code{static} symbols are special and are handled by
74    setting the second word in the .non_lazy_symbol_pointer data
75    structure to symbol.  See indirect_data for the code that handles
76    the extra indirection, and machopic_output_indirection and its use
77    of MACHO_SYMBOL_STATIC for the code that handles @code{static}
78    symbol indirection.  */
79 
80 /* For darwin >= 9  (OSX 10.5) the linker is capable of making the necessary
81    branch islands and we no longer need to emit darwin stubs.
82    However, if we are generating code for earlier systems (or for use in the
83    kernel) the stubs might still be required, and this will be set true.  */
84 int darwin_emit_branch_islands = false;
85 
86 typedef struct GTY(()) cdtor_record {
87   rtx symbol;
88   int priority;		/* [con/de]structor priority */
89   int position;		/* original position */
90 } cdtor_record;
91 
92 static GTY(()) vec<cdtor_record, va_gc> *ctors = NULL;
93 static GTY(()) vec<cdtor_record, va_gc> *dtors = NULL;
94 
95 /* A flag to determine whether we are running c++ or obj-c++.  This has to be
96    settable from non-c-family contexts too (i.e. we can't use the c_dialect_
97    functions).  */
98 int darwin_running_cxx;
99 
100 /* Some code-gen now depends on OS major version numbers (at least).  */
101 int generating_for_darwin_version ;
102 
103 /* Section names.  */
104 section * darwin_sections[NUM_DARWIN_SECTIONS];
105 
106 /* While we transition to using in-tests instead of ifdef'd code.  */
107 #ifndef HAVE_lo_sum
108 #define HAVE_lo_sum 0
109 #define gen_macho_high(a,b) (a)
110 #define gen_macho_low(a,b,c) (a)
111 #endif
112 
113 /* True if we're setting __attribute__ ((ms_struct)).  */
114 int darwin_ms_struct = false;
115 
116 /* Earlier versions of Darwin as do not recognize an alignment field in
117    .comm directives, this should be set for versions that allow it.  */
118 int emit_aligned_common = false;
119 
120 /* A get_unnamed_section callback used to switch to an ObjC section.
121    DIRECTIVE is as for output_section_asm_op.  */
122 
123 static void
output_objc_section_asm_op(const void * directive)124 output_objc_section_asm_op (const void *directive)
125 {
126   static bool been_here = false;
127 
128   /* The NeXT ObjC Runtime requires these sections to be present and in
129      order in the object.  The code below implements this by emitting
130      a section header for each ObjC section the first time that an ObjC
131      section is requested.  */
132   if (! been_here)
133     {
134       section *saved_in_section = in_section;
135       static const enum darwin_section_enum tomark[] =
136 	{
137 	  /* written, cold -> hot */
138 	  objc_cat_cls_meth_section,
139 	  objc_cat_inst_meth_section,
140 	  objc_string_object_section,
141 	  objc_constant_string_object_section,
142 	  objc_selector_refs_section,
143 	  objc_selector_fixup_section,
144 	  objc_cls_refs_section,
145 	  objc_class_section,
146 	  objc_meta_class_section,
147 	  /* shared, hot -> cold */
148 	  objc_cls_meth_section,
149 	  objc_inst_meth_section,
150 	  objc_protocol_section,
151 	  objc_class_names_section,
152 	  objc_meth_var_types_section,
153 	  objc_meth_var_names_section,
154 	  objc_category_section,
155 	  objc_class_vars_section,
156 	  objc_instance_vars_section,
157 	  objc_module_info_section,
158 	  objc_symbols_section,
159 	};
160       /* ABI=1 */
161       static const enum darwin_section_enum tomarkv1[] =
162 	{
163 	  objc1_protocol_ext_section,
164 	  objc1_class_ext_section,
165 	  objc1_prop_list_section
166 	} ;
167       /* ABI=2 */
168       static const enum darwin_section_enum tomarkv2[] =
169 	{
170 	  objc2_message_refs_section,
171 	  objc2_classdefs_section,
172 	  objc2_metadata_section,
173 	  objc2_classrefs_section,
174 	  objc2_classlist_section,
175 	  objc2_categorylist_section,
176 	  objc2_selector_refs_section,
177 	  objc2_nonlazy_class_section,
178 	  objc2_nonlazy_category_section,
179 	  objc2_protocollist_section,
180 	  objc2_protocolrefs_section,
181 	  objc2_super_classrefs_section,
182 	  objc2_image_info_section,
183 	  objc2_constant_string_object_section
184 	} ;
185       size_t i;
186 
187       been_here = true;
188       if (flag_objc_abi < 2)
189 	{
190 	  for (i = 0; i < ARRAY_SIZE (tomark); i++)
191 	    switch_to_section (darwin_sections[tomark[i]]);
192 	  if (flag_objc_abi == 1)
193 	    for (i = 0; i < ARRAY_SIZE (tomarkv1); i++)
194 	      switch_to_section (darwin_sections[tomarkv1[i]]);
195 	}
196       else
197 	for (i = 0; i < ARRAY_SIZE (tomarkv2); i++)
198 	  switch_to_section (darwin_sections[tomarkv2[i]]);
199       /* Make sure we don't get varasm.c out of sync with us.  */
200       switch_to_section (saved_in_section);
201     }
202   output_section_asm_op (directive);
203 }
204 
205 
206 /* Private flag applied to disable section-anchors in a particular section.  */
207 #define SECTION_NO_ANCHOR SECTION_MACH_DEP
208 
209 
210 /* Implement TARGET_ASM_INIT_SECTIONS.  */
211 
212 void
darwin_init_sections(void)213 darwin_init_sections (void)
214 {
215 #define DEF_SECTION(NAME, FLAGS, DIRECTIVE, OBJC)		\
216   darwin_sections[NAME] =					\
217     get_unnamed_section (FLAGS, (OBJC				\
218 				 ? output_objc_section_asm_op	\
219 				 : output_section_asm_op),	\
220 			 "\t" DIRECTIVE);
221 #include "config/darwin-sections.def"
222 #undef DEF_SECTION
223 
224   readonly_data_section = darwin_sections[const_section];
225   exception_section = darwin_sections[darwin_exception_section];
226   eh_frame_section = darwin_sections[darwin_eh_frame_section];
227 }
228 
229 int
name_needs_quotes(const char * name)230 name_needs_quotes (const char *name)
231 {
232   int c;
233   while ((c = *name++) != '\0')
234     if (! ISIDNUM (c)
235 	  && c != '.' && c != '$' && c != '_' )
236       return 1;
237   return 0;
238 }
239 
240 /* Return true if SYM_REF can be used without an indirection.  */
241 int
machopic_symbol_defined_p(rtx sym_ref)242 machopic_symbol_defined_p (rtx sym_ref)
243 {
244   if (SYMBOL_REF_FLAGS (sym_ref) & MACHO_SYMBOL_FLAG_DEFINED)
245     return true;
246 
247   /* If a symbol references local and is not an extern to this
248      file, then the symbol might be able to declared as defined.  */
249   if (SYMBOL_REF_LOCAL_P (sym_ref) && ! SYMBOL_REF_EXTERNAL_P (sym_ref))
250     {
251       /* If the symbol references a variable and the variable is a
252 	 common symbol, then this symbol is not defined.  */
253       if (SYMBOL_REF_FLAGS (sym_ref) & MACHO_SYMBOL_FLAG_VARIABLE)
254 	{
255 	  tree decl = SYMBOL_REF_DECL (sym_ref);
256 	  if (!decl)
257 	    return true;
258 	  if (DECL_COMMON (decl))
259 	    return false;
260 	}
261       return true;
262     }
263   return false;
264 }
265 
266 /* This module assumes that (const (symbol_ref "foo")) is a legal pic
267    reference, which will not be changed.  */
268 
269 enum machopic_addr_class
machopic_classify_symbol(rtx sym_ref)270 machopic_classify_symbol (rtx sym_ref)
271 {
272   bool function_p;
273 
274   function_p = SYMBOL_REF_FUNCTION_P (sym_ref);
275   if (machopic_symbol_defined_p (sym_ref))
276     return (function_p
277 	    ? MACHOPIC_DEFINED_FUNCTION : MACHOPIC_DEFINED_DATA);
278   else
279     return (function_p
280 	    ? MACHOPIC_UNDEFINED_FUNCTION : MACHOPIC_UNDEFINED_DATA);
281 }
282 
283 #ifndef TARGET_FIX_AND_CONTINUE
284 #define TARGET_FIX_AND_CONTINUE 0
285 #endif
286 
287 /* Indicate when fix-and-continue style code generation is being used
288    and when a reference to data should be indirected so that it can be
289    rebound in a new translation unit to reference the original instance
290    of that data.  Symbol names that are for code generation local to
291    the translation unit are bound to the new translation unit;
292    currently this means symbols that begin with L or _OBJC_;
293    otherwise, we indicate that an indirect reference should be made to
294    permit the runtime to rebind new instances of the translation unit
295    to the original instance of the data.  */
296 
297 static int
indirect_data(rtx sym_ref)298 indirect_data (rtx sym_ref)
299 {
300   int lprefix;
301   const char *name;
302 
303   /* If we aren't generating fix-and-continue code, don't do anything
304      special.  */
305   if (TARGET_FIX_AND_CONTINUE == 0)
306     return 0;
307 
308   /* Otherwise, all symbol except symbols that begin with L or _OBJC_
309      are indirected.  Symbols that begin with L and _OBJC_ are always
310      bound to the current translation unit as they are used for
311      generated local data of the translation unit.  */
312 
313   name = XSTR (sym_ref, 0);
314 
315   lprefix = (((name[0] == '*' || name[0] == '&')
316               && (name[1] == 'L' || (name[1] == '"' && name[2] == 'L')))
317              || (strncmp (name, "_OBJC_", 6) == 0));
318 
319   return ! lprefix;
320 }
321 
322 static int
machopic_data_defined_p(rtx sym_ref)323 machopic_data_defined_p (rtx sym_ref)
324 {
325   if (indirect_data (sym_ref))
326     return 0;
327 
328   switch (machopic_classify_symbol (sym_ref))
329     {
330     case MACHOPIC_DEFINED_DATA:
331     case MACHOPIC_DEFINED_FUNCTION:
332       return 1;
333     default:
334       return 0;
335     }
336 }
337 
338 void
machopic_define_symbol(rtx mem)339 machopic_define_symbol (rtx mem)
340 {
341   rtx sym_ref;
342 
343   gcc_assert (GET_CODE (mem) == MEM);
344   sym_ref = XEXP (mem, 0);
345   SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_DEFINED;
346 }
347 
348 /* Return either ORIG or:
349 
350      (const:P (unspec:P [ORIG] UNSPEC_MACHOPIC_OFFSET))
351 
352    depending on MACHO_DYNAMIC_NO_PIC_P.  */
353 rtx
machopic_gen_offset(rtx orig)354 machopic_gen_offset (rtx orig)
355 {
356   if (MACHO_DYNAMIC_NO_PIC_P)
357     return orig;
358   else
359     {
360       /* Play games to avoid marking the function as needing pic if we
361 	 are being called as part of the cost-estimation process.  */
362       if (current_ir_type () != IR_GIMPLE || currently_expanding_to_rtl)
363 	crtl->uses_pic_offset_table = 1;
364       orig = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, orig),
365 			     UNSPEC_MACHOPIC_OFFSET);
366       return gen_rtx_CONST (Pmode, orig);
367     }
368 }
369 
370 static GTY(()) const char * function_base_func_name;
371 static GTY(()) int current_pic_label_num;
372 static GTY(()) int emitted_pic_label_num;
373 
374 static void
update_pic_label_number_if_needed(void)375 update_pic_label_number_if_needed (void)
376 {
377   const char *current_name;
378 
379   /* When we are generating _get_pc thunks within stubs, there is no current
380      function.  */
381   if (current_function_decl)
382     {
383       current_name =
384 	IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (current_function_decl));
385       if (function_base_func_name != current_name)
386 	{
387 	  ++current_pic_label_num;
388 	  function_base_func_name = current_name;
389 	}
390     }
391   else
392     {
393       ++current_pic_label_num;
394       function_base_func_name = "L_machopic_stub_dummy";
395     }
396 }
397 
398 void
machopic_output_function_base_name(FILE * file)399 machopic_output_function_base_name (FILE *file)
400 {
401   /* If dynamic-no-pic is on, we should not get here.  */
402   gcc_assert (!MACHO_DYNAMIC_NO_PIC_P);
403 
404   update_pic_label_number_if_needed ();
405   fprintf (file, "L%d$pb", current_pic_label_num);
406 }
407 
408 bool
machopic_should_output_picbase_label(void)409 machopic_should_output_picbase_label (void)
410 {
411   update_pic_label_number_if_needed ();
412 
413   if (current_pic_label_num == emitted_pic_label_num)
414     return false;
415 
416   emitted_pic_label_num = current_pic_label_num;
417   return true;
418 }
419 
420 /* The suffix attached to non-lazy pointer symbols.  */
421 #define NON_LAZY_POINTER_SUFFIX "$non_lazy_ptr"
422 /* The suffix attached to stub symbols.  */
423 #define STUB_SUFFIX "$stub"
424 
425 typedef struct GTY (()) machopic_indirection
426 {
427   /* The SYMBOL_REF for the entity referenced.  */
428   rtx symbol;
429   /* The name of the stub or non-lazy pointer.  */
430   const char * ptr_name;
431   /* True iff this entry is for a stub (as opposed to a non-lazy
432      pointer).  */
433   bool stub_p;
434   /* True iff this stub or pointer pointer has been referenced.  */
435   bool used;
436 } machopic_indirection;
437 
438 /* A table mapping stub names and non-lazy pointer names to
439    SYMBOL_REFs for the stubbed-to and pointed-to entities.  */
440 
441 static GTY ((param_is (struct machopic_indirection))) htab_t
442   machopic_indirections;
443 
444 /* Return a hash value for a SLOT in the indirections hash table.  */
445 
446 static hashval_t
machopic_indirection_hash(const void * slot)447 machopic_indirection_hash (const void *slot)
448 {
449   const machopic_indirection *p = (const machopic_indirection *) slot;
450   return htab_hash_string (p->ptr_name);
451 }
452 
453 /* Returns true if the KEY is the same as that associated with
454    SLOT.  */
455 
456 static int
machopic_indirection_eq(const void * slot,const void * key)457 machopic_indirection_eq (const void *slot, const void *key)
458 {
459   return strcmp (((const machopic_indirection *) slot)->ptr_name,
460 		 (const char *) key) == 0;
461 }
462 
463 /* Return the name of the non-lazy pointer (if STUB_P is false) or
464    stub (if STUB_B is true) corresponding to the given name.  */
465 
466 const char *
machopic_indirection_name(rtx sym_ref,bool stub_p)467 machopic_indirection_name (rtx sym_ref, bool stub_p)
468 {
469   char *buffer;
470   const char *name = XSTR (sym_ref, 0);
471   size_t namelen = strlen (name);
472   machopic_indirection *p;
473   void ** slot;
474   bool needs_quotes;
475   const char *suffix;
476   const char *prefix = user_label_prefix;
477   const char *quote = "";
478   tree id;
479 
480   id = maybe_get_identifier (name);
481   if (id)
482     {
483       tree id_orig = id;
484 
485       while (IDENTIFIER_TRANSPARENT_ALIAS (id))
486 	id = TREE_CHAIN (id);
487       if (id != id_orig)
488 	{
489 	  name = IDENTIFIER_POINTER (id);
490 	  namelen = strlen (name);
491 	}
492     }
493 
494   if (name[0] == '*')
495     {
496       prefix = "";
497       ++name;
498       --namelen;
499     }
500 
501   needs_quotes = name_needs_quotes (name);
502   if (needs_quotes)
503     {
504       quote = "\"";
505     }
506 
507   if (stub_p)
508     suffix = STUB_SUFFIX;
509   else
510     suffix = NON_LAZY_POINTER_SUFFIX;
511 
512   buffer = XALLOCAVEC (char, strlen ("&L")
513 		   + strlen (prefix)
514 		   + namelen
515 		   + strlen (suffix)
516 		   + 2 * strlen (quote)
517 		   + 1 /* '\0' */);
518 
519   /* Construct the name of the non-lazy pointer or stub.  */
520   sprintf (buffer, "&%sL%s%s%s%s", quote, prefix, name, suffix, quote);
521 
522   if (!machopic_indirections)
523     machopic_indirections = htab_create_ggc (37,
524 					     machopic_indirection_hash,
525 					     machopic_indirection_eq,
526 					     /*htab_del=*/NULL);
527 
528   slot = htab_find_slot_with_hash (machopic_indirections, buffer,
529 				   htab_hash_string (buffer), INSERT);
530   if (*slot)
531     {
532       p = (machopic_indirection *) *slot;
533     }
534   else
535     {
536       p = ggc_alloc_machopic_indirection ();
537       p->symbol = sym_ref;
538       p->ptr_name = xstrdup (buffer);
539       p->stub_p = stub_p;
540       p->used = false;
541       *slot = p;
542     }
543 
544   return p->ptr_name;
545 }
546 
547 /* Return the name of the stub for the mcount function.  */
548 
549 const char*
machopic_mcount_stub_name(void)550 machopic_mcount_stub_name (void)
551 {
552   rtx symbol = gen_rtx_SYMBOL_REF (Pmode, "*mcount");
553   return machopic_indirection_name (symbol, /*stub_p=*/true);
554 }
555 
556 /* If NAME is the name of a stub or a non-lazy pointer , mark the stub
557    or non-lazy pointer as used -- and mark the object to which the
558    pointer/stub refers as used as well, since the pointer/stub will
559    emit a reference to it.  */
560 
561 void
machopic_validate_stub_or_non_lazy_ptr(const char * name)562 machopic_validate_stub_or_non_lazy_ptr (const char *name)
563 {
564   machopic_indirection *p;
565 
566   p = ((machopic_indirection *)
567        (htab_find_with_hash (machopic_indirections, name,
568 			     htab_hash_string (name))));
569   if (p && ! p->used)
570     {
571       const char *real_name;
572       tree id;
573 
574       p->used = true;
575 
576       /* Do what output_addr_const will do when we actually call it.  */
577       if (SYMBOL_REF_DECL (p->symbol))
578 	mark_decl_referenced (SYMBOL_REF_DECL (p->symbol));
579 
580       real_name = targetm.strip_name_encoding (XSTR (p->symbol, 0));
581 
582       id = maybe_get_identifier (real_name);
583       if (id)
584 	mark_referenced (id);
585     }
586 }
587 
588 /* Transform ORIG, which may be any data source, to the corresponding
589    source using indirections.  */
590 
591 rtx
machopic_indirect_data_reference(rtx orig,rtx reg)592 machopic_indirect_data_reference (rtx orig, rtx reg)
593 {
594   rtx ptr_ref = orig;
595 
596   if (! MACHOPIC_INDIRECT)
597     return orig;
598 
599   if (GET_CODE (orig) == SYMBOL_REF)
600     {
601       int defined = machopic_data_defined_p (orig);
602 
603       if (defined && MACHO_DYNAMIC_NO_PIC_P)
604 	{
605 	  if (DARWIN_PPC)
606 	    {
607 	  /* Create a new register for CSE opportunities.  */
608 	  rtx hi_reg = (!can_create_pseudo_p () ? reg : gen_reg_rtx (Pmode));
609  	  emit_insn (gen_macho_high (hi_reg, orig));
610  	  emit_insn (gen_macho_low (reg, hi_reg, orig));
611 	      return reg;
612  	    }
613 	  else if (DARWIN_X86)
614 	    return orig;
615 	  else
616 	   /* some other cpu -- writeme!  */
617 	   gcc_unreachable ();
618 	}
619       else if (defined)
620 	{
621 	  rtx offset = NULL;
622 	  if (DARWIN_PPC || HAVE_lo_sum)
623 	    offset = machopic_gen_offset (orig);
624 
625 	  if (DARWIN_PPC)
626 	    {
627 	  rtx hi_sum_reg = (!can_create_pseudo_p ()
628 			    ? reg
629 			    : gen_reg_rtx (Pmode));
630 
631 	  gcc_assert (reg);
632 
633 	  emit_insn (gen_rtx_SET (Pmode, hi_sum_reg,
634 			      gen_rtx_PLUS (Pmode, pic_offset_table_rtx,
635 				       gen_rtx_HIGH (Pmode, offset))));
636 	  emit_insn (gen_rtx_SET (Pmode, reg,
637 				  gen_rtx_LO_SUM (Pmode, hi_sum_reg,
638 						  copy_rtx (offset))));
639 
640 	  orig = reg;
641 	    }
642 	  else if (HAVE_lo_sum)
643 	    {
644 	  gcc_assert (reg);
645 
646 	  emit_insn (gen_rtx_SET (VOIDmode, reg,
647 				  gen_rtx_HIGH (Pmode, offset)));
648 	  emit_insn (gen_rtx_SET (VOIDmode, reg,
649 				  gen_rtx_LO_SUM (Pmode, reg,
650 						  copy_rtx (offset))));
651 	  emit_use (pic_offset_table_rtx);
652 
653 	  orig = gen_rtx_PLUS (Pmode, pic_offset_table_rtx, reg);
654 	    }
655 	  return orig;
656 	}
657 
658       ptr_ref = (gen_rtx_SYMBOL_REF
659 		 (Pmode,
660 		  machopic_indirection_name (orig, /*stub_p=*/false)));
661 
662       SYMBOL_REF_DATA (ptr_ref) = SYMBOL_REF_DATA (orig);
663 
664       ptr_ref = gen_const_mem (Pmode, ptr_ref);
665       machopic_define_symbol (ptr_ref);
666 
667       if (DARWIN_X86
668           && reg
669           && MACHO_DYNAMIC_NO_PIC_P)
670 	{
671 	    emit_insn (gen_rtx_SET (Pmode, reg, ptr_ref));
672 	    ptr_ref = reg;
673 	}
674 
675       return ptr_ref;
676     }
677   else if (GET_CODE (orig) == CONST)
678     {
679       /* If "(const (plus ...", walk the PLUS and return that result.
680 	 PLUS processing (below) will restore the "(const ..." if
681 	 appropriate.  */
682       if (GET_CODE (XEXP (orig, 0)) == PLUS)
683 	return machopic_indirect_data_reference (XEXP (orig, 0), reg);
684       else
685 	return orig;
686     }
687   else if (GET_CODE (orig) == MEM)
688     {
689       XEXP (ptr_ref, 0) =
690 		machopic_indirect_data_reference (XEXP (orig, 0), reg);
691       return ptr_ref;
692     }
693   else if (GET_CODE (orig) == PLUS)
694     {
695       rtx base, result;
696       /* When the target is i386, this code prevents crashes due to the
697 	compiler's ignorance on how to move the PIC base register to
698 	other registers.  (The reload phase sometimes introduces such
699 	insns.)  */
700       if (GET_CODE (XEXP (orig, 0)) == REG
701 	   && REGNO (XEXP (orig, 0)) == PIC_OFFSET_TABLE_REGNUM
702 	   /* Prevent the same register from being erroneously used
703 	      as both the base and index registers.  */
704 	   && (DARWIN_X86 && (GET_CODE (XEXP (orig, 1)) == CONST))
705 	   && reg)
706 	{
707 	  emit_move_insn (reg, XEXP (orig, 0));
708 	  XEXP (ptr_ref, 0) = reg;
709 	  return ptr_ref;
710 	}
711 
712       /* Legitimize both operands of the PLUS.  */
713       base = machopic_indirect_data_reference (XEXP (orig, 0), reg);
714       orig = machopic_indirect_data_reference (XEXP (orig, 1),
715 					       (base == reg ? 0 : reg));
716       if (MACHOPIC_INDIRECT && (GET_CODE (orig) == CONST_INT))
717 	result = plus_constant (Pmode, base, INTVAL (orig));
718       else
719 	result = gen_rtx_PLUS (Pmode, base, orig);
720 
721       if (MACHOPIC_JUST_INDIRECT && GET_CODE (base) == MEM)
722 	{
723 	  if (reg)
724 	    {
725 	      emit_move_insn (reg, result);
726 	      result = reg;
727 	    }
728 	  else
729 	    {
730 	      result = force_reg (GET_MODE (result), result);
731 	    }
732 	}
733 
734       return result;
735     }
736   return ptr_ref;
737 }
738 
739 /* Transform TARGET (a MEM), which is a function call target, to the
740    corresponding symbol_stub if necessary.  Return a new MEM.  */
741 
742 rtx
machopic_indirect_call_target(rtx target)743 machopic_indirect_call_target (rtx target)
744 {
745   if (! darwin_emit_branch_islands)
746     return target;
747 
748   if (GET_CODE (target) != MEM)
749     return target;
750 
751   if (MACHOPIC_INDIRECT
752       && GET_CODE (XEXP (target, 0)) == SYMBOL_REF
753       && !(SYMBOL_REF_FLAGS (XEXP (target, 0))
754 	   & MACHO_SYMBOL_FLAG_DEFINED))
755     {
756       rtx sym_ref = XEXP (target, 0);
757       const char *stub_name = machopic_indirection_name (sym_ref,
758 							 /*stub_p=*/true);
759       enum machine_mode mode = GET_MODE (sym_ref);
760 
761       XEXP (target, 0) = gen_rtx_SYMBOL_REF (mode, stub_name);
762       SYMBOL_REF_DATA (XEXP (target, 0)) = SYMBOL_REF_DATA (sym_ref);
763       MEM_READONLY_P (target) = 1;
764       MEM_NOTRAP_P (target) = 1;
765     }
766 
767   return target;
768 }
769 
770 rtx
machopic_legitimize_pic_address(rtx orig,enum machine_mode mode,rtx reg)771 machopic_legitimize_pic_address (rtx orig, enum machine_mode mode, rtx reg)
772 {
773   rtx pic_ref = orig;
774 
775   if (! MACHOPIC_INDIRECT)
776     return orig;
777 
778   /* First handle a simple SYMBOL_REF or LABEL_REF */
779   if (GET_CODE (orig) == LABEL_REF
780       || (GET_CODE (orig) == SYMBOL_REF
781 	  ))
782     {
783       /* addr(foo) = &func+(foo-func) */
784       orig = machopic_indirect_data_reference (orig, reg);
785 
786       if (GET_CODE (orig) == PLUS
787 	  && GET_CODE (XEXP (orig, 0)) == REG)
788 	{
789 	  if (reg == 0)
790 	    return force_reg (mode, orig);
791 
792 	  emit_move_insn (reg, orig);
793 	  return reg;
794 	}
795 
796       if (GET_CODE (orig) == MEM)
797 	{
798 	  if (reg == 0)
799 	    {
800 	      gcc_assert (!reload_in_progress);
801 	      reg = gen_reg_rtx (Pmode);
802 	    }
803 
804 #if HAVE_lo_sum
805 	  if (MACHO_DYNAMIC_NO_PIC_P
806 	      && (GET_CODE (XEXP (orig, 0)) == SYMBOL_REF
807 		  || GET_CODE (XEXP (orig, 0)) == LABEL_REF))
808 	    {
809 #if defined (TARGET_TOC)	/* ppc  */
810 	      rtx temp_reg = (!can_create_pseudo_p ()
811 			      ? reg :
812 			      gen_reg_rtx (Pmode));
813 	      rtx asym = XEXP (orig, 0);
814 	      rtx mem;
815 
816 	      emit_insn (gen_macho_high (temp_reg, asym));
817 	      mem = gen_const_mem (GET_MODE (orig),
818 				   gen_rtx_LO_SUM (Pmode, temp_reg,
819 						   copy_rtx (asym)));
820 	      emit_insn (gen_rtx_SET (VOIDmode, reg, mem));
821 #else
822 	      /* Some other CPU -- WriteMe! but right now there are no other
823 		 platforms that can use dynamic-no-pic  */
824 	      gcc_unreachable ();
825 #endif
826 	      pic_ref = reg;
827 	    }
828 	  else
829 	  if (GET_CODE (XEXP (orig, 0)) == SYMBOL_REF
830 	      || GET_CODE (XEXP (orig, 0)) == LABEL_REF)
831 	    {
832 	      rtx offset = machopic_gen_offset (XEXP (orig, 0));
833 #if defined (TARGET_TOC) /* i.e., PowerPC */
834 	      /* Generating a new reg may expose opportunities for
835 		 common subexpression elimination.  */
836               rtx hi_sum_reg = (!can_create_pseudo_p ()
837 				? reg
838 				: gen_reg_rtx (Pmode));
839 	      rtx mem;
840 	      rtx insn;
841 	      rtx sum;
842 
843 	      sum = gen_rtx_HIGH (Pmode, offset);
844 	      if (! MACHO_DYNAMIC_NO_PIC_P)
845 		sum = gen_rtx_PLUS (Pmode, pic_offset_table_rtx, sum);
846 
847 	      emit_insn (gen_rtx_SET (Pmode, hi_sum_reg, sum));
848 
849 	      mem = gen_const_mem (GET_MODE (orig),
850 				  gen_rtx_LO_SUM (Pmode,
851 						  hi_sum_reg,
852 						  copy_rtx (offset)));
853 	      insn = emit_insn (gen_rtx_SET (VOIDmode, reg, mem));
854 	      set_unique_reg_note (insn, REG_EQUAL, pic_ref);
855 
856 	      pic_ref = reg;
857 #else
858 	      emit_use (gen_rtx_REG (Pmode, PIC_OFFSET_TABLE_REGNUM));
859 
860 	      emit_insn (gen_rtx_SET (VOIDmode, reg,
861 				      gen_rtx_HIGH (Pmode,
862 						    gen_rtx_CONST (Pmode,
863 								   offset))));
864 	      emit_insn (gen_rtx_SET (VOIDmode, reg,
865 				  gen_rtx_LO_SUM (Pmode, reg,
866 					   gen_rtx_CONST (Pmode,
867 						   	  copy_rtx (offset)))));
868 	      pic_ref = gen_rtx_PLUS (Pmode,
869 				      pic_offset_table_rtx, reg);
870 #endif
871 	    }
872 	  else
873 #endif  /* HAVE_lo_sum */
874 	    {
875 	      rtx pic = pic_offset_table_rtx;
876 	      if (GET_CODE (pic) != REG)
877 		{
878 		  emit_move_insn (reg, pic);
879 		  pic = reg;
880 		}
881 #if 0
882 	      emit_use (gen_rtx_REG (Pmode, PIC_OFFSET_TABLE_REGNUM));
883 #endif
884 
885 	      if (reload_in_progress)
886 		df_set_regs_ever_live (REGNO (pic), true);
887 	      pic_ref = gen_rtx_PLUS (Pmode, pic,
888 				      machopic_gen_offset (XEXP (orig, 0)));
889 	    }
890 
891 #if !defined (TARGET_TOC)
892 	  emit_move_insn (reg, pic_ref);
893 	  pic_ref = gen_const_mem (GET_MODE (orig), reg);
894 #endif
895 	}
896       else
897 	{
898 
899 #if HAVE_lo_sum
900 	  if (GET_CODE (orig) == SYMBOL_REF
901 	      || GET_CODE (orig) == LABEL_REF)
902 	    {
903 	      rtx offset = machopic_gen_offset (orig);
904 #if defined (TARGET_TOC) /* i.e., PowerPC */
905               rtx hi_sum_reg;
906 
907 	      if (reg == 0)
908 		{
909 		  gcc_assert (!reload_in_progress);
910 		  reg = gen_reg_rtx (Pmode);
911 		}
912 
913 	      hi_sum_reg = reg;
914 
915 	      emit_insn (gen_rtx_SET (Pmode, hi_sum_reg,
916 				      (MACHO_DYNAMIC_NO_PIC_P)
917 				      ? gen_rtx_HIGH (Pmode, offset)
918 				      : gen_rtx_PLUS (Pmode,
919 						      pic_offset_table_rtx,
920 						      gen_rtx_HIGH (Pmode,
921 								    offset))));
922 	      emit_insn (gen_rtx_SET (VOIDmode, reg,
923 				      gen_rtx_LO_SUM (Pmode,
924 						      hi_sum_reg,
925 						      copy_rtx (offset))));
926 	      pic_ref = reg;
927 #else
928 	      emit_insn (gen_rtx_SET (VOIDmode, reg,
929 				      gen_rtx_HIGH (Pmode, offset)));
930 	      emit_insn (gen_rtx_SET (VOIDmode, reg,
931 				      gen_rtx_LO_SUM (Pmode, reg,
932 						      copy_rtx (offset))));
933 	      pic_ref = gen_rtx_PLUS (Pmode,
934 				      pic_offset_table_rtx, reg);
935 #endif
936 	    }
937 	  else
938 #endif  /*  HAVE_lo_sum  */
939 	    {
940 	      if (REG_P (orig)
941 	          || GET_CODE (orig) == SUBREG)
942 		{
943 		  return orig;
944 		}
945 	      else
946 		{
947 		  rtx pic = pic_offset_table_rtx;
948 		  if (GET_CODE (pic) != REG)
949 		    {
950 		      emit_move_insn (reg, pic);
951 		      pic = reg;
952 		    }
953 #if 0
954 		  emit_use (pic_offset_table_rtx);
955 #endif
956 		  if (reload_in_progress)
957 		    df_set_regs_ever_live (REGNO (pic), true);
958 		  pic_ref = gen_rtx_PLUS (Pmode,
959 					  pic,
960 					  machopic_gen_offset (orig));
961 		}
962 	    }
963 	}
964 
965       if (GET_CODE (pic_ref) != REG)
966         {
967           if (reg != 0)
968             {
969               emit_move_insn (reg, pic_ref);
970               return reg;
971             }
972           else
973             {
974               return force_reg (mode, pic_ref);
975             }
976         }
977       else
978         {
979           return pic_ref;
980         }
981     }
982 
983   else if (GET_CODE (orig) == SYMBOL_REF)
984     return orig;
985 
986   else if (GET_CODE (orig) == PLUS
987 	   && (GET_CODE (XEXP (orig, 0)) == MEM
988 	       || GET_CODE (XEXP (orig, 0)) == SYMBOL_REF
989 	       || GET_CODE (XEXP (orig, 0)) == LABEL_REF)
990 	   && XEXP (orig, 0) != pic_offset_table_rtx
991 	   && GET_CODE (XEXP (orig, 1)) != REG)
992 
993     {
994       rtx base;
995       int is_complex = (GET_CODE (XEXP (orig, 0)) == MEM);
996 
997       base = machopic_legitimize_pic_address (XEXP (orig, 0), Pmode, reg);
998       orig = machopic_legitimize_pic_address (XEXP (orig, 1),
999 					      Pmode, (base == reg ? 0 : reg));
1000       if (GET_CODE (orig) == CONST_INT)
1001 	{
1002 	  pic_ref = plus_constant (Pmode, base, INTVAL (orig));
1003 	  is_complex = 1;
1004 	}
1005       else
1006 	pic_ref = gen_rtx_PLUS (Pmode, base, orig);
1007 
1008       if (reg && is_complex)
1009 	{
1010 	  emit_move_insn (reg, pic_ref);
1011 	  pic_ref = reg;
1012 	}
1013       /* Likewise, should we set special REG_NOTEs here?  */
1014     }
1015 
1016   else if (GET_CODE (orig) == CONST)
1017     {
1018       return machopic_legitimize_pic_address (XEXP (orig, 0), Pmode, reg);
1019     }
1020 
1021   else if (GET_CODE (orig) == MEM
1022 	   && GET_CODE (XEXP (orig, 0)) == SYMBOL_REF)
1023     {
1024       rtx addr = machopic_legitimize_pic_address (XEXP (orig, 0), Pmode, reg);
1025       addr = replace_equiv_address (orig, addr);
1026       emit_move_insn (reg, addr);
1027       pic_ref = reg;
1028     }
1029 
1030   return pic_ref;
1031 }
1032 
1033 /* Output the stub or non-lazy pointer in *SLOT, if it has been used.
1034    DATA is the FILE* for assembly output.  Called from
1035    htab_traverse.  */
1036 
1037 static int
machopic_output_indirection(void ** slot,void * data)1038 machopic_output_indirection (void **slot, void *data)
1039 {
1040   machopic_indirection *p = *((machopic_indirection **) slot);
1041   FILE *asm_out_file = (FILE *) data;
1042   rtx symbol;
1043   const char *sym_name;
1044   const char *ptr_name;
1045 
1046   if (!p->used)
1047     return 1;
1048 
1049   symbol = p->symbol;
1050   sym_name = XSTR (symbol, 0);
1051   ptr_name = p->ptr_name;
1052 
1053   if (p->stub_p)
1054     {
1055       char *sym;
1056       char *stub;
1057       tree id;
1058 
1059       id = maybe_get_identifier (sym_name);
1060       if (id)
1061 	{
1062 	  tree id_orig = id;
1063 
1064 	  while (IDENTIFIER_TRANSPARENT_ALIAS (id))
1065 	    id = TREE_CHAIN (id);
1066 	  if (id != id_orig)
1067 	    sym_name = IDENTIFIER_POINTER (id);
1068 	}
1069 
1070       sym = XALLOCAVEC (char, strlen (sym_name) + 2);
1071       if (sym_name[0] == '*' || sym_name[0] == '&')
1072 	strcpy (sym, sym_name + 1);
1073       else if (sym_name[0] == '-' || sym_name[0] == '+')
1074 	strcpy (sym, sym_name);
1075       else
1076 	sprintf (sym, "%s%s", user_label_prefix, sym_name);
1077 
1078       stub = XALLOCAVEC (char, strlen (ptr_name) + 2);
1079       if (ptr_name[0] == '*' || ptr_name[0] == '&')
1080 	strcpy (stub, ptr_name + 1);
1081       else
1082 	sprintf (stub, "%s%s", user_label_prefix, ptr_name);
1083 
1084       machopic_output_stub (asm_out_file, sym, stub);
1085     }
1086   else if (! indirect_data (symbol)
1087 	   && (machopic_symbol_defined_p (symbol)
1088 	       || SYMBOL_REF_LOCAL_P (symbol)))
1089     {
1090       switch_to_section (data_section);
1091       assemble_align (GET_MODE_ALIGNMENT (Pmode));
1092       assemble_label (asm_out_file, ptr_name);
1093       assemble_integer (gen_rtx_SYMBOL_REF (Pmode, sym_name),
1094 			GET_MODE_SIZE (Pmode),
1095 			GET_MODE_ALIGNMENT (Pmode), 1);
1096     }
1097   else
1098     {
1099       rtx init = const0_rtx;
1100 
1101       switch_to_section (darwin_sections[machopic_nl_symbol_ptr_section]);
1102 
1103       /* Mach-O symbols are passed around in code through indirect
1104 	 references and the original symbol_ref hasn't passed through
1105 	 the generic handling and reference-catching in
1106 	 output_operand, so we need to manually mark weak references
1107 	 as such.  */
1108       if (SYMBOL_REF_WEAK (symbol))
1109 	{
1110 	  tree decl = SYMBOL_REF_DECL (symbol);
1111 	  gcc_assert (DECL_P (decl));
1112 
1113 	  if (decl != NULL_TREE
1114 	      && DECL_EXTERNAL (decl) && TREE_PUBLIC (decl)
1115 	      /* Handle only actual external-only definitions, not
1116 		 e.g. extern inline code or variables for which
1117 		 storage has been allocated.  */
1118 	      && !TREE_STATIC (decl))
1119 	    {
1120 	      fputs ("\t.weak_reference ", asm_out_file);
1121 	      assemble_name (asm_out_file, sym_name);
1122 	      fputc ('\n', asm_out_file);
1123 	    }
1124 	}
1125 
1126       assemble_name (asm_out_file, ptr_name);
1127       fprintf (asm_out_file, ":\n");
1128 
1129       fprintf (asm_out_file, "\t.indirect_symbol ");
1130       assemble_name (asm_out_file, sym_name);
1131       fprintf (asm_out_file, "\n");
1132 
1133       /* Variables that are marked with MACHO_SYMBOL_STATIC need to
1134 	 have their symbol name instead of 0 in the second entry of
1135 	 the non-lazy symbol pointer data structure when they are
1136 	 defined.  This allows the runtime to rebind newer instances
1137 	 of the translation unit with the original instance of the
1138 	 symbol.  */
1139 
1140       if ((SYMBOL_REF_FLAGS (symbol) & MACHO_SYMBOL_STATIC)
1141 	  && machopic_symbol_defined_p (symbol))
1142 	init = gen_rtx_SYMBOL_REF (Pmode, sym_name);
1143 
1144       assemble_integer (init, GET_MODE_SIZE (Pmode),
1145 			GET_MODE_ALIGNMENT (Pmode), 1);
1146     }
1147 
1148   return 1;
1149 }
1150 
1151 void
machopic_finish(FILE * asm_out_file)1152 machopic_finish (FILE *asm_out_file)
1153 {
1154   if (machopic_indirections)
1155     htab_traverse_noresize (machopic_indirections,
1156 			    machopic_output_indirection,
1157 			    asm_out_file);
1158 }
1159 
1160 int
machopic_operand_p(rtx op)1161 machopic_operand_p (rtx op)
1162 {
1163   if (MACHOPIC_JUST_INDIRECT)
1164     return (GET_CODE (op) == SYMBOL_REF
1165 	    && machopic_symbol_defined_p (op));
1166   else
1167     return (GET_CODE (op) == CONST
1168 	    && GET_CODE (XEXP (op, 0)) == UNSPEC
1169 	    && XINT (XEXP (op, 0), 1) == UNSPEC_MACHOPIC_OFFSET);
1170 }
1171 
1172 /* This function records whether a given name corresponds to a defined
1173    or undefined function or variable, for machopic_classify_ident to
1174    use later.  */
1175 
1176 void
darwin_encode_section_info(tree decl,rtx rtl,int first ATTRIBUTE_UNUSED)1177 darwin_encode_section_info (tree decl, rtx rtl, int first ATTRIBUTE_UNUSED)
1178 {
1179   rtx sym_ref;
1180 
1181   /* Do the standard encoding things first.  */
1182   default_encode_section_info (decl, rtl, first);
1183 
1184   if (TREE_CODE (decl) != FUNCTION_DECL && TREE_CODE (decl) != VAR_DECL)
1185     return;
1186 
1187   sym_ref = XEXP (rtl, 0);
1188   if (TREE_CODE (decl) == VAR_DECL)
1189     SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_VARIABLE;
1190 
1191   if (!DECL_EXTERNAL (decl)
1192       && (!TREE_PUBLIC (decl) || !DECL_WEAK (decl))
1193       && ! lookup_attribute ("weakref", DECL_ATTRIBUTES (decl))
1194       && ((TREE_STATIC (decl)
1195 	   && (!DECL_COMMON (decl) || !TREE_PUBLIC (decl)))
1196 	  || (!DECL_COMMON (decl) && DECL_INITIAL (decl)
1197 	      && DECL_INITIAL (decl) != error_mark_node)))
1198     SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_FLAG_DEFINED;
1199 
1200   if (! TREE_PUBLIC (decl))
1201     SYMBOL_REF_FLAGS (sym_ref) |= MACHO_SYMBOL_STATIC;
1202 }
1203 
1204 void
darwin_mark_decl_preserved(const char * name)1205 darwin_mark_decl_preserved (const char *name)
1206 {
1207   fprintf (asm_out_file, "\t.no_dead_strip ");
1208   assemble_name (asm_out_file, name);
1209   fputc ('\n', asm_out_file);
1210 }
1211 
1212 static section *
darwin_rodata_section(int weak,bool zsize)1213 darwin_rodata_section (int weak, bool zsize)
1214 {
1215   return (weak
1216 	  ? darwin_sections[const_coal_section]
1217 	  : (zsize ? darwin_sections[zobj_const_section]
1218 		   : darwin_sections[const_section]));
1219 }
1220 
1221 static section *
darwin_mergeable_string_section(tree exp,unsigned HOST_WIDE_INT align)1222 darwin_mergeable_string_section (tree exp,
1223 				 unsigned HOST_WIDE_INT align)
1224 {
1225   /* Darwin's ld expects to see non-writable string literals in the .cstring
1226      section.  Later versions of ld check and complain when CFStrings are
1227      enabled.  Therefore we shall force the strings into .cstring since we
1228      don't support writable ones anyway.  */
1229   if ((darwin_constant_cfstrings || flag_merge_constants)
1230       && TREE_CODE (exp) == STRING_CST
1231       && TREE_CODE (TREE_TYPE (exp)) == ARRAY_TYPE
1232       && align <= 256
1233       && (int_size_in_bytes (TREE_TYPE (exp))
1234 	  == TREE_STRING_LENGTH (exp))
1235       && ((size_t) TREE_STRING_LENGTH (exp)
1236 	  == strlen (TREE_STRING_POINTER (exp)) + 1))
1237     return darwin_sections[cstring_section];
1238 
1239   if (DARWIN_SECTION_ANCHORS && flag_section_anchors
1240       && TREE_CODE (exp) == STRING_CST
1241       && TREE_STRING_LENGTH (exp) == 0)
1242     return darwin_sections[zobj_const_section];
1243 
1244   return readonly_data_section;
1245 }
1246 
1247 #ifndef HAVE_GAS_LITERAL16
1248 #define HAVE_GAS_LITERAL16 0
1249 #endif
1250 
1251 static section *
darwin_mergeable_constant_section(tree exp,unsigned HOST_WIDE_INT align,bool zsize)1252 darwin_mergeable_constant_section (tree exp,
1253 				   unsigned HOST_WIDE_INT align,
1254 				   bool zsize)
1255 {
1256   enum machine_mode mode = DECL_MODE (exp);
1257   unsigned int modesize = GET_MODE_BITSIZE (mode);
1258 
1259   if (DARWIN_SECTION_ANCHORS
1260       && flag_section_anchors
1261       && zsize)
1262     return darwin_sections[zobj_const_section];
1263 
1264   if (flag_merge_constants
1265       && mode != VOIDmode
1266       && mode != BLKmode
1267       && modesize <= align
1268       && align >= 8
1269       && align <= 256
1270       && (align & (align -1)) == 0)
1271     {
1272       tree size = TYPE_SIZE_UNIT (TREE_TYPE (exp));
1273 
1274       if (TREE_CODE (size) == INTEGER_CST
1275 	  && TREE_INT_CST_LOW (size) == 4
1276 	  && TREE_INT_CST_HIGH (size) == 0)
1277         return darwin_sections[literal4_section];
1278       else if (TREE_CODE (size) == INTEGER_CST
1279 	       && TREE_INT_CST_LOW (size) == 8
1280 	       && TREE_INT_CST_HIGH (size) == 0)
1281         return darwin_sections[literal8_section];
1282       else if (HAVE_GAS_LITERAL16
1283 	       && TARGET_64BIT
1284                && TREE_CODE (size) == INTEGER_CST
1285                && TREE_INT_CST_LOW (size) == 16
1286                && TREE_INT_CST_HIGH (size) == 0)
1287         return darwin_sections[literal16_section];
1288       else
1289         return readonly_data_section;
1290     }
1291 
1292   return readonly_data_section;
1293 }
1294 
1295 section *
darwin_tm_clone_table_section(void)1296 darwin_tm_clone_table_section (void)
1297 {
1298   return get_named_section (NULL,
1299 			    "__DATA,__tm_clone_table,regular,no_dead_strip",
1300 			    3);
1301 }
1302 
1303 int
machopic_reloc_rw_mask(void)1304 machopic_reloc_rw_mask (void)
1305 {
1306   return MACHOPIC_INDIRECT ? 3 : 0;
1307 }
1308 
1309 /* We have to deal with ObjC/C++ metadata section placement in the common
1310    code, since it will also be called from LTO.
1311 
1312    Return metadata attributes, if present (searching for ABI=2 first)
1313    Return NULL_TREE if no such attributes are found.  */
1314 
1315 static tree
is_objc_metadata(tree decl)1316 is_objc_metadata (tree decl)
1317 {
1318   if (DECL_P (decl)
1319       && (TREE_CODE (decl) == VAR_DECL || TREE_CODE (decl) == CONST_DECL)
1320       && DECL_ATTRIBUTES (decl))
1321     {
1322       tree meta = lookup_attribute ("OBJC2META", DECL_ATTRIBUTES (decl));
1323       if (meta)
1324 	return meta;
1325       meta = lookup_attribute ("OBJC1META", DECL_ATTRIBUTES (decl));
1326       if (meta)
1327 	return meta;
1328     }
1329   return NULL_TREE;
1330 }
1331 
1332 static int classes_seen;
1333 static int objc_metadata_seen;
1334 
1335 /* Return the section required for Objective C ABI 2 metadata.  */
1336 static section *
darwin_objc2_section(tree decl ATTRIBUTE_UNUSED,tree meta,section * base)1337 darwin_objc2_section (tree decl ATTRIBUTE_UNUSED, tree meta, section * base)
1338 {
1339   const char *p;
1340   tree ident = TREE_VALUE (meta);
1341   gcc_assert (TREE_CODE (ident) == IDENTIFIER_NODE);
1342   p = IDENTIFIER_POINTER (ident);
1343 
1344   gcc_checking_assert (flag_next_runtime == 1 && flag_objc_abi == 2);
1345 
1346   objc_metadata_seen = 1;
1347 
1348   if (base == data_section)
1349     base = darwin_sections[objc2_metadata_section];
1350 
1351   /* Most of the OBJC2 META-data end up in the base section, so check it
1352      first.  */
1353   if      (!strncmp (p, "V2_BASE", 7))
1354     return base;
1355   else if (!strncmp (p, "V2_STRG", 7))
1356     return darwin_sections[cstring_section];
1357 
1358   else if (!strncmp (p, "G2_META", 7) || !strncmp (p, "G2_CLAS", 7))
1359     return darwin_sections[objc2_classdefs_section];
1360   else if (!strncmp (p, "V2_MREF", 7))
1361     return darwin_sections[objc2_message_refs_section];
1362   else if (!strncmp (p, "V2_CLRF", 7))
1363     return darwin_sections[objc2_classrefs_section];
1364   else if (!strncmp (p, "V2_SURF", 7))
1365     return darwin_sections[objc2_super_classrefs_section];
1366   else if (!strncmp (p, "V2_NLCL", 7))
1367     return darwin_sections[objc2_nonlazy_class_section];
1368   else if (!strncmp (p, "V2_CLAB", 7))
1369     {
1370       classes_seen = 1;
1371       return darwin_sections[objc2_classlist_section];
1372     }
1373   else if (!strncmp (p, "V2_SRFS", 7))
1374     return darwin_sections[objc2_selector_refs_section];
1375   else if (!strncmp (p, "V2_NLCA", 7))
1376     return darwin_sections[objc2_nonlazy_category_section];
1377   else if (!strncmp (p, "V2_CALA", 7))
1378     return darwin_sections[objc2_categorylist_section];
1379 
1380   else if (!strncmp (p, "V2_PLST", 7))
1381     return darwin_sections[objc2_protocollist_section];
1382   else if (!strncmp (p, "V2_PRFS", 7))
1383     return darwin_sections[objc2_protocolrefs_section];
1384 
1385   else if (!strncmp (p, "V2_INFO", 7))
1386     return darwin_sections[objc2_image_info_section];
1387 
1388   else if (!strncmp (p, "V2_EHTY", 7))
1389     return darwin_sections[data_coal_section];
1390 
1391   else if (!strncmp (p, "V2_CSTR", 7))
1392     return darwin_sections[objc2_constant_string_object_section];
1393 
1394   /* Not recognized, default.  */
1395   return base;
1396 }
1397 
1398 /* Return the section required for Objective C ABI 0/1 metadata.  */
1399 static section *
darwin_objc1_section(tree decl ATTRIBUTE_UNUSED,tree meta,section * base)1400 darwin_objc1_section (tree decl ATTRIBUTE_UNUSED, tree meta, section * base)
1401 {
1402   const char *p;
1403   tree ident = TREE_VALUE (meta);
1404   gcc_assert (TREE_CODE (ident) == IDENTIFIER_NODE);
1405   p = IDENTIFIER_POINTER (ident);
1406 
1407   gcc_checking_assert (flag_next_runtime == 1 && flag_objc_abi < 2);
1408 
1409   objc_metadata_seen = 1;
1410 
1411   /* String sections first, cos there are lots of strings.  */
1412   if      (!strncmp (p, "V1_STRG", 7))
1413     return darwin_sections[cstring_section];
1414   else if (!strncmp (p, "V1_CLSN", 7))
1415     return darwin_sections[objc_class_names_section];
1416   else if (!strncmp (p, "V1_METN", 7))
1417     return darwin_sections[objc_meth_var_names_section];
1418   else if (!strncmp (p, "V1_METT", 7))
1419     return darwin_sections[objc_meth_var_types_section];
1420 
1421   else if (!strncmp (p, "V1_CLAS", 7))
1422     {
1423       classes_seen = 1;
1424       return darwin_sections[objc_class_section];
1425     }
1426   else if (!strncmp (p, "V1_META", 7))
1427     return darwin_sections[objc_meta_class_section];
1428   else if (!strncmp (p, "V1_CATG", 7))
1429     return darwin_sections[objc_category_section];
1430   else if (!strncmp (p, "V1_PROT", 7))
1431     return darwin_sections[objc_protocol_section];
1432 
1433   else if (!strncmp (p, "V1_CLCV", 7))
1434     return darwin_sections[objc_class_vars_section];
1435   else if (!strncmp (p, "V1_CLIV", 7))
1436     return darwin_sections[objc_instance_vars_section];
1437 
1438   else if (!strncmp (p, "V1_CLCM", 7))
1439     return darwin_sections[objc_cls_meth_section];
1440   else if (!strncmp (p, "V1_CLIM", 7))
1441     return darwin_sections[objc_inst_meth_section];
1442   else if (!strncmp (p, "V1_CACM", 7))
1443     return darwin_sections[objc_cat_cls_meth_section];
1444   else if (!strncmp (p, "V1_CAIM", 7))
1445     return darwin_sections[objc_cat_inst_meth_section];
1446   else if (!strncmp (p, "V1_PNSM", 7))
1447     return darwin_sections[objc_cat_inst_meth_section];
1448   else if (!strncmp (p, "V1_PCLM", 7))
1449     return darwin_sections[objc_cat_cls_meth_section];
1450 
1451   else if (!strncmp (p, "V1_CLPR", 7))
1452     return darwin_sections[objc_cat_cls_meth_section];
1453   else if (!strncmp (p, "V1_CAPR", 7))
1454     return darwin_sections[objc_category_section]; /* ??? CHECK me.  */
1455 
1456   else if (!strncmp (p, "V1_PRFS", 7))
1457     return darwin_sections[objc_cat_cls_meth_section];
1458   else if (!strncmp (p, "V1_CLRF", 7))
1459     return darwin_sections[objc_cls_refs_section];
1460   else if (!strncmp (p, "V1_SRFS", 7))
1461     return darwin_sections[objc_selector_refs_section];
1462 
1463   else if (!strncmp (p, "V1_MODU", 7))
1464     return darwin_sections[objc_module_info_section];
1465   else if (!strncmp (p, "V1_SYMT", 7))
1466     return darwin_sections[objc_symbols_section];
1467   else if (!strncmp (p, "V1_INFO", 7))
1468     return darwin_sections[objc_image_info_section];
1469 
1470   else if (!strncmp (p, "V1_PLST", 7))
1471     return darwin_sections[objc1_prop_list_section];
1472   else if (!strncmp (p, "V1_PEXT", 7))
1473     return darwin_sections[objc1_protocol_ext_section];
1474   else if (!strncmp (p, "V1_CEXT", 7))
1475     return darwin_sections[objc1_class_ext_section];
1476 
1477   else if (!strncmp (p, "V2_CSTR", 7))
1478     return darwin_sections[objc_constant_string_object_section];
1479 
1480   return base;
1481 }
1482 
1483 section *
machopic_select_section(tree decl,int reloc,unsigned HOST_WIDE_INT align)1484 machopic_select_section (tree decl,
1485 			 int reloc,
1486 			 unsigned HOST_WIDE_INT align)
1487 {
1488   bool zsize, one, weak, ro;
1489   section *base_section = NULL;
1490 
1491   weak = (DECL_P (decl)
1492 	  && DECL_WEAK (decl)
1493 	  && !lookup_attribute ("weak_import", DECL_ATTRIBUTES (decl)));
1494 
1495   zsize = (DECL_P (decl)
1496 	   && (TREE_CODE (decl) == VAR_DECL || TREE_CODE (decl) == CONST_DECL)
1497 	   && tree_low_cst (DECL_SIZE_UNIT (decl), 1) == 0);
1498 
1499   one = DECL_P (decl)
1500 	&& TREE_CODE (decl) == VAR_DECL
1501 	&& DECL_ONE_ONLY (decl);
1502 
1503   ro = TREE_READONLY (decl) || TREE_CONSTANT (decl) ;
1504 
1505   switch (categorize_decl_for_section (decl, reloc))
1506     {
1507     case SECCAT_TEXT:
1508       gcc_unreachable ();
1509       break;
1510 
1511     case SECCAT_RODATA:
1512     case SECCAT_SRODATA:
1513       base_section = darwin_rodata_section (weak, zsize);
1514       break;
1515 
1516     case SECCAT_RODATA_MERGE_STR:
1517       base_section = darwin_mergeable_string_section (decl, align);
1518       break;
1519 
1520     case SECCAT_RODATA_MERGE_STR_INIT:
1521       base_section = darwin_mergeable_string_section (DECL_INITIAL (decl), align);
1522       break;
1523 
1524     case SECCAT_RODATA_MERGE_CONST:
1525       base_section =  darwin_mergeable_constant_section (decl, align, zsize);
1526       break;
1527 
1528     case SECCAT_DATA:
1529     case SECCAT_DATA_REL:
1530     case SECCAT_DATA_REL_LOCAL:
1531     case SECCAT_DATA_REL_RO:
1532     case SECCAT_DATA_REL_RO_LOCAL:
1533     case SECCAT_SDATA:
1534     case SECCAT_TDATA:
1535       if (weak || one)
1536 	{
1537 	  if (ro)
1538 	    base_section = darwin_sections[const_data_coal_section];
1539 	  else
1540 	    base_section = darwin_sections[data_coal_section];
1541 	}
1542       else if (DARWIN_SECTION_ANCHORS
1543 	       && flag_section_anchors
1544 	       && zsize)
1545 	{
1546 	  /* If we're doing section anchors, then punt zero-sized objects into
1547 	     their own sections so that they don't interfere with offset
1548 	     computation for the remaining vars.  This does not need to be done
1549 	     for stuff in mergeable sections, since these are ineligible for
1550 	     anchors.  */
1551 	  if (ro)
1552 	    base_section = darwin_sections[zobj_const_data_section];
1553 	  else
1554 	    base_section = darwin_sections[zobj_data_section];
1555 	}
1556       else if (ro)
1557 	base_section = darwin_sections[const_data_section];
1558       else
1559 	base_section = data_section;
1560       break;
1561     case SECCAT_BSS:
1562     case SECCAT_SBSS:
1563     case SECCAT_TBSS:
1564       if (weak || one)
1565 	base_section = darwin_sections[data_coal_section];
1566       else
1567 	{
1568 	  if (!TREE_PUBLIC (decl))
1569 	    base_section = lcomm_section;
1570 	  else if (bss_noswitch_section)
1571 	    base_section = bss_noswitch_section;
1572 	  else
1573 	    base_section = data_section;
1574 	}
1575       break;
1576 
1577     default:
1578       gcc_unreachable ();
1579     }
1580 
1581   /* Darwin weird special cases.
1582      a) OBJC Meta-data. */
1583   if (DECL_P (decl)
1584       && (TREE_CODE (decl) == VAR_DECL
1585 	  || TREE_CODE (decl) == CONST_DECL)
1586       && DECL_ATTRIBUTES (decl))
1587     {
1588       tree meta = lookup_attribute ("OBJC2META", DECL_ATTRIBUTES (decl));
1589       if (meta)
1590 	return darwin_objc2_section (decl, meta, base_section);
1591       meta = lookup_attribute ("OBJC1META", DECL_ATTRIBUTES (decl));
1592       if (meta)
1593 	return darwin_objc1_section (decl, meta, base_section);
1594       meta = lookup_attribute ("OBJC1METG", DECL_ATTRIBUTES (decl));
1595       if (meta)
1596 	return base_section; /* GNU runtime is happy with it all in one pot.  */
1597     }
1598 
1599   /* b) Constant string objects.  */
1600   if (TREE_CODE (decl) == CONSTRUCTOR
1601       && TREE_TYPE (decl)
1602       && TREE_CODE (TREE_TYPE (decl)) == RECORD_TYPE
1603       && TYPE_NAME (TREE_TYPE (decl)))
1604     {
1605       tree name = TYPE_NAME (TREE_TYPE (decl));
1606       if (TREE_CODE (name) == TYPE_DECL)
1607         name = DECL_NAME (name);
1608 
1609       if (!strcmp (IDENTIFIER_POINTER (name), "__builtin_ObjCString"))
1610 	{
1611 	  if (flag_next_runtime)
1612 	    {
1613 	      if (flag_objc_abi == 2)
1614 		return darwin_sections[objc2_constant_string_object_section];
1615 	      else
1616 		return darwin_sections[objc_constant_string_object_section];
1617 	    }
1618 	  else
1619 	    return darwin_sections[objc_string_object_section];
1620 	}
1621       else if (!strcmp (IDENTIFIER_POINTER (name), "__builtin_CFString"))
1622 	return darwin_sections[cfstring_constant_object_section];
1623       else
1624 	return base_section;
1625     }
1626   /* c) legacy meta-data selection.  */
1627   else if (TREE_CODE (decl) == VAR_DECL
1628 	   && DECL_NAME (decl)
1629 	   && TREE_CODE (DECL_NAME (decl)) == IDENTIFIER_NODE
1630 	   && IDENTIFIER_POINTER (DECL_NAME (decl))
1631 	   && flag_next_runtime
1632 	   && !strncmp (IDENTIFIER_POINTER (DECL_NAME (decl)), "_OBJC_", 6))
1633     {
1634       const char *name = IDENTIFIER_POINTER (DECL_NAME (decl));
1635       static bool warned_objc_46 = false;
1636       /* We shall assert that zero-sized objects are an error in ObjC
1637          meta-data.  */
1638       gcc_assert (tree_low_cst (DECL_SIZE_UNIT (decl), 1) != 0);
1639 
1640       /* ??? This mechanism for determining the metadata section is
1641 	 broken when LTO is in use, since the frontend that generated
1642 	 the data is not identified.  We will keep the capability for
1643 	 the short term - in case any non-Objective-C programs are using
1644 	 it to place data in specified sections.  */
1645       if (!warned_objc_46)
1646 	{
1647 	  location_t loc = DECL_SOURCE_LOCATION (decl);
1648 	  warning_at (loc, 0, "the use of _OBJC_-prefixed variable names"
1649 		      " to select meta-data sections is deprecated at 4.6"
1650 		      " and will be removed in 4.7");
1651 	  warned_objc_46 = true;
1652 	}
1653 
1654       if (!strncmp (name, "_OBJC_CLASS_METHODS_", 20))
1655         return darwin_sections[objc_cls_meth_section];
1656       else if (!strncmp (name, "_OBJC_INSTANCE_METHODS_", 23))
1657         return darwin_sections[objc_inst_meth_section];
1658       else if (!strncmp (name, "_OBJC_CATEGORY_CLASS_METHODS_", 29))
1659         return darwin_sections[objc_cat_cls_meth_section];
1660       else if (!strncmp (name, "_OBJC_CATEGORY_INSTANCE_METHODS_", 32))
1661         return darwin_sections[objc_cat_inst_meth_section];
1662       else if (!strncmp (name, "_OBJC_CLASS_VARIABLES_", 22))
1663         return darwin_sections[objc_class_vars_section];
1664       else if (!strncmp (name, "_OBJC_INSTANCE_VARIABLES_", 25))
1665         return darwin_sections[objc_instance_vars_section];
1666       else if (!strncmp (name, "_OBJC_CLASS_PROTOCOLS_", 22))
1667         return darwin_sections[objc_cat_cls_meth_section];
1668       else if (!strncmp (name, "_OBJC_CLASS_NAME_", 17))
1669         return darwin_sections[objc_class_names_section];
1670       else if (!strncmp (name, "_OBJC_METH_VAR_NAME_", 20))
1671         return darwin_sections[objc_meth_var_names_section];
1672       else if (!strncmp (name, "_OBJC_METH_VAR_TYPE_", 20))
1673         return darwin_sections[objc_meth_var_types_section];
1674       else if (!strncmp (name, "_OBJC_CLASS_REFERENCES", 22))
1675         return darwin_sections[objc_cls_refs_section];
1676       else if (!strncmp (name, "_OBJC_CLASS_", 12))
1677         return darwin_sections[objc_class_section];
1678       else if (!strncmp (name, "_OBJC_METACLASS_", 16))
1679         return darwin_sections[objc_meta_class_section];
1680       else if (!strncmp (name, "_OBJC_CATEGORY_", 15))
1681         return darwin_sections[objc_category_section];
1682       else if (!strncmp (name, "_OBJC_SELECTOR_REFERENCES", 25))
1683         return darwin_sections[objc_selector_refs_section];
1684       else if (!strncmp (name, "_OBJC_SELECTOR_FIXUP", 20))
1685         return darwin_sections[objc_selector_fixup_section];
1686       else if (!strncmp (name, "_OBJC_SYMBOLS", 13))
1687         return darwin_sections[objc_symbols_section];
1688       else if (!strncmp (name, "_OBJC_MODULES", 13))
1689         return darwin_sections[objc_module_info_section];
1690       else if (!strncmp (name, "_OBJC_IMAGE_INFO", 16))
1691         return darwin_sections[objc_image_info_section];
1692       else if (!strncmp (name, "_OBJC_PROTOCOL_INSTANCE_METHODS_", 32))
1693         return darwin_sections[objc_cat_inst_meth_section];
1694       else if (!strncmp (name, "_OBJC_PROTOCOL_CLASS_METHODS_", 29))
1695         return darwin_sections[objc_cat_cls_meth_section];
1696       else if (!strncmp (name, "_OBJC_PROTOCOL_REFS_", 20))
1697         return darwin_sections[objc_cat_cls_meth_section];
1698       else if (!strncmp (name, "_OBJC_PROTOCOL_", 15))
1699         return darwin_sections[objc_protocol_section];
1700       else
1701         return base_section;
1702     }
1703 
1704   return base_section;
1705 }
1706 
1707 /* This can be called with address expressions as "rtx".
1708    They must go in "const".  */
1709 
1710 section *
machopic_select_rtx_section(enum machine_mode mode,rtx x,unsigned HOST_WIDE_INT align ATTRIBUTE_UNUSED)1711 machopic_select_rtx_section (enum machine_mode mode, rtx x,
1712 			     unsigned HOST_WIDE_INT align ATTRIBUTE_UNUSED)
1713 {
1714   if (GET_MODE_SIZE (mode) == 8
1715       && (GET_CODE (x) == CONST_INT
1716 	  || GET_CODE (x) == CONST_DOUBLE))
1717     return darwin_sections[literal8_section];
1718   else if (GET_MODE_SIZE (mode) == 4
1719 	   && (GET_CODE (x) == CONST_INT
1720 	       || GET_CODE (x) == CONST_DOUBLE))
1721     return darwin_sections[literal4_section];
1722   else if (HAVE_GAS_LITERAL16
1723 	   && TARGET_64BIT
1724 	   && GET_MODE_SIZE (mode) == 16
1725 	   && (GET_CODE (x) == CONST_INT
1726 	       || GET_CODE (x) == CONST_DOUBLE
1727 	       || GET_CODE (x) == CONST_VECTOR))
1728     return darwin_sections[literal16_section];
1729   else if (MACHOPIC_INDIRECT
1730 	   && (GET_CODE (x) == SYMBOL_REF
1731 	       || GET_CODE (x) == CONST
1732 	       || GET_CODE (x) == LABEL_REF))
1733     return darwin_sections[const_data_section];
1734   else
1735     return darwin_sections[const_section];
1736 }
1737 
1738 void
machopic_asm_out_constructor(rtx symbol,int priority ATTRIBUTE_UNUSED)1739 machopic_asm_out_constructor (rtx symbol, int priority ATTRIBUTE_UNUSED)
1740 {
1741   cdtor_record new_elt = {symbol, priority, vec_safe_length (ctors)};
1742 
1743   vec_safe_push (ctors, new_elt);
1744 
1745   if (! MACHOPIC_INDIRECT)
1746     fprintf (asm_out_file, ".reference .constructors_used\n");
1747 }
1748 
1749 void
machopic_asm_out_destructor(rtx symbol,int priority ATTRIBUTE_UNUSED)1750 machopic_asm_out_destructor (rtx symbol, int priority ATTRIBUTE_UNUSED)
1751 {
1752   cdtor_record new_elt = {symbol, priority, vec_safe_length (dtors)};
1753 
1754   vec_safe_push (dtors, new_elt);
1755 
1756   if (! MACHOPIC_INDIRECT)
1757     fprintf (asm_out_file, ".reference .destructors_used\n");
1758 }
1759 
1760 static int
sort_cdtor_records(const void * a,const void * b)1761 sort_cdtor_records (const void * a, const void * b)
1762 {
1763   const cdtor_record *cda = (const cdtor_record *)a;
1764   const cdtor_record *cdb = (const cdtor_record *)b;
1765   if (cda->priority > cdb->priority)
1766     return 1;
1767   if (cda->priority < cdb->priority)
1768     return -1;
1769   if (cda->position > cdb->position)
1770     return 1;
1771   if (cda->position < cdb->position)
1772     return -1;
1773   return 0;
1774 }
1775 
1776 static void
finalize_ctors()1777 finalize_ctors ()
1778 {
1779   unsigned int i;
1780   cdtor_record *elt;
1781 
1782   if (MACHOPIC_INDIRECT)
1783     switch_to_section (darwin_sections[mod_init_section]);
1784   else
1785     switch_to_section (darwin_sections[constructor_section]);
1786 
1787   if (vec_safe_length (ctors) > 1)
1788     ctors->qsort (sort_cdtor_records);
1789   FOR_EACH_VEC_SAFE_ELT (ctors, i, elt)
1790     {
1791       assemble_align (POINTER_SIZE);
1792       assemble_integer (elt->symbol, POINTER_SIZE / BITS_PER_UNIT, POINTER_SIZE, 1);
1793     }
1794 }
1795 
1796 static void
finalize_dtors()1797 finalize_dtors ()
1798 {
1799   unsigned int i;
1800   cdtor_record *elt;
1801 
1802   if (MACHOPIC_INDIRECT)
1803     switch_to_section (darwin_sections[mod_term_section]);
1804   else
1805     switch_to_section (darwin_sections[destructor_section]);
1806 
1807   if (vec_safe_length (dtors) > 1)
1808     dtors->qsort (sort_cdtor_records);
1809   FOR_EACH_VEC_SAFE_ELT (dtors, i, elt)
1810     {
1811       assemble_align (POINTER_SIZE);
1812       assemble_integer (elt->symbol, POINTER_SIZE / BITS_PER_UNIT, POINTER_SIZE, 1);
1813     }
1814 }
1815 
1816 void
darwin_globalize_label(FILE * stream,const char * name)1817 darwin_globalize_label (FILE *stream, const char *name)
1818 {
1819   if (!!strncmp (name, "_OBJC_", 6))
1820     default_globalize_label (stream, name);
1821 }
1822 
1823 /* This routine returns non-zero if 'name' starts with the special objective-c
1824    anonymous file-scope static name.  It accommodates c++'s mangling of such
1825    symbols (in this case the symbols will have form _ZL{d}*_OBJC_* d=digit).  */
1826 
1827 int
darwin_label_is_anonymous_local_objc_name(const char * name)1828 darwin_label_is_anonymous_local_objc_name (const char *name)
1829 {
1830   const unsigned char *p = (const unsigned char *) name;
1831   if (*p != '_')
1832     return 0;
1833   if (p[1] == 'Z' && p[2] == 'L')
1834   {
1835     p += 3;
1836     while (*p >= '0' && *p <= '9')
1837       p++;
1838   }
1839   return (!strncmp ((const char *)p, "_OBJC_", 6));
1840 }
1841 
1842 /* LTO support for Mach-O.
1843 
1844    This version uses three mach-o sections to encapsulate the (unlimited
1845    number of) lto sections.
1846 
1847    __GNU_LTO, __lto_sections  contains the concatented GNU LTO section data.
1848    __GNU_LTO, __section_names contains the GNU LTO section names.
1849    __GNU_LTO, __section_index contains an array of values that index these.
1850 
1851    Indexed thus:
1852      <section offset from the start of __GNU_LTO, __lto_sections>,
1853      <section length>
1854      <name offset from the start of __GNU_LTO, __section_names,
1855      <name length>.
1856 
1857    At present, for both m32 and m64 mach-o files each of these fields is
1858    represented  by a uint32_t.  This is because, AFAICT, a mach-o object
1859    cannot exceed 4Gb because the section_64 offset field (see below) is 32bits.
1860 
1861     uint32_t offset;
1862    "offset  An integer specifying the offset to this section in the file."  */
1863 
1864 /* Count lto section numbers.  */
1865 static unsigned int lto_section_num = 0;
1866 
1867 /* A vector of information about LTO sections, at present, we only have
1868    the name.  TODO: see if we can get the data length somehow.  */
1869 typedef struct GTY (()) darwin_lto_section_e {
1870   const char *sectname;
1871 } darwin_lto_section_e ;
1872 
1873 static GTY (()) vec<darwin_lto_section_e, va_gc> *lto_section_names;
1874 
1875 /* Segment for LTO data.  */
1876 #define LTO_SEGMENT_NAME "__GNU_LTO"
1877 
1878 /* Section wrapper scheme (used here to wrap the unlimited number of LTO
1879    sections into three Mach-O ones).
1880    NOTE: These names MUST be kept in sync with those in
1881 	 libiberty/simple-object-mach-o.  */
1882 #define LTO_SECTS_SECTION "__wrapper_sects"
1883 #define LTO_NAMES_SECTION "__wrapper_names"
1884 #define LTO_INDEX_SECTION "__wrapper_index"
1885 
1886 /* File to temporarily store LTO data.  This is appended to asm_out_file
1887    in darwin_end_file.  */
1888 static FILE *lto_asm_out_file, *saved_asm_out_file;
1889 static char *lto_asm_out_name;
1890 
1891 /* Prepare asm_out_file for LTO output.  For darwin, this means hiding
1892    asm_out_file and switching to an alternative output file.  */
1893 void
darwin_asm_lto_start(void)1894 darwin_asm_lto_start (void)
1895 {
1896   gcc_assert (! saved_asm_out_file);
1897   saved_asm_out_file = asm_out_file;
1898   if (! lto_asm_out_name)
1899     lto_asm_out_name = make_temp_file (".lto.s");
1900   lto_asm_out_file = fopen (lto_asm_out_name, "a");
1901   if (lto_asm_out_file == NULL)
1902     fatal_error ("failed to open temporary file %s for LTO output",
1903 		 lto_asm_out_name);
1904   asm_out_file = lto_asm_out_file;
1905 }
1906 
1907 /* Restore asm_out_file.  */
1908 void
darwin_asm_lto_end(void)1909 darwin_asm_lto_end (void)
1910 {
1911   gcc_assert (saved_asm_out_file);
1912   fclose (lto_asm_out_file);
1913   asm_out_file = saved_asm_out_file;
1914   saved_asm_out_file = NULL;
1915 }
1916 
1917 static void
1918 darwin_asm_dwarf_section (const char *name, unsigned int flags, tree decl);
1919 
1920 /*  Called for the TARGET_ASM_NAMED_SECTION hook.  */
1921 
1922 void
darwin_asm_named_section(const char * name,unsigned int flags,tree decl ATTRIBUTE_UNUSED)1923 darwin_asm_named_section (const char *name,
1924 			  unsigned int flags,
1925 			  tree decl ATTRIBUTE_UNUSED)
1926 {
1927   /* LTO sections go in a special section that encapsulates the (unlimited)
1928      number of GNU LTO sections within a single mach-o one.  */
1929   if (strncmp (name, LTO_SECTION_NAME_PREFIX,
1930 	       strlen (LTO_SECTION_NAME_PREFIX)) == 0)
1931     {
1932       darwin_lto_section_e e;
1933       /* We expect certain flags to be set...  */
1934       gcc_assert ((flags & (SECTION_DEBUG | SECTION_NAMED))
1935 		  == (SECTION_DEBUG | SECTION_NAMED));
1936 
1937       /* Switch to our combined section.  */
1938       fprintf (asm_out_file, "\t.section %s,%s,regular,debug\n",
1939 	       LTO_SEGMENT_NAME, LTO_SECTS_SECTION);
1940       /* Output a label for the start of this sub-section.  */
1941       fprintf (asm_out_file, "L_GNU_LTO%d:\t;# %s\n",
1942 	       lto_section_num, name);
1943       /* We have to jump through hoops to get the values of the intra-section
1944          offsets... */
1945       fprintf (asm_out_file, "\t.set L$gnu$lto$offs%d,L_GNU_LTO%d-L_GNU_LTO0\n",
1946 	       lto_section_num, lto_section_num);
1947       fprintf (asm_out_file,
1948 	       "\t.set L$gnu$lto$size%d,L_GNU_LTO%d-L_GNU_LTO%d\n",
1949 	       lto_section_num, lto_section_num+1, lto_section_num);
1950       lto_section_num++;
1951       e.sectname = xstrdup (name);
1952       /* Keep the names, we'll need to make a table later.
1953          TODO: check that we do not revisit sections, that would break
1954          the assumption of how this is done.  */
1955       if (lto_section_names == NULL)
1956         vec_alloc (lto_section_names, 16);
1957       vec_safe_push (lto_section_names, e);
1958    }
1959   else if (strncmp (name, "__DWARF,", 8) == 0)
1960     darwin_asm_dwarf_section (name, flags, decl);
1961   else
1962     fprintf (asm_out_file, "\t.section %s\n", name);
1963 }
1964 
1965 void
darwin_unique_section(tree decl ATTRIBUTE_UNUSED,int reloc ATTRIBUTE_UNUSED)1966 darwin_unique_section (tree decl ATTRIBUTE_UNUSED, int reloc ATTRIBUTE_UNUSED)
1967 {
1968   /* Darwin does not use unique sections.  */
1969 }
1970 
1971 /* Handle __attribute__ ((apple_kext_compatibility)).
1972    This only applies to darwin kexts for 2.95 compatibility -- it shrinks the
1973    vtable for classes with this attribute (and their descendants) by not
1974    outputting the new 3.0 nondeleting destructor.  This means that such
1975    objects CANNOT be allocated on the stack or as globals UNLESS they have
1976    a completely empty `operator delete'.
1977    Luckily, this fits in with the Darwin kext model.
1978 
1979    This attribute also disables gcc3's potential overlaying of derived
1980    class data members on the padding at the end of the base class.  */
1981 
1982 tree
darwin_handle_kext_attribute(tree * node,tree name,tree args ATTRIBUTE_UNUSED,int flags ATTRIBUTE_UNUSED,bool * no_add_attrs)1983 darwin_handle_kext_attribute (tree *node, tree name,
1984 			      tree args ATTRIBUTE_UNUSED,
1985 			      int flags ATTRIBUTE_UNUSED,
1986 			      bool *no_add_attrs)
1987 {
1988   /* APPLE KEXT stuff -- only applies with pure static C++ code.  */
1989   if (! TARGET_KEXTABI)
1990     {
1991       warning (0, "%qE 2.95 vtable-compatibility attribute applies "
1992 	       "only when compiling a kext", name);
1993 
1994       *no_add_attrs = true;
1995     }
1996   else if (TREE_CODE (*node) != RECORD_TYPE)
1997     {
1998       warning (0, "%qE 2.95 vtable-compatibility attribute applies "
1999 	       "only to C++ classes", name);
2000 
2001       *no_add_attrs = true;
2002     }
2003 
2004   return NULL_TREE;
2005 }
2006 
2007 /* Handle a "weak_import" attribute; arguments as in
2008    struct attribute_spec.handler.  */
2009 
2010 tree
darwin_handle_weak_import_attribute(tree * node,tree name,tree ARG_UNUSED (args),int ARG_UNUSED (flags),bool * no_add_attrs)2011 darwin_handle_weak_import_attribute (tree *node, tree name,
2012 				     tree ARG_UNUSED (args),
2013 				     int ARG_UNUSED (flags),
2014 				     bool * no_add_attrs)
2015 {
2016   if (TREE_CODE (*node) != FUNCTION_DECL && TREE_CODE (*node) != VAR_DECL)
2017     {
2018       warning (OPT_Wattributes, "%qE attribute ignored",
2019 	       name);
2020       *no_add_attrs = true;
2021     }
2022   else
2023     declare_weak (*node);
2024 
2025   return NULL_TREE;
2026 }
2027 
2028 /* Emit a label for an FDE, making it global and/or weak if appropriate.
2029    The third parameter is nonzero if this is for exception handling.
2030    The fourth parameter is nonzero if this is just a placeholder for an
2031    FDE that we are omitting. */
2032 
2033 void
darwin_emit_unwind_label(FILE * file,tree decl,int for_eh,int empty)2034 darwin_emit_unwind_label (FILE *file, tree decl, int for_eh, int empty)
2035 {
2036   char *lab ;
2037   char buf[32];
2038   static int invok_count = 0;
2039   static tree last_fun_decl = NULL_TREE;
2040 
2041   /* We use the linker to emit the .eh labels for Darwin 9 and above.  */
2042   if (! for_eh || generating_for_darwin_version >= 9)
2043     return;
2044 
2045   /* FIXME: This only works when the eh for all sections of a function is
2046      emitted at the same time.  If that changes, we would need to use a lookup
2047      table of some form to determine what to do.  Also, we should emit the
2048      unadorned label for the partition containing the public label for a
2049      function.  This is of limited use, probably, since we do not currently
2050      enable partitioning.  */
2051   strcpy (buf, ".eh");
2052   if (decl && TREE_CODE (decl) == FUNCTION_DECL)
2053     {
2054       if (decl == last_fun_decl)
2055         {
2056 	  invok_count++;
2057 	  snprintf (buf, 31, "$$part$$%d.eh", invok_count);
2058 	}
2059       else
2060 	{
2061 	  last_fun_decl = decl;
2062 	  invok_count = 0;
2063 	}
2064     }
2065 
2066   lab = concat (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl)), buf, NULL);
2067 
2068   if (TREE_PUBLIC (decl))
2069     {
2070       targetm.asm_out.globalize_label (file, lab);
2071       if (DECL_VISIBILITY (decl) == VISIBILITY_HIDDEN)
2072 	{
2073 	  fputs ("\t.private_extern ", file);
2074 	  assemble_name (file, lab);
2075 	  fputc ('\n', file);
2076 	}
2077     }
2078 
2079   if (DECL_WEAK (decl))
2080     {
2081       fputs ("\t.weak_definition ", file);
2082       assemble_name (file, lab);
2083       fputc ('\n', file);
2084     }
2085 
2086   assemble_name (file, lab);
2087   if (empty)
2088     {
2089       fputs (" = 0\n", file);
2090 
2091       /* Mark the absolute .eh and .eh1 style labels as needed to
2092 	 ensure that we don't dead code strip them and keep such
2093 	 labels from another instantiation point until we can fix this
2094 	 properly with group comdat support.  */
2095       darwin_mark_decl_preserved (lab);
2096     }
2097   else
2098     fputs (":\n", file);
2099 
2100   free (lab);
2101 }
2102 
2103 static GTY(()) unsigned long except_table_label_num;
2104 
2105 void
darwin_emit_except_table_label(FILE * file)2106 darwin_emit_except_table_label (FILE *file)
2107 {
2108   char section_start_label[30];
2109 
2110   ASM_GENERATE_INTERNAL_LABEL (section_start_label, "GCC_except_table",
2111 			       except_table_label_num++);
2112   ASM_OUTPUT_LABEL (file, section_start_label);
2113 }
2114 /* Generate a PC-relative reference to a Mach-O non-lazy-symbol.  */
2115 
2116 void
darwin_non_lazy_pcrel(FILE * file,rtx addr)2117 darwin_non_lazy_pcrel (FILE *file, rtx addr)
2118 {
2119   const char *nlp_name;
2120 
2121   gcc_assert (GET_CODE (addr) == SYMBOL_REF);
2122 
2123   nlp_name = machopic_indirection_name (addr, /*stub_p=*/false);
2124   fputs ("\t.long\t", file);
2125   ASM_OUTPUT_LABELREF (file, nlp_name);
2126   fputs ("-.", file);
2127 }
2128 
2129 /* If this is uncommented, details of each allocation will be printed
2130    in the asm right before the actual code.  WARNING - this will cause some
2131    test-suite fails (since the printout will contain items that some tests
2132    are not expecting) -- so don't leave it on by default (it bloats the
2133    asm too).  */
2134 /*#define DEBUG_DARWIN_MEM_ALLOCATORS*/
2135 
2136 /* The first two of these routines are ostensibly just intended to put
2137    names into the asm.  However, they are both hijacked in order to ensure
2138    that zero-sized items do not make their way into the output.  Consequently,
2139    we also need to make these participate in provisions for dealing with
2140    such items in section anchors.  */
2141 
2142 /* The implementation of ASM_DECLARE_OBJECT_NAME.  */
2143 /* The RTTI data (e.g., __ti4name) is common and public (and static),
2144    but it does need to be referenced via indirect PIC data pointers.
2145    The machopic_define_symbol calls are telling the machopic subsystem
2146    that the name *is* defined in this module, so it doesn't need to
2147    make them indirect.  */
2148 void
darwin_asm_declare_object_name(FILE * file,const char * nam,tree decl)2149 darwin_asm_declare_object_name (FILE *file,
2150 				const char *nam, tree decl)
2151 {
2152   const char *xname = nam;
2153   unsigned HOST_WIDE_INT size;
2154   bool local_def, weak;
2155 
2156   weak = (DECL_P (decl)
2157 	  && DECL_WEAK (decl)
2158 	  && !lookup_attribute ("weak_import",
2159 				 DECL_ATTRIBUTES (decl)));
2160 
2161   local_def = DECL_INITIAL (decl) || (TREE_STATIC (decl)
2162 				      && (!DECL_COMMON (decl)
2163 					  || !TREE_PUBLIC (decl)));
2164 
2165   if (GET_CODE (XEXP (DECL_RTL (decl), 0)) != SYMBOL_REF)
2166     xname = IDENTIFIER_POINTER (DECL_NAME (decl));
2167 
2168   if (local_def)
2169     {
2170       (* targetm.encode_section_info) (decl, DECL_RTL (decl), false);
2171       if (!weak)
2172 	machopic_define_symbol (DECL_RTL (decl));
2173     }
2174 
2175   size = tree_low_cst (DECL_SIZE_UNIT (decl), 1);
2176 
2177 #ifdef DEBUG_DARWIN_MEM_ALLOCATORS
2178 fprintf (file, "# dadon: %s %s (%llu, %u) local %d weak %d"
2179 	       " stat %d com %d pub %d t-const %d t-ro %d init %lx\n",
2180 	xname, (TREE_CODE (decl) == VAR_DECL?"var":"const"),
2181 	(unsigned long long)size, DECL_ALIGN (decl), local_def,
2182 	DECL_WEAK (decl), TREE_STATIC (decl), DECL_COMMON (decl),
2183 	TREE_PUBLIC (decl), TREE_CONSTANT (decl), TREE_READONLY (decl),
2184 	(unsigned long)DECL_INITIAL (decl));
2185 #endif
2186 
2187   /* Darwin needs help to support local zero-sized objects.
2188      They must be made at least one byte, and the section containing must be
2189      marked as unsuitable for section-anchors (see storage allocators below).
2190 
2191      For non-zero objects this output is handled by varasm.c.
2192   */
2193   if (!size)
2194     {
2195       unsigned int l2align = 0;
2196 
2197       /* The align must be honored, even for zero-sized.  */
2198       if (DECL_ALIGN (decl))
2199 	{
2200 	  l2align = floor_log2 (DECL_ALIGN (decl) / BITS_PER_UNIT);
2201 	  fprintf (file, "\t.align\t%u\n", l2align);
2202 	}
2203 
2204       ASM_OUTPUT_LABEL (file, xname);
2205       size = 1;
2206       fprintf (file, "\t.space\t" HOST_WIDE_INT_PRINT_UNSIGNED"\n", size);
2207 
2208       /* Check that we've correctly picked up the zero-sized item and placed it
2209          properly.  */
2210       gcc_assert ((!DARWIN_SECTION_ANCHORS || !flag_section_anchors)
2211 		  || (in_section
2212 		      && (in_section->common.flags & SECTION_NO_ANCHOR)));
2213     }
2214   else
2215     ASM_OUTPUT_LABEL (file, xname);
2216 }
2217 
2218 /* The implementation of ASM_DECLARE_CONSTANT_NAME.  */
2219 void
darwin_asm_declare_constant_name(FILE * file,const char * name,const_tree exp ATTRIBUTE_UNUSED,HOST_WIDE_INT size)2220 darwin_asm_declare_constant_name (FILE *file, const char *name,
2221 				  const_tree exp ATTRIBUTE_UNUSED,
2222 				  HOST_WIDE_INT size)
2223 {
2224   assemble_label (file, name);
2225   /* As for other items, we need at least one byte.  */
2226   if (!size)
2227     {
2228       fputs ("\t.space\t1\n", file);
2229       /* Check that we've correctly picked up the zero-sized item and placed it
2230          properly.  */
2231       gcc_assert ((!DARWIN_SECTION_ANCHORS || !flag_section_anchors)
2232 		  || (in_section
2233 		      && (in_section->common.flags & SECTION_NO_ANCHOR)));
2234     }
2235 }
2236 
2237 /* Darwin storage allocators.
2238 
2239    Zerofill sections are desirable for large blank data since, otherwise, these
2240    data bloat objects (PR33210).
2241 
2242    However, section anchors don't work in .zerofill sections (one cannot switch
2243    to a zerofill section).  Ergo, for Darwin targets using section anchors we need
2244    to put (at least some) data into 'normal' switchable sections.
2245 
2246    Here we set a relatively arbitrary value for the size of an object to trigger
2247    zerofill when section anchors are enabled (anything bigger than a page for
2248    current Darwin implementations).  FIXME: there ought to be some objective way
2249    to make this choice.
2250 
2251    When section anchor are off this is ignored anyway.  */
2252 
2253 #define BYTES_ZFILL 4096
2254 
2255 /* Emit a chunk of data for items coalesced by the linker.  */
2256 static void
darwin_emit_weak_or_comdat(FILE * fp,tree decl,const char * name,unsigned HOST_WIDE_INT size,unsigned int align)2257 darwin_emit_weak_or_comdat (FILE *fp, tree decl, const char *name,
2258 				  unsigned HOST_WIDE_INT size,
2259 				  unsigned int align)
2260 {
2261   /* Since the sections used here are coalesed, they will not be eligible
2262      for section anchors, and therefore we don't need to break that out.  */
2263  if (TREE_READONLY (decl) || TREE_CONSTANT (decl))
2264     switch_to_section (darwin_sections[const_data_coal_section]);
2265   else
2266     switch_to_section (darwin_sections[data_coal_section]);
2267 
2268   /* To be consistent, we'll allow darwin_asm_declare_object_name to assemble
2269      the align info for zero-sized items... but do it here otherwise.  */
2270   if (size && align)
2271     fprintf (fp, "\t.align\t%d\n", floor_log2 (align / BITS_PER_UNIT));
2272 
2273   if (TREE_PUBLIC (decl))
2274     darwin_globalize_label (fp, name);
2275 
2276   /* ... and we let it deal with outputting one byte of zero for them too.  */
2277   darwin_asm_declare_object_name (fp, name, decl);
2278   if (size)
2279     assemble_zeros (size);
2280 }
2281 
2282 /* Emit a chunk of data for ObjC meta-data that got placed in BSS erroneously.  */
2283 static void
darwin_emit_objc_zeroed(FILE * fp,tree decl,const char * name,unsigned HOST_WIDE_INT size,unsigned int align,tree meta)2284 darwin_emit_objc_zeroed (FILE *fp, tree decl, const char *name,
2285 				  unsigned HOST_WIDE_INT size,
2286 				  unsigned int align, tree meta)
2287 {
2288   section *ocs = data_section;
2289 
2290   if (TREE_PURPOSE (meta) == get_identifier("OBJC2META"))
2291     ocs = darwin_objc2_section (decl, meta, ocs);
2292   else
2293     ocs = darwin_objc1_section (decl, meta, ocs);
2294 
2295   switch_to_section (ocs);
2296 
2297   /* We shall declare that zero-sized meta-data are not valid (yet).  */
2298   gcc_assert (size);
2299   fprintf (fp, "\t.align\t%d\n", floor_log2 (align / BITS_PER_UNIT));
2300 
2301   /* ... and we let it deal with outputting one byte of zero for them too.  */
2302   darwin_asm_declare_object_name (fp, name, decl);
2303   assemble_zeros (size);
2304 }
2305 
2306 /* This routine emits 'local' storage:
2307 
2308    When Section Anchors are off this routine emits .zerofill commands in
2309    sections named for their alignment.
2310 
2311    When Section Anchors are on, smaller (non-zero-sized) items are placed in
2312    the .static_data section so that the section anchoring system can see them.
2313    Larger items are still placed in .zerofill sections, addressing PR33210.
2314    The routine has no checking - it is all assumed to be done by the caller.
2315 */
2316 static void
darwin_emit_local_bss(FILE * fp,tree decl,const char * name,unsigned HOST_WIDE_INT size,unsigned int l2align)2317 darwin_emit_local_bss (FILE *fp, tree decl, const char *name,
2318 			unsigned HOST_WIDE_INT size,
2319 			unsigned int l2align)
2320 {
2321    /* FIXME: We have a fudge to make this work with Java even when the target does
2322    not use sections anchors -- Java seems to need at least one small item in a
2323    non-zerofill segment.   */
2324    if ((DARWIN_SECTION_ANCHORS && flag_section_anchors && size < BYTES_ZFILL)
2325        || (size && size <= 2))
2326     {
2327       /* Put smaller objects in _static_data, where the section anchors system
2328 	 can get them.
2329 	 However, if they are zero-sized punt them to yet a different section
2330 	 (that is not allowed to participate in anchoring).  */
2331       if (!size)
2332 	{
2333 	  fputs ("\t.section\t__DATA,__zobj_bss\n", fp);
2334 	  in_section = darwin_sections[zobj_bss_section];
2335 	  size = 1;
2336 	}
2337       else
2338 	{
2339 	  fputs ("\t.static_data\n", fp);
2340 	  in_section = darwin_sections[static_data_section];
2341 	}
2342 
2343       if (l2align)
2344 	fprintf (fp, "\t.align\t%u\n", l2align);
2345 
2346       assemble_name (fp, name);
2347       fprintf (fp, ":\n\t.space\t" HOST_WIDE_INT_PRINT_UNSIGNED"\n", size);
2348     }
2349   else
2350     {
2351       /* When we are on a non-section anchor target, we can get zero-sized
2352 	 items here.  However, all we need to do is to bump them to one byte
2353 	 and the section alignment will take care of the rest.  */
2354       char secnam[64];
2355       unsigned int flags ;
2356       snprintf (secnam, 64, "__DATA,__%sbss%u", ((size)?"":"zo_"),
2357 						(unsigned) l2align);
2358       /* We can't anchor (yet, if ever) in zerofill sections, because we can't
2359 	 switch to them and emit a label.  */
2360       flags = SECTION_BSS|SECTION_WRITE|SECTION_NO_ANCHOR;
2361       in_section = get_section (secnam, flags, NULL);
2362       fprintf (fp, "\t.zerofill %s,", secnam);
2363       assemble_name (fp, name);
2364       if (!size)
2365 	size = 1;
2366 
2367       if (l2align)
2368 	fprintf (fp, "," HOST_WIDE_INT_PRINT_UNSIGNED",%u\n",
2369 		 size, (unsigned) l2align);
2370       else
2371 	fprintf (fp, "," HOST_WIDE_INT_PRINT_UNSIGNED"\n", size);
2372     }
2373 
2374   (*targetm.encode_section_info) (decl, DECL_RTL (decl), false);
2375   /* This is defined as a file-scope var, so we know to notify machopic.  */
2376   machopic_define_symbol (DECL_RTL (decl));
2377 }
2378 
2379 /* Emit a chunk of common.  */
2380 static void
darwin_emit_common(FILE * fp,const char * name,unsigned HOST_WIDE_INT size,unsigned int align)2381 darwin_emit_common (FILE *fp, const char *name,
2382 		    unsigned HOST_WIDE_INT size, unsigned int align)
2383 {
2384   unsigned HOST_WIDE_INT rounded;
2385   unsigned int l2align;
2386 
2387   /* Earlier systems complain if the alignment exceeds the page size.
2388      The magic number is 4096 * 8 - hard-coded for legacy systems.  */
2389   if (!emit_aligned_common && (align > 32768UL))
2390     align = 4096UL; /* In units.  */
2391   else
2392     align /= BITS_PER_UNIT;
2393 
2394   /* Make sure we have a meaningful align.  */
2395   if (!align)
2396     align = 1;
2397 
2398   /* For earlier toolchains, we need to emit the var as a rounded size to
2399      tell ld the alignment.  */
2400   if (size < align)
2401     rounded = align;
2402   else
2403     rounded = (size + (align-1)) & ~(align-1);
2404 
2405   l2align = floor_log2 (align);
2406   gcc_assert (l2align <= L2_MAX_OFILE_ALIGNMENT);
2407 
2408   in_section = comm_section;
2409   /* We mustn't allow multiple public symbols to share an address when using
2410      the normal OSX toolchain.  */
2411   if (!size)
2412     {
2413       /* Put at least one byte.  */
2414       size = 1;
2415       /* This section can no longer participate in section anchoring.  */
2416       comm_section->common.flags |= SECTION_NO_ANCHOR;
2417     }
2418 
2419   fputs ("\t.comm\t", fp);
2420   assemble_name (fp, name);
2421   fprintf (fp, "," HOST_WIDE_INT_PRINT_UNSIGNED,
2422 	   emit_aligned_common?size:rounded);
2423   if (l2align && emit_aligned_common)
2424     fprintf (fp, ",%u", l2align);
2425   fputs ("\n", fp);
2426 }
2427 
2428 /* Output a var which is all zero - into aligned BSS sections, common, lcomm
2429    or coalescable data sections (for weak or comdat) as appropriate.  */
2430 
2431 void
darwin_output_aligned_bss(FILE * fp,tree decl,const char * name,unsigned HOST_WIDE_INT size,unsigned int align)2432 darwin_output_aligned_bss (FILE *fp, tree decl, const char *name,
2433 			  unsigned HOST_WIDE_INT size, unsigned int align)
2434 {
2435   unsigned int l2align;
2436   bool one, pub, weak;
2437   tree meta;
2438 
2439   pub = TREE_PUBLIC (decl);
2440   one = DECL_ONE_ONLY (decl);
2441   weak = (DECL_P (decl)
2442 	  && DECL_WEAK (decl)
2443 	  && !lookup_attribute ("weak_import",
2444 				 DECL_ATTRIBUTES (decl)));
2445 
2446 #ifdef DEBUG_DARWIN_MEM_ALLOCATORS
2447 fprintf (fp, "# albss: %s (%lld,%d) ro %d cst %d stat %d com %d"
2448 	     " pub %d weak %d one %d init %lx\n",
2449 	name, (long long)size, (int)align, TREE_READONLY (decl),
2450 	TREE_CONSTANT (decl), TREE_STATIC (decl), DECL_COMMON (decl),
2451 	pub, weak, one, (unsigned long)DECL_INITIAL (decl));
2452 #endif
2453 
2454   /* ObjC metadata can get put in BSS because varasm.c decides it's BSS
2455      before the target has a chance to comment.  */
2456   if ((meta = is_objc_metadata (decl)))
2457     {
2458       darwin_emit_objc_zeroed (fp, decl, name, size, DECL_ALIGN (decl), meta);
2459       return;
2460     }
2461 
2462   /* Check that any initializer is valid.  */
2463   gcc_assert ((DECL_INITIAL (decl) == NULL)
2464 	       || (DECL_INITIAL (decl) == error_mark_node)
2465 	       || initializer_zerop (DECL_INITIAL (decl)));
2466 
2467   gcc_assert (DECL_SECTION_NAME (decl) == NULL);
2468   gcc_assert (!DECL_COMMON (decl));
2469 
2470   /*  Pick up the correct alignment.  */
2471   if (!size || !align)
2472     align = DECL_ALIGN (decl);
2473 
2474   l2align = floor_log2 (align / BITS_PER_UNIT);
2475   gcc_assert (l2align <= L2_MAX_OFILE_ALIGNMENT);
2476 
2477   last_assemble_variable_decl = decl;
2478 
2479   /* We would rather not have to check this here - but it seems that we might
2480      be passed a decl that should be in coalesced space.  */
2481   if (one || weak)
2482     {
2483       /* Weak or COMDAT objects are put in mergeable sections.  */
2484       darwin_emit_weak_or_comdat (fp, decl, name, size,
2485 					DECL_ALIGN (decl));
2486       return;
2487     }
2488 
2489   /* If this is not public, then emit according to local rules.  */
2490   if (!pub)
2491     {
2492       darwin_emit_local_bss (fp, decl, name, size, l2align);
2493       return;
2494     }
2495 
2496   /* So we have a public symbol (small item fudge for Java, see above).  */
2497   if ((DARWIN_SECTION_ANCHORS && flag_section_anchors && size < BYTES_ZFILL)
2498        || (size && size <= 2))
2499     {
2500       /* Put smaller objects in data, where the section anchors system can get
2501 	 them.  However, if they are zero-sized punt them to yet a different
2502 	 section (that is not allowed to participate in anchoring).  */
2503       if (!size)
2504 	{
2505 	  fputs ("\t.section\t__DATA,__zobj_data\n", fp);
2506 	  in_section = darwin_sections[zobj_data_section];
2507 	  size = 1;
2508 	}
2509       else
2510 	{
2511 	  fputs ("\t.data\n", fp);
2512 	  in_section = data_section;
2513 	}
2514 
2515       if (l2align)
2516 	fprintf (fp, "\t.align\t%u\n", l2align);
2517 
2518       assemble_name (fp, name);
2519       fprintf (fp, ":\n\t.space\t" HOST_WIDE_INT_PRINT_UNSIGNED"\n", size);
2520     }
2521   else
2522     {
2523       char secnam[64];
2524       unsigned int flags ;
2525       /* When we are on a non-section anchor target, we can get zero-sized
2526 	 items here.  However, all we need to do is to bump them to one byte
2527 	 and the section alignment will take care of the rest.  */
2528       snprintf (secnam, 64, "__DATA,__%spu_bss%u", ((size)?"":"zo_"), l2align);
2529 
2530       /* We can't anchor in zerofill sections, because we can't switch
2531 	 to them and emit a label.  */
2532       flags = SECTION_BSS|SECTION_WRITE|SECTION_NO_ANCHOR;
2533       in_section = get_section (secnam, flags, NULL);
2534       fprintf (fp, "\t.zerofill %s,", secnam);
2535       assemble_name (fp, name);
2536       if (!size)
2537 	size = 1;
2538 
2539       if (l2align)
2540 	fprintf (fp, "," HOST_WIDE_INT_PRINT_UNSIGNED",%u\n", size, l2align);
2541       else
2542 	fprintf (fp, "," HOST_WIDE_INT_PRINT_UNSIGNED"\n", size);
2543     }
2544   (* targetm.encode_section_info) (decl, DECL_RTL (decl), false);
2545 }
2546 
2547 /* Output a chunk of common, with alignment specified (where the target
2548    supports this).  */
2549 void
darwin_asm_output_aligned_decl_common(FILE * fp,tree decl,const char * name,unsigned HOST_WIDE_INT size,unsigned int align)2550 darwin_asm_output_aligned_decl_common (FILE *fp, tree decl, const char *name,
2551 				       unsigned HOST_WIDE_INT size,
2552 				       unsigned int align)
2553 {
2554   unsigned int l2align;
2555   bool one, weak;
2556   tree meta;
2557 
2558   /* No corresponding var.  */
2559   if (decl==NULL)
2560     {
2561 #ifdef DEBUG_DARWIN_MEM_ALLOCATORS
2562 fprintf (fp, "# adcom: %s (%d,%d) decl=0x0\n", name, (int)size, (int)align);
2563 #endif
2564       darwin_emit_common (fp, name, size, align);
2565       return;
2566     }
2567 
2568   one = DECL_ONE_ONLY (decl);
2569   weak = (DECL_P (decl)
2570 	  && DECL_WEAK (decl)
2571 	  && !lookup_attribute ("weak_import",
2572 				 DECL_ATTRIBUTES (decl)));
2573 
2574 #ifdef DEBUG_DARWIN_MEM_ALLOCATORS
2575 fprintf (fp, "# adcom: %s (%lld,%d) ro %d cst %d stat %d com %d pub %d"
2576 	     " weak %d one %d init %lx\n",
2577 	name,  (long long)size, (int)align, TREE_READONLY (decl),
2578 	TREE_CONSTANT (decl), TREE_STATIC (decl), DECL_COMMON (decl),
2579 	TREE_PUBLIC (decl), weak, one, (unsigned long)DECL_INITIAL (decl));
2580 #endif
2581 
2582   /* ObjC metadata can get put in BSS because varasm.c decides it's BSS
2583      before the target has a chance to comment.  */
2584   if ((meta = is_objc_metadata (decl)))
2585     {
2586       darwin_emit_objc_zeroed (fp, decl, name, size, DECL_ALIGN (decl), meta);
2587       return;
2588     }
2589 
2590   /* We shouldn't be messing with this if the decl has a section name.  */
2591   gcc_assert (DECL_SECTION_NAME (decl) == NULL);
2592 
2593   /* We would rather not have to check this here - but it seems that we might
2594      be passed a decl that should be in coalesced space.  */
2595   if (one || weak)
2596     {
2597       /* Weak or COMDAT objects are put in mergable sections.  */
2598       darwin_emit_weak_or_comdat (fp, decl, name, size,
2599 					DECL_ALIGN (decl));
2600       return;
2601     }
2602 
2603   /* We should only get here for DECL_COMMON, with a zero init (and, in
2604      principle, only for public symbols too - although we deal with local
2605      ones below).  */
2606 
2607   /* Check the initializer is OK.  */
2608   gcc_assert (DECL_COMMON (decl)
2609 	      && ((DECL_INITIAL (decl) == NULL)
2610 	       || (DECL_INITIAL (decl) == error_mark_node)
2611 	       || initializer_zerop (DECL_INITIAL (decl))));
2612 
2613   last_assemble_variable_decl = decl;
2614 
2615   if (!size || !align)
2616     align = DECL_ALIGN (decl);
2617 
2618   l2align = floor_log2 (align / BITS_PER_UNIT);
2619   /* Check we aren't asking for more aligment than the platform allows.  */
2620   gcc_assert (l2align <= L2_MAX_OFILE_ALIGNMENT);
2621 
2622   if (TREE_PUBLIC (decl) != 0)
2623     darwin_emit_common (fp, name, size, align);
2624   else
2625     darwin_emit_local_bss (fp, decl, name, size, l2align);
2626 }
2627 
2628 /* Output a chunk of BSS with alignment specfied.  */
2629 void
darwin_asm_output_aligned_decl_local(FILE * fp,tree decl,const char * name,unsigned HOST_WIDE_INT size,unsigned int align)2630 darwin_asm_output_aligned_decl_local (FILE *fp, tree decl, const char *name,
2631 				      unsigned HOST_WIDE_INT size,
2632 				      unsigned int align)
2633 {
2634   unsigned long l2align;
2635   bool one, weak;
2636   tree meta;
2637 
2638   one = DECL_ONE_ONLY (decl);
2639   weak = (DECL_P (decl)
2640 	  && DECL_WEAK (decl)
2641 	  && !lookup_attribute ("weak_import",
2642 				 DECL_ATTRIBUTES (decl)));
2643 
2644 #ifdef DEBUG_DARWIN_MEM_ALLOCATORS
2645 fprintf (fp, "# adloc: %s (%lld,%d) ro %d cst %d stat %d one %d pub %d"
2646 	     " weak %d init %lx\n",
2647 	name, (long long)size, (int)align, TREE_READONLY (decl),
2648 	TREE_CONSTANT (decl), TREE_STATIC (decl), one, TREE_PUBLIC (decl),
2649 	weak , (unsigned long)DECL_INITIAL (decl));
2650 #endif
2651 
2652   /* ObjC metadata can get put in BSS because varasm.c decides it's BSS
2653      before the target has a chance to comment.  */
2654   if ((meta = is_objc_metadata (decl)))
2655     {
2656       darwin_emit_objc_zeroed (fp, decl, name, size, DECL_ALIGN (decl), meta);
2657       return;
2658     }
2659 
2660   /* We shouldn't be messing with this if the decl has a section name.  */
2661   gcc_assert (DECL_SECTION_NAME (decl) == NULL);
2662 
2663   /* We would rather not have to check this here - but it seems that we might
2664      be passed a decl that should be in coalesced space.  */
2665   if (one || weak)
2666     {
2667       /* Weak or COMDAT objects are put in mergable sections.  */
2668       darwin_emit_weak_or_comdat (fp, decl, name, size,
2669 					DECL_ALIGN (decl));
2670       return;
2671     }
2672 
2673   /* .. and it should be suitable for placement in local mem.  */
2674   gcc_assert(!TREE_PUBLIC (decl) && !DECL_COMMON (decl));
2675   /* .. and any initializer must be all-zero.  */
2676   gcc_assert ((DECL_INITIAL (decl) == NULL)
2677 	       || (DECL_INITIAL (decl) == error_mark_node)
2678 	       || initializer_zerop (DECL_INITIAL (decl)));
2679 
2680   last_assemble_variable_decl = decl;
2681 
2682   if (!size || !align)
2683     align = DECL_ALIGN (decl);
2684 
2685   l2align = floor_log2 (align / BITS_PER_UNIT);
2686   gcc_assert (l2align <= L2_MAX_OFILE_ALIGNMENT);
2687 
2688   darwin_emit_local_bss (fp, decl, name, size, l2align);
2689 }
2690 
2691 /* Emit an assembler directive to set visibility for a symbol.  The
2692    only supported visibilities are VISIBILITY_DEFAULT and
2693    VISIBILITY_HIDDEN; the latter corresponds to Darwin's "private
2694    extern".  There is no MACH-O equivalent of ELF's
2695    VISIBILITY_INTERNAL or VISIBILITY_PROTECTED. */
2696 
2697 void
darwin_assemble_visibility(tree decl,int vis)2698 darwin_assemble_visibility (tree decl, int vis)
2699 {
2700   if (vis == VISIBILITY_DEFAULT)
2701     ;
2702   else if (vis == VISIBILITY_HIDDEN || vis == VISIBILITY_INTERNAL)
2703     {
2704       fputs ("\t.private_extern ", asm_out_file);
2705       assemble_name (asm_out_file,
2706 		     (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl))));
2707       fputs ("\n", asm_out_file);
2708     }
2709   else
2710     warning (OPT_Wattributes, "protected visibility attribute "
2711 	     "not supported in this configuration; ignored");
2712 }
2713 
2714 /* vec used by darwin_asm_dwarf_section.
2715    Maybe a hash tab would be better here - but the intention is that this is
2716    a very short list (fewer than 16 items) and each entry should (ideally,
2717    eventually) only be presented once.
2718 
2719    A structure to hold a dwarf debug section used entry.  */
2720 
2721 typedef struct GTY(()) dwarf_sect_used_entry {
2722   const char *name;
2723   unsigned count;
2724 }
2725 dwarf_sect_used_entry;
2726 
2727 
2728 /* A list of used __DWARF sections.  */
2729 static GTY (()) vec<dwarf_sect_used_entry, va_gc> *dwarf_sect_names_table;
2730 
2731 /* This is called when we are asked to assemble a named section and the
2732    name begins with __DWARF,.  We keep a list of the section names (without
2733    the __DWARF, prefix) and use this to emit our required start label on the
2734    first switch to each section.  */
2735 
2736 static void
darwin_asm_dwarf_section(const char * name,unsigned int flags,tree ARG_UNUSED (decl))2737 darwin_asm_dwarf_section (const char *name, unsigned int flags,
2738 			  tree ARG_UNUSED (decl))
2739 {
2740   unsigned i;
2741   int namelen;
2742   const char * sname;
2743   dwarf_sect_used_entry *ref;
2744   bool found = false;
2745   gcc_assert ((flags & (SECTION_DEBUG | SECTION_NAMED))
2746 		    == (SECTION_DEBUG | SECTION_NAMED));
2747   /* We know that the name starts with __DWARF,  */
2748   sname = name + 8;
2749   namelen = strchr (sname, ',') - sname;
2750   gcc_assert (namelen);
2751   if (dwarf_sect_names_table == NULL)
2752     vec_alloc (dwarf_sect_names_table, 16);
2753   else
2754     for (i = 0;
2755 	 dwarf_sect_names_table->iterate (i, &ref);
2756 	 i++)
2757       {
2758 	if (!ref)
2759 	  break;
2760 	if (!strcmp (ref->name, sname))
2761 	  {
2762 	    found = true;
2763 	    ref->count++;
2764 	    break;
2765 	  }
2766       }
2767 
2768   fprintf (asm_out_file, "\t.section %s\n", name);
2769   if (!found)
2770     {
2771       dwarf_sect_used_entry e;
2772       fprintf (asm_out_file, "Lsection%.*s:\n", namelen, sname);
2773       e.count = 1;
2774       e.name = xstrdup (sname);
2775       vec_safe_push (dwarf_sect_names_table, e);
2776     }
2777 }
2778 
2779 /* Output a difference of two labels that will be an assembly time
2780    constant if the two labels are local.  (.long lab1-lab2 will be
2781    very different if lab1 is at the boundary between two sections; it
2782    will be relocated according to the second section, not the first,
2783    so one ends up with a difference between labels in different
2784    sections, which is bad in the dwarf2 eh context for instance.)  */
2785 
2786 static int darwin_dwarf_label_counter;
2787 
2788 void
darwin_asm_output_dwarf_delta(FILE * file,int size,const char * lab1,const char * lab2)2789 darwin_asm_output_dwarf_delta (FILE *file, int size,
2790 			       const char *lab1, const char *lab2)
2791 {
2792   int islocaldiff = (lab1[0] == '*' && lab1[1] == 'L'
2793 		     && lab2[0] == '*' && lab2[1] == 'L');
2794   const char *directive = (size == 8 ? ".quad" : ".long");
2795 
2796   if (islocaldiff)
2797     fprintf (file, "\t.set L$set$%d,", darwin_dwarf_label_counter);
2798   else
2799     fprintf (file, "\t%s\t", directive);
2800 
2801   assemble_name_raw (file, lab1);
2802   fprintf (file, "-");
2803   assemble_name_raw (file, lab2);
2804   if (islocaldiff)
2805     fprintf (file, "\n\t%s L$set$%d", directive, darwin_dwarf_label_counter++);
2806 }
2807 
2808 /* Output an offset in a DWARF section on Darwin.  On Darwin, DWARF section
2809    offsets are not represented using relocs in .o files; either the
2810    section never leaves the .o file, or the linker or other tool is
2811    responsible for parsing the DWARF and updating the offsets.  */
2812 
2813 void
darwin_asm_output_dwarf_offset(FILE * file,int size,const char * lab,section * base)2814 darwin_asm_output_dwarf_offset (FILE *file, int size, const char * lab,
2815 				section *base)
2816 {
2817   char sname[64];
2818   int namelen;
2819 
2820   gcc_assert (base->common.flags & SECTION_NAMED);
2821   gcc_assert (strncmp (base->named.name, "__DWARF,", 8) == 0);
2822   gcc_assert (strchr (base->named.name + 8, ','));
2823 
2824   namelen = strchr (base->named.name + 8, ',') - (base->named.name + 8);
2825   sprintf (sname, "*Lsection%.*s", namelen, base->named.name + 8);
2826   darwin_asm_output_dwarf_delta (file, size, lab, sname);
2827 }
2828 
2829 /* Called from the within the TARGET_ASM_FILE_START for each target.  */
2830 
2831 void
darwin_file_start(void)2832 darwin_file_start (void)
2833 {
2834   /* Nothing to do.  */
2835 }
2836 
2837 /* Called for the TARGET_ASM_FILE_END hook.
2838    Emit the mach-o pic indirection data, the lto data and, finally a flag
2839    to tell the linker that it can break the file object into sections and
2840    move those around for efficiency.  */
2841 
2842 void
darwin_file_end(void)2843 darwin_file_end (void)
2844 {
2845   if (!vec_safe_is_empty (ctors))
2846     finalize_ctors ();
2847   if (!vec_safe_is_empty (dtors))
2848     finalize_dtors ();
2849 
2850   /* If we are expecting to output NeXT ObjC meta-data, (and we actually see
2851      some) then we output the fix-and-continue marker (Image Info).
2852      This applies to Objective C, Objective C++ and LTO with either language
2853      as part of the input.  */
2854   if (flag_next_runtime && objc_metadata_seen)
2855     {
2856       unsigned int flags = 0;
2857       if (flag_objc_abi >= 2)
2858 	{
2859 	  flags = 16;
2860 	  output_section_asm_op
2861 	    (darwin_sections[objc2_image_info_section]->unnamed.data);
2862 	}
2863       else
2864 	output_section_asm_op
2865 	  (darwin_sections[objc_image_info_section]->unnamed.data);
2866 
2867       ASM_OUTPUT_ALIGN (asm_out_file, 2);
2868       fputs ("L_OBJC_ImageInfo:\n", asm_out_file);
2869 
2870       flags |= (flag_replace_objc_classes && classes_seen) ? 1 : 0;
2871       flags |= flag_objc_gc ? 2 : 0;
2872 
2873       fprintf (asm_out_file, "\t.long\t0\n\t.long\t%u\n", flags);
2874      }
2875 
2876   machopic_finish (asm_out_file);
2877   if (strcmp (lang_hooks.name, "GNU C++") == 0)
2878     {
2879       switch_to_section (darwin_sections[constructor_section]);
2880       switch_to_section (darwin_sections[destructor_section]);
2881       ASM_OUTPUT_ALIGN (asm_out_file, 1);
2882     }
2883 
2884   /* If there was LTO assembler output, append it to asm_out_file.  */
2885   if (lto_asm_out_name)
2886     {
2887       int n;
2888       char *buf, *lto_asm_txt;
2889 
2890       /* Shouldn't be here if we failed to switch back.  */
2891       gcc_assert (! saved_asm_out_file);
2892 
2893       lto_asm_out_file = fopen (lto_asm_out_name, "r");
2894       if (lto_asm_out_file == NULL)
2895 	fatal_error ("failed to open temporary file %s with LTO output",
2896 		     lto_asm_out_name);
2897       fseek (lto_asm_out_file, 0, SEEK_END);
2898       n = ftell (lto_asm_out_file);
2899       if (n > 0)
2900         {
2901 	  fseek (lto_asm_out_file, 0, SEEK_SET);
2902 	  lto_asm_txt = buf = (char *) xmalloc (n + 1);
2903 	  while (fgets (lto_asm_txt, n, lto_asm_out_file))
2904 	    fputs (lto_asm_txt, asm_out_file);
2905 	  /* Put a termination label.  */
2906 	  fprintf (asm_out_file, "\t.section %s,%s,regular,debug\n",
2907 		   LTO_SEGMENT_NAME, LTO_SECTS_SECTION);
2908 	  fprintf (asm_out_file, "L_GNU_LTO%d:\t;# end of lto\n",
2909 		   lto_section_num);
2910 	  /* Make sure our termination label stays in this section.  */
2911 	  fputs ("\t.space\t1\n", asm_out_file);
2912 	}
2913 
2914       /* Remove the temporary file.  */
2915       fclose (lto_asm_out_file);
2916       unlink_if_ordinary (lto_asm_out_name);
2917       free (lto_asm_out_name);
2918     }
2919 
2920   /* Output the names and indices.  */
2921   if (lto_section_names && lto_section_names->length ())
2922     {
2923       int count;
2924       darwin_lto_section_e *ref;
2925       /* For now, we'll make the offsets 4 bytes and unaligned - we'll fix
2926          the latter up ourselves.  */
2927       const char *op = integer_asm_op (4,0);
2928 
2929       /* Emit the names.  */
2930       fprintf (asm_out_file, "\t.section %s,%s,regular,debug\n",
2931 	       LTO_SEGMENT_NAME, LTO_NAMES_SECTION);
2932       FOR_EACH_VEC_ELT (*lto_section_names, count, ref)
2933 	{
2934 	  fprintf (asm_out_file, "L_GNU_LTO_NAME%d:\n", count);
2935          /* We have to jump through hoops to get the values of the intra-section
2936             offsets... */
2937 	  fprintf (asm_out_file,
2938 		   "\t.set L$gnu$lto$noff%d,L_GNU_LTO_NAME%d-L_GNU_LTO_NAME0\n",
2939 		   count, count);
2940 	  fprintf (asm_out_file,
2941 		   "\t.set L$gnu$lto$nsiz%d,L_GNU_LTO_NAME%d-L_GNU_LTO_NAME%d\n",
2942 		   count, count+1, count);
2943 	  fprintf (asm_out_file, "\t.asciz\t\"%s\"\n", ref->sectname);
2944 	}
2945       fprintf (asm_out_file, "L_GNU_LTO_NAME%d:\t;# end\n", lto_section_num);
2946       /* make sure our termination label stays in this section.  */
2947       fputs ("\t.space\t1\n", asm_out_file);
2948 
2949       /* Emit the Index.  */
2950       fprintf (asm_out_file, "\t.section %s,%s,regular,debug\n",
2951 	       LTO_SEGMENT_NAME, LTO_INDEX_SECTION);
2952       fputs ("\t.align\t2\n", asm_out_file);
2953       fputs ("# Section offset, Section length, Name offset, Name length\n",
2954 	     asm_out_file);
2955       FOR_EACH_VEC_ELT (*lto_section_names, count, ref)
2956 	{
2957 	  fprintf (asm_out_file, "%s L$gnu$lto$offs%d\t;# %s\n",
2958 		   op, count, ref->sectname);
2959 	  fprintf (asm_out_file, "%s L$gnu$lto$size%d\n", op, count);
2960 	  fprintf (asm_out_file, "%s L$gnu$lto$noff%d\n", op, count);
2961 	  fprintf (asm_out_file, "%s L$gnu$lto$nsiz%d\n", op, count);
2962 	}
2963     }
2964 
2965   /* If we have section anchors, then we must prevent the linker from
2966      re-arranging data.  */
2967   if (!DARWIN_SECTION_ANCHORS || !flag_section_anchors)
2968     fprintf (asm_out_file, "\t.subsections_via_symbols\n");
2969 }
2970 
2971 /* TODO: Add a language hook for identifying if a decl is a vtable.  */
2972 #define DARWIN_VTABLE_P(DECL) 0
2973 
2974 /* Cross-module name binding.  Darwin does not support overriding
2975    functions at dynamic-link time, except for vtables in kexts.  */
2976 
2977 bool
darwin_binds_local_p(const_tree decl)2978 darwin_binds_local_p (const_tree decl)
2979 {
2980   return default_binds_local_p_1 (decl,
2981 				  TARGET_KEXTABI && DARWIN_VTABLE_P (decl));
2982 }
2983 
2984 /* The Darwin's implementation of TARGET_ASM_OUTPUT_ANCHOR.  Define the
2985    anchor relative to ".", the current section position.  We cannot use
2986    the default one because ASM_OUTPUT_DEF is wrong for Darwin.  */
2987 void
darwin_asm_output_anchor(rtx symbol)2988 darwin_asm_output_anchor (rtx symbol)
2989 {
2990   fprintf (asm_out_file, "\t.set\t");
2991   assemble_name (asm_out_file, XSTR (symbol, 0));
2992   fprintf (asm_out_file, ", . + " HOST_WIDE_INT_PRINT_DEC "\n",
2993 	   SYMBOL_REF_BLOCK_OFFSET (symbol));
2994 }
2995 
2996 /* Disable section anchoring on any section containing a zero-sized
2997    object.  */
2998 bool
darwin_use_anchors_for_symbol_p(const_rtx symbol)2999 darwin_use_anchors_for_symbol_p (const_rtx symbol)
3000 {
3001   if (DARWIN_SECTION_ANCHORS && flag_section_anchors)
3002     {
3003       section *sect;
3004       /* If the section contains a zero-sized object it's ineligible.  */
3005       sect = SYMBOL_REF_BLOCK (symbol)->sect;
3006       /* This should have the effect of disabling anchors for vars that follow
3007          any zero-sized one, in a given section.  */
3008       if (sect->common.flags & SECTION_NO_ANCHOR)
3009 	return false;
3010 
3011         /* Also check the normal reasons for suppressing.  */
3012         return default_use_anchors_for_symbol_p (symbol);
3013     }
3014   else
3015     return false;
3016 }
3017 
3018 /* Set the darwin specific attributes on TYPE.  */
3019 void
darwin_set_default_type_attributes(tree type)3020 darwin_set_default_type_attributes (tree type)
3021 {
3022   if (darwin_ms_struct
3023       && TREE_CODE (type) == RECORD_TYPE)
3024     TYPE_ATTRIBUTES (type) = tree_cons (get_identifier ("ms_struct"),
3025                                         NULL_TREE,
3026                                         TYPE_ATTRIBUTES (type));
3027 }
3028 
3029 /* True, iff we're generating code for loadable kernel extensions.  */
3030 
3031 bool
darwin_kextabi_p(void)3032 darwin_kextabi_p (void) {
3033   return flag_apple_kext;
3034 }
3035 
3036 void
darwin_override_options(void)3037 darwin_override_options (void)
3038 {
3039   /* Keep track of which (major) version we're generating code for.  */
3040   if (darwin_macosx_version_min)
3041     {
3042       if (strverscmp (darwin_macosx_version_min, "10.6") >= 0)
3043 	generating_for_darwin_version = 10;
3044       else if (strverscmp (darwin_macosx_version_min, "10.5") >= 0)
3045 	generating_for_darwin_version = 9;
3046 
3047       /* Earlier versions are not specifically accounted, until required.  */
3048     }
3049 
3050   /* In principle, this should be c-family only.  However, we really need to
3051      set sensible defaults for LTO as well, since the section selection stuff
3052      should check for correctness re. the ABI.  TODO: check and provide the
3053      flags (runtime & ABI) from the lto wrapper).  */
3054 
3055   /* Unless set, force ABI=2 for NeXT and m64, 0 otherwise.  */
3056   if (!global_options_set.x_flag_objc_abi)
3057     global_options.x_flag_objc_abi
3058 	= (!flag_next_runtime)
3059 		? 0
3060 		: (TARGET_64BIT ? 2
3061 				: (generating_for_darwin_version >= 9) ? 1
3062 								       : 0);
3063 
3064   /* Objective-C family ABI 2 is only valid for next/m64 at present.  */
3065   if (global_options_set.x_flag_objc_abi && flag_next_runtime)
3066     {
3067       if (TARGET_64BIT && global_options.x_flag_objc_abi < 2)
3068 	error_at (UNKNOWN_LOCATION, "%<-fobjc-abi-version%> >= 2 must be"
3069 				    " used for %<-m64%> targets with"
3070 				    " %<-fnext-runtime%>");
3071       if (!TARGET_64BIT && global_options.x_flag_objc_abi >= 2)
3072 	error_at (UNKNOWN_LOCATION, "%<-fobjc-abi-version%> >= 2 is not"
3073 				    " supported on %<-m32%> targets with"
3074 				    " %<-fnext-runtime%>");
3075     }
3076 
3077   /* Don't emit DWARF3/4 unless specifically selected.  This is a
3078      workaround for tool bugs.  */
3079   if (!global_options_set.x_dwarf_strict)
3080     dwarf_strict = 1;
3081   if (!global_options_set.x_dwarf_version)
3082     dwarf_version = 2;
3083 
3084   /* Do not allow unwind tables to be generated by default for m32.
3085      fnon-call-exceptions will override this, regardless of what we do.  */
3086   if (generating_for_darwin_version < 10
3087       && !global_options_set.x_flag_asynchronous_unwind_tables
3088       && !TARGET_64BIT)
3089     global_options.x_flag_asynchronous_unwind_tables = 0;
3090 
3091    /* Disable -freorder-blocks-and-partition when unwind tables are being
3092       emitted for Darwin < 9 (OSX 10.5).
3093       The strategy is, "Unless the User has specifically set/unset an unwind
3094       flag we will switch off -freorder-blocks-and-partition when unwind tables
3095       will be generated".  If the User specifically sets flags... we assume
3096       (s)he knows why...  */
3097    if (generating_for_darwin_version < 9
3098        && global_options_set.x_flag_reorder_blocks_and_partition
3099        && ((global_options.x_flag_exceptions 		/* User, c++, java */
3100 	    && !global_options_set.x_flag_exceptions) 	/* User specified... */
3101 	   || (global_options.x_flag_unwind_tables
3102 	       && !global_options_set.x_flag_unwind_tables)
3103 	   || (global_options.x_flag_non_call_exceptions
3104 	       && !global_options_set.x_flag_non_call_exceptions)
3105 	   || (global_options.x_flag_asynchronous_unwind_tables
3106 	       && !global_options_set.x_flag_asynchronous_unwind_tables)))
3107     {
3108       inform (input_location,
3109 	      "-freorder-blocks-and-partition does not work with exceptions "
3110 	      "on this architecture");
3111       flag_reorder_blocks_and_partition = 0;
3112       flag_reorder_blocks = 1;
3113     }
3114 
3115     /* FIXME: flag_objc_sjlj_exceptions is no longer needed since there is only
3116        one valid choice of exception scheme for each runtime.  */
3117     if (!global_options_set.x_flag_objc_sjlj_exceptions)
3118       global_options.x_flag_objc_sjlj_exceptions =
3119 				flag_next_runtime && !TARGET_64BIT;
3120 
3121     /* FIXME: and this could be eliminated then too.  */
3122     if (!global_options_set.x_flag_exceptions
3123 	&& flag_objc_exceptions
3124 	&& TARGET_64BIT)
3125       flag_exceptions = 1;
3126 
3127   if (flag_mkernel || flag_apple_kext)
3128     {
3129       /* -mkernel implies -fapple-kext for C++ */
3130       if (strcmp (lang_hooks.name, "GNU C++") == 0)
3131 	flag_apple_kext = 1;
3132 
3133       flag_no_common = 1;
3134 
3135       /* No EH in kexts.  */
3136       flag_exceptions = 0;
3137       /* No -fnon-call-exceptions data in kexts.  */
3138       flag_non_call_exceptions = 0;
3139       /* so no tables either.. */
3140       flag_unwind_tables = 0;
3141       flag_asynchronous_unwind_tables = 0;
3142       /* We still need to emit branch islands for kernel context.  */
3143       darwin_emit_branch_islands = true;
3144     }
3145 
3146   if (flag_var_tracking_uninit == 0
3147       && generating_for_darwin_version >= 9
3148       && (flag_gtoggle ? (debug_info_level == DINFO_LEVEL_NONE)
3149       : (debug_info_level >= DINFO_LEVEL_NORMAL))
3150       && write_symbols == DWARF2_DEBUG)
3151     flag_var_tracking_uninit = flag_var_tracking;
3152 
3153   if (MACHO_DYNAMIC_NO_PIC_P)
3154     {
3155       if (flag_pic)
3156 	warning_at (UNKNOWN_LOCATION, 0,
3157 		 "%<-mdynamic-no-pic%> overrides %<-fpic%>, %<-fPIC%>,"
3158 		 " %<-fpie%> or %<-fPIE%>");
3159       flag_pic = 0;
3160     }
3161   else if (flag_pic == 1)
3162     {
3163       /* Darwin's -fpic is -fPIC.  */
3164       flag_pic = 2;
3165     }
3166 
3167   /* It is assumed that branch island stubs are needed for earlier systems.  */
3168   if (generating_for_darwin_version < 9)
3169     darwin_emit_branch_islands = true;
3170   else
3171     emit_aligned_common = true; /* Later systems can support aligned common.  */
3172 
3173   /* The c_dialect...() macros are not available to us here.  */
3174   darwin_running_cxx = (strstr (lang_hooks.name, "C++") != 0);
3175 }
3176 
3177 #if DARWIN_PPC
3178 /* Add $LDBL128 suffix to long double builtins for ppc darwin.  */
3179 
3180 static void
darwin_patch_builtin(enum built_in_function fncode)3181 darwin_patch_builtin (enum built_in_function fncode)
3182 {
3183   tree fn = builtin_decl_explicit (fncode);
3184   tree sym;
3185   char *newname;
3186 
3187   if (!fn)
3188     return;
3189 
3190   sym = DECL_ASSEMBLER_NAME (fn);
3191   newname = ACONCAT (("_", IDENTIFIER_POINTER (sym), "$LDBL128", NULL));
3192 
3193   set_user_assembler_name (fn, newname);
3194 
3195   fn = builtin_decl_implicit (fncode);
3196   if (fn)
3197     set_user_assembler_name (fn, newname);
3198 }
3199 
3200 void
darwin_patch_builtins(void)3201 darwin_patch_builtins (void)
3202 {
3203   if (LONG_DOUBLE_TYPE_SIZE != 128)
3204     return;
3205 
3206 #define PATCH_BUILTIN(fncode) darwin_patch_builtin (fncode);
3207 #define PATCH_BUILTIN_NO64(fncode)		\
3208   if (!TARGET_64BIT)				\
3209     darwin_patch_builtin (fncode);
3210 #define PATCH_BUILTIN_VARIADIC(fncode)				  \
3211   if (!TARGET_64BIT						  \
3212       && (strverscmp (darwin_macosx_version_min, "10.3.9") >= 0)) \
3213     darwin_patch_builtin (fncode);
3214 #include "darwin-ppc-ldouble-patch.def"
3215 #undef PATCH_BUILTIN
3216 #undef PATCH_BUILTIN_NO64
3217 #undef PATCH_BUILTIN_VARIADIC
3218 }
3219 #endif
3220 
3221 /*  CFStrings implementation.  */
3222 static GTY(()) tree cfstring_class_reference = NULL_TREE;
3223 static GTY(()) tree cfstring_type_node = NULL_TREE;
3224 static GTY(()) tree ccfstring_type_node = NULL_TREE;
3225 static GTY(()) tree pccfstring_type_node = NULL_TREE;
3226 static GTY(()) tree pcint_type_node = NULL_TREE;
3227 static GTY(()) tree pcchar_type_node = NULL_TREE;
3228 
3229 static enum built_in_function darwin_builtin_cfstring;
3230 
3231 /* Store all constructed constant CFStrings in a hash table so that
3232    they get uniqued properly.  */
3233 
3234 typedef struct GTY (()) cfstring_descriptor {
3235   /* The string literal.  */
3236   tree literal;
3237   /* The resulting constant CFString.  */
3238   tree constructor;
3239 } cfstring_descriptor;
3240 
3241 static GTY ((param_is (struct cfstring_descriptor))) htab_t cfstring_htab;
3242 
3243 static hashval_t cfstring_hash (const void *);
3244 static int cfstring_eq (const void *, const void *);
3245 
3246 static tree
add_builtin_field_decl(tree type,const char * name,tree ** chain)3247 add_builtin_field_decl (tree type, const char *name, tree **chain)
3248 {
3249   tree field = build_decl (BUILTINS_LOCATION, FIELD_DECL,
3250 			    get_identifier (name), type);
3251 
3252   if (*chain != NULL)
3253     **chain = field;
3254   *chain = &DECL_CHAIN (field);
3255 
3256   return field;
3257 }
3258 
3259 tree
darwin_init_cfstring_builtins(unsigned builtin_cfstring)3260 darwin_init_cfstring_builtins (unsigned builtin_cfstring)
3261 {
3262   tree cfsfun, fields, pccfstring_ftype_pcchar;
3263   tree *chain = NULL;
3264 
3265   darwin_builtin_cfstring =
3266     (enum built_in_function) builtin_cfstring;
3267 
3268   /* struct __builtin_CFString {
3269        const int *isa;		(will point at
3270        int flags;		 __CFConstantStringClassReference)
3271        const char *str;
3272        long length;
3273      };  */
3274 
3275   pcint_type_node = build_pointer_type
3276 		   (build_qualified_type (integer_type_node, TYPE_QUAL_CONST));
3277 
3278   pcchar_type_node = build_pointer_type
3279 		   (build_qualified_type (char_type_node, TYPE_QUAL_CONST));
3280 
3281   cfstring_type_node = (*lang_hooks.types.make_type) (RECORD_TYPE);
3282 
3283   /* Have to build backwards for finish struct.  */
3284   fields = add_builtin_field_decl (long_integer_type_node, "length", &chain);
3285   add_builtin_field_decl (pcchar_type_node, "str", &chain);
3286   add_builtin_field_decl (integer_type_node, "flags", &chain);
3287   add_builtin_field_decl (pcint_type_node, "isa", &chain);
3288   finish_builtin_struct (cfstring_type_node, "__builtin_CFString",
3289 			 fields, NULL_TREE);
3290 
3291   /* const struct __builtin_CFstring *
3292      __builtin___CFStringMakeConstantString (const char *); */
3293 
3294   ccfstring_type_node = build_qualified_type
3295 			(cfstring_type_node, TYPE_QUAL_CONST);
3296   pccfstring_type_node = build_pointer_type (ccfstring_type_node);
3297   pccfstring_ftype_pcchar = build_function_type_list
3298 			(pccfstring_type_node, pcchar_type_node, NULL_TREE);
3299 
3300   cfsfun  = build_decl (BUILTINS_LOCATION, FUNCTION_DECL,
3301 			get_identifier ("__builtin___CFStringMakeConstantString"),
3302 			pccfstring_ftype_pcchar);
3303 
3304   TREE_PUBLIC (cfsfun) = 1;
3305   DECL_EXTERNAL (cfsfun) = 1;
3306   DECL_ARTIFICIAL (cfsfun) = 1;
3307   /* Make a lang-specific section - dup_lang_specific_decl makes a new node
3308      in place of the existing, which may be NULL.  */
3309   DECL_LANG_SPECIFIC (cfsfun) = NULL;
3310   (*lang_hooks.dup_lang_specific_decl) (cfsfun);
3311   DECL_BUILT_IN_CLASS (cfsfun) = BUILT_IN_MD;
3312   DECL_FUNCTION_CODE (cfsfun) = darwin_builtin_cfstring;
3313   lang_hooks.builtin_function (cfsfun);
3314 
3315   /* extern int __CFConstantStringClassReference[];  */
3316   cfstring_class_reference = build_decl (BUILTINS_LOCATION, VAR_DECL,
3317 		 get_identifier ("__CFConstantStringClassReference"),
3318 		 build_array_type (integer_type_node, NULL_TREE));
3319 
3320   TREE_PUBLIC (cfstring_class_reference) = 1;
3321   DECL_ARTIFICIAL (cfstring_class_reference) = 1;
3322   (*lang_hooks.decls.pushdecl) (cfstring_class_reference);
3323   DECL_EXTERNAL (cfstring_class_reference) = 1;
3324   rest_of_decl_compilation (cfstring_class_reference, 0, 0);
3325 
3326   /* Initialize the hash table used to hold the constant CFString objects.  */
3327   cfstring_htab = htab_create_ggc (31, cfstring_hash, cfstring_eq, NULL);
3328 
3329   return cfstring_type_node;
3330 }
3331 
3332 tree
darwin_fold_builtin(tree fndecl,int n_args,tree * argp,bool ARG_UNUSED (ignore))3333 darwin_fold_builtin (tree fndecl, int n_args, tree *argp,
3334 		     bool ARG_UNUSED (ignore))
3335 {
3336   unsigned int fcode = DECL_FUNCTION_CODE (fndecl);
3337 
3338   if (fcode == darwin_builtin_cfstring)
3339     {
3340       if (!darwin_constant_cfstrings)
3341 	{
3342 	  error ("built-in function %qD requires the"
3343 		 " %<-mconstant-cfstrings%> flag", fndecl);
3344 	  return error_mark_node;
3345 	}
3346 
3347       if (n_args != 1)
3348 	{
3349 	  error ("built-in function %qD takes one argument only", fndecl);
3350 	  return error_mark_node;
3351 	}
3352 
3353       return darwin_build_constant_cfstring (*argp);
3354     }
3355 
3356   return NULL_TREE;
3357 }
3358 
3359 void
darwin_rename_builtins(void)3360 darwin_rename_builtins (void)
3361 {
3362   /* The system ___divdc3 routine in libSystem on darwin10 is not
3363      accurate to 1ulp, ours is, so we avoid ever using the system name
3364      for this routine and instead install a non-conflicting name that
3365      is accurate.
3366 
3367      When -ffast-math or -funsafe-math-optimizations is given, we can
3368      use the faster version.  */
3369   if (!flag_unsafe_math_optimizations)
3370     {
3371       enum built_in_function dcode
3372 	= (enum built_in_function)(BUILT_IN_COMPLEX_DIV_MIN
3373 				   + DCmode - MIN_MODE_COMPLEX_FLOAT);
3374       tree fn = builtin_decl_explicit (dcode);
3375       /* Fortran and c call TARGET_INIT_BUILTINS and
3376 	 TARGET_INIT_LIBFUNCS at different times, so we have to put a
3377 	 call into each to ensure that at least one of them is called
3378 	 after build_common_builtin_nodes.  A better fix is to add a
3379 	 new hook to run after build_common_builtin_nodes runs.  */
3380       if (fn)
3381 	set_user_assembler_name (fn, "___ieee_divdc3");
3382       fn = builtin_decl_implicit (dcode);
3383       if (fn)
3384 	set_user_assembler_name (fn, "___ieee_divdc3");
3385     }
3386 }
3387 
3388 static hashval_t
cfstring_hash(const void * ptr)3389 cfstring_hash (const void *ptr)
3390 {
3391   tree str = ((const struct cfstring_descriptor *)ptr)->literal;
3392   const unsigned char *p = (const unsigned char *) TREE_STRING_POINTER (str);
3393   int i, len = TREE_STRING_LENGTH (str);
3394   hashval_t h = len;
3395 
3396   for (i = 0; i < len; i++)
3397     h = ((h * 613) + p[i]);
3398 
3399   return h;
3400 }
3401 
3402 static int
cfstring_eq(const void * ptr1,const void * ptr2)3403 cfstring_eq (const void *ptr1, const void *ptr2)
3404 {
3405   tree str1 = ((const struct cfstring_descriptor *)ptr1)->literal;
3406   tree str2 = ((const struct cfstring_descriptor *)ptr2)->literal;
3407   int len1 = TREE_STRING_LENGTH (str1);
3408 
3409   return (len1 == TREE_STRING_LENGTH (str2)
3410 	  && !memcmp (TREE_STRING_POINTER (str1), TREE_STRING_POINTER (str2),
3411 		      len1));
3412 }
3413 
3414 tree
darwin_build_constant_cfstring(tree str)3415 darwin_build_constant_cfstring (tree str)
3416 {
3417   struct cfstring_descriptor *desc, key;
3418   void **loc;
3419   tree addr;
3420 
3421   if (!str)
3422     {
3423       error ("CFString literal is missing");
3424       return error_mark_node;
3425     }
3426 
3427   STRIP_NOPS (str);
3428 
3429   if (TREE_CODE (str) == ADDR_EXPR)
3430     str = TREE_OPERAND (str, 0);
3431 
3432   if (TREE_CODE (str) != STRING_CST)
3433     {
3434       error ("CFString literal expression is not a string constant");
3435       return error_mark_node;
3436     }
3437 
3438   /* Perhaps we already constructed a constant CFString just like this one? */
3439   key.literal = str;
3440   loc = htab_find_slot (cfstring_htab, &key, INSERT);
3441   desc = (struct cfstring_descriptor *) *loc;
3442 
3443   if (!desc)
3444     {
3445       tree var, constructor, field;
3446       vec<constructor_elt, va_gc> *v = NULL;
3447       int length = TREE_STRING_LENGTH (str) - 1;
3448 
3449       if (darwin_warn_nonportable_cfstrings)
3450 	{
3451 	  const char *s = TREE_STRING_POINTER (str);
3452 	  int l = 0;
3453 
3454 	  for (l = 0; l < length; l++)
3455 	    if (!s[l] || !isascii (s[l]))
3456 	      {
3457 		warning (darwin_warn_nonportable_cfstrings, "%s in CFString literal",
3458 			 s[l] ? "non-ASCII character" : "embedded NUL");
3459 		break;
3460 	      }
3461 	}
3462 
3463       *loc = desc = ggc_alloc_cleared_cfstring_descriptor ();
3464       desc->literal = str;
3465 
3466       /* isa *. */
3467       field = TYPE_FIELDS (ccfstring_type_node);
3468       CONSTRUCTOR_APPEND_ELT(v, NULL_TREE,
3469 			     build1 (ADDR_EXPR,  TREE_TYPE (field),
3470 				     cfstring_class_reference));
3471       /* flags */
3472       field = DECL_CHAIN (field);
3473       CONSTRUCTOR_APPEND_ELT(v, NULL_TREE,
3474 			     build_int_cst (TREE_TYPE (field), 0x000007c8));
3475       /* string *. */
3476       field = DECL_CHAIN (field);
3477       CONSTRUCTOR_APPEND_ELT(v, NULL_TREE,
3478 			     build1 (ADDR_EXPR, TREE_TYPE (field), str));
3479       /* length */
3480       field = DECL_CHAIN (field);
3481       CONSTRUCTOR_APPEND_ELT(v, NULL_TREE,
3482 			     build_int_cst (TREE_TYPE (field), length));
3483 
3484       constructor = build_constructor (ccfstring_type_node, v);
3485       TREE_READONLY (constructor) = 1;
3486       TREE_CONSTANT (constructor) = 1;
3487       TREE_STATIC (constructor) = 1;
3488 
3489       /* Fromage: The C++ flavor of 'build_unary_op' expects constructor nodes
3490 	 to have the TREE_HAS_CONSTRUCTOR (...) bit set.  However, this file is
3491 	 being built without any knowledge of C++ tree accessors; hence, we shall
3492 	 use the generic accessor that TREE_HAS_CONSTRUCTOR actually maps to!  */
3493       if (darwin_running_cxx)
3494 	TREE_LANG_FLAG_4 (constructor) = 1;  /* TREE_HAS_CONSTRUCTOR  */
3495 
3496       /* Create an anonymous global variable for this CFString.  */
3497       var = build_decl (input_location, CONST_DECL,
3498 			NULL, TREE_TYPE (constructor));
3499       DECL_ARTIFICIAL (var) = 1;
3500       TREE_STATIC (var) = 1;
3501       DECL_INITIAL (var) = constructor;
3502       /* FIXME: This should use a translation_unit_decl to indicate file scope.  */
3503       DECL_CONTEXT (var) = NULL_TREE;
3504       desc->constructor = var;
3505     }
3506 
3507   addr = build1 (ADDR_EXPR, pccfstring_type_node, desc->constructor);
3508   TREE_CONSTANT (addr) = 1;
3509 
3510   return addr;
3511 }
3512 
3513 bool
darwin_cfstring_p(tree str)3514 darwin_cfstring_p (tree str)
3515 {
3516   struct cfstring_descriptor key;
3517   void **loc;
3518 
3519   if (!str)
3520     return false;
3521 
3522   STRIP_NOPS (str);
3523 
3524   if (TREE_CODE (str) == ADDR_EXPR)
3525     str = TREE_OPERAND (str, 0);
3526 
3527   if (TREE_CODE (str) != STRING_CST)
3528     return false;
3529 
3530   key.literal = str;
3531   loc = htab_find_slot (cfstring_htab, &key, NO_INSERT);
3532 
3533   if (loc)
3534     return true;
3535 
3536   return false;
3537 }
3538 
3539 void
darwin_enter_string_into_cfstring_table(tree str)3540 darwin_enter_string_into_cfstring_table (tree str)
3541 {
3542   struct cfstring_descriptor key;
3543   void **loc;
3544 
3545   key.literal = str;
3546   loc = htab_find_slot (cfstring_htab, &key, INSERT);
3547 
3548   if (!*loc)
3549     {
3550       *loc = ggc_alloc_cleared_cfstring_descriptor ();
3551       ((struct cfstring_descriptor *)*loc)->literal = str;
3552     }
3553 }
3554 
3555 /* Choose named function section based on its frequency.  */
3556 
3557 section *
darwin_function_section(tree decl,enum node_frequency freq,bool startup,bool exit)3558 darwin_function_section (tree decl, enum node_frequency freq,
3559 			  bool startup, bool exit)
3560 {
3561   /* Decide if we need to put this in a coalescable section.  */
3562   bool weak = (decl
3563 	       && DECL_WEAK (decl)
3564 	       && (!DECL_ATTRIBUTES (decl)
3565 		   || !lookup_attribute ("weak_import",
3566 					  DECL_ATTRIBUTES (decl))));
3567 
3568   /* If there is a specified section name, we should not be trying to
3569      override.  */
3570   if (decl && DECL_SECTION_NAME (decl) != NULL_TREE)
3571     return get_named_section (decl, NULL, 0);
3572 
3573   /* Default when there is no function re-ordering.  */
3574   if (!flag_reorder_functions)
3575     return (weak)
3576 	    ? darwin_sections[text_coal_section]
3577 	    : text_section;
3578 
3579   /* Startup code should go to startup subsection unless it is
3580      unlikely executed (this happens especially with function splitting
3581      where we can split away unnecessary parts of static constructors).  */
3582   if (startup && freq != NODE_FREQUENCY_UNLIKELY_EXECUTED)
3583     return (weak)
3584 	    ? darwin_sections[text_startup_coal_section]
3585 	    : darwin_sections[text_startup_section];
3586 
3587   /* Similarly for exit.  */
3588   if (exit && freq != NODE_FREQUENCY_UNLIKELY_EXECUTED)
3589     return (weak)
3590 	    ? darwin_sections[text_exit_coal_section]
3591 	    : darwin_sections[text_exit_section];
3592 
3593   /* Group cold functions together, similarly for hot code.  */
3594   switch (freq)
3595     {
3596       case NODE_FREQUENCY_UNLIKELY_EXECUTED:
3597 	return (weak)
3598 		? darwin_sections[text_cold_coal_section]
3599 		: darwin_sections[text_cold_section];
3600 	break;
3601       case NODE_FREQUENCY_HOT:
3602 	return (weak)
3603 		? darwin_sections[text_hot_coal_section]
3604 		: darwin_sections[text_hot_section];
3605 	break;
3606       default:
3607 	return (weak)
3608 		? darwin_sections[text_coal_section]
3609 		: text_section;
3610 	break;
3611     }
3612 }
3613 
3614 /* When a function is partitioned between sections, we need to insert a label
3615    at the start of each new chunk - so that it may become a valid 'atom' for
3616    eh and debug purposes.  Without this the linker will emit warnings if one
3617    tries to add line location information (since the switched fragment will
3618    be anonymous).  */
3619 
3620 void
darwin_function_switched_text_sections(FILE * fp,tree decl,bool new_is_cold)3621 darwin_function_switched_text_sections (FILE *fp, tree decl, bool new_is_cold)
3622 {
3623   char buf[128];
3624   snprintf (buf, 128, "%s%s",new_is_cold?"__cold_sect_of_":"__hot_sect_of_",
3625 	    IDENTIFIER_POINTER (DECL_NAME (decl)));
3626   /* Make sure we pick up all the relevant quotes etc.  */
3627   assemble_name_raw (fp, (const char *) buf);
3628   fputs (":\n", fp);
3629 }
3630 
3631 #include "gt-darwin.h"
3632