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