OSDN Git Service

45a736ad60e995f3e1667112d0c532292505fe2d
[pf3gnuchains/gcc-fork.git] / gcc / config / i386 / winnt.c
1 /* Subroutines for insn-output.c for Windows NT.
2    Contributed by Douglas Rupp (drupp@cs.washington.edu)
3    Copyright (C) 1995, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4    2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "rtl.h"
27 #include "regs.h"
28 #include "hard-reg-set.h"
29 #include "output.h"
30 #include "tree.h"
31 #include "flags.h"
32 #include "tm_p.h"
33 #include "diagnostic-core.h"
34 #include "toplev.h"
35 #include "hashtab.h"
36 #include "langhooks.h"
37 #include "ggc.h"
38 #include "target.h"
39 #include "except.h"
40 #include "lto-streamer.h"
41
42 /* i386/PE specific attribute support.
43
44    i386/PE has two new attributes:
45    dllexport - for exporting a function/variable that will live in a dll
46    dllimport - for importing a function/variable from a dll
47
48    Microsoft allows multiple declspecs in one __declspec, separating
49    them with spaces.  We do NOT support this.  Instead, use __declspec
50    multiple times.
51 */
52
53 /* Handle a "shared" attribute;
54    arguments as in struct attribute_spec.handler.  */
55 tree
56 ix86_handle_shared_attribute (tree *node, tree name,
57                               tree args ATTRIBUTE_UNUSED,
58                               int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
59 {
60   if (TREE_CODE (*node) != VAR_DECL)
61     {
62       warning (OPT_Wattributes, "%qE attribute only applies to variables",
63                name);
64       *no_add_attrs = true;
65     }
66
67   return NULL_TREE;
68 }
69
70 /* Handle a "selectany" attribute;
71    arguments as in struct attribute_spec.handler.  */
72 tree
73 ix86_handle_selectany_attribute (tree *node, tree name,
74                                  tree args ATTRIBUTE_UNUSED,
75                                  int flags ATTRIBUTE_UNUSED,
76                                  bool *no_add_attrs)
77 {
78   /* The attribute applies only to objects that are initialized and have
79      external linkage.  However, we may not know about initialization
80      until the language frontend has processed the decl. We'll check for
81      initialization later in encode_section_info.  */
82   if (TREE_CODE (*node) != VAR_DECL || !TREE_PUBLIC (*node))
83     {   
84       error ("%qE attribute applies only to initialized variables"
85              " with external linkage", name);
86       *no_add_attrs = true;
87     }
88
89   return NULL_TREE;
90 }
91
92 \f
93 /* Return the type that we should use to determine if DECL is
94    imported or exported.  */
95
96 static tree
97 associated_type (tree decl)
98 {
99   return (DECL_CONTEXT (decl) && TYPE_P (DECL_CONTEXT (decl))
100           ?  DECL_CONTEXT (decl) : NULL_TREE);
101 }
102
103 /* Return true if DECL should be a dllexport'd object.  */
104
105 static bool
106 i386_pe_determine_dllexport_p (tree decl)
107 {
108   if (TREE_CODE (decl) != VAR_DECL && TREE_CODE (decl) != FUNCTION_DECL)
109     return false;
110
111   /* Don't export local clones of dllexports.  */
112   if (!TREE_PUBLIC (decl))
113     return false;
114
115   if (lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)))
116     return true;
117
118   return false;
119 }
120
121 /* Return true if DECL should be a dllimport'd object.  */
122
123 static bool
124 i386_pe_determine_dllimport_p (tree decl)
125 {
126   tree assoc;
127
128   if (TREE_CODE (decl) != VAR_DECL && TREE_CODE (decl) != FUNCTION_DECL)
129     return false;
130
131   if (DECL_DLLIMPORT_P (decl))
132     return true;
133
134   /* The DECL_DLLIMPORT_P flag was set for decls in the class definition
135      by  targetm.cxx.adjust_class_at_definition.  Check again to emit
136      error message if the class attribute has been overridden by an
137      out-of-class definition of static data.  */
138   assoc = associated_type (decl);
139   if (assoc && lookup_attribute ("dllimport", TYPE_ATTRIBUTES (assoc))
140       && TREE_CODE (decl) == VAR_DECL
141       && TREE_STATIC (decl) && TREE_PUBLIC (decl)
142       && !DECL_EXTERNAL (decl)
143       /* vtable's are linkonce constants, so defining a vtable is not
144          an error as long as we don't try to import it too.  */
145       && !DECL_VIRTUAL_P (decl))
146         error ("definition of static data member %q+D of "
147                "dllimport'd class", decl);
148
149   return false;
150 }
151
152 /* Handle the -mno-fun-dllimport target switch.  */
153
154 bool
155 i386_pe_valid_dllimport_attribute_p (const_tree decl)
156 {
157    if (TARGET_NOP_FUN_DLLIMPORT && TREE_CODE (decl) == FUNCTION_DECL)
158      return false;
159    return true;
160 }
161
162 /* Return string which is the function name, identified by ID, modified
163    with a suffix consisting of an atsign (@) followed by the number of
164    bytes of arguments.  If ID is NULL use the DECL_NAME as base. If
165    FASTCALL is true, also add the FASTCALL_PREFIX.
166    Return NULL if no change required.  */
167
168 static tree
169 gen_stdcall_or_fastcall_suffix (tree decl, tree id, bool fastcall)
170 {
171   HOST_WIDE_INT total = 0;
172   const char *old_str = IDENTIFIER_POINTER (id != NULL_TREE ? id : DECL_NAME (decl));
173   char *new_str, *p;
174   tree type = TREE_TYPE (decl);
175   tree arg;
176   function_args_iterator args_iter;
177
178   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL);  
179
180   if (prototype_p (type))
181     {
182       /* This attribute is ignored for variadic functions.  */ 
183       if (stdarg_p (type))
184         return NULL_TREE;
185
186       /* Quit if we hit an incomplete type.  Error is reported
187          by convert_arguments in c-typeck.c or cp/typeck.c.  */
188       FOREACH_FUNCTION_ARGS(type, arg, args_iter)
189         {
190           HOST_WIDE_INT parm_size;
191           HOST_WIDE_INT parm_boundary_bytes = PARM_BOUNDARY / BITS_PER_UNIT;
192
193           if (! COMPLETE_TYPE_P (arg))
194             break;
195
196           parm_size = int_size_in_bytes (arg);
197           if (parm_size < 0)
198             break;
199
200           /* Must round up to include padding.  This is done the same
201              way as in store_one_arg.  */
202           parm_size = ((parm_size + parm_boundary_bytes - 1)
203                        / parm_boundary_bytes * parm_boundary_bytes);
204           total += parm_size;
205         }
206       }
207   /* Assume max of 8 base 10 digits in the suffix.  */
208   p = new_str = XALLOCAVEC (char, 1 + strlen (old_str) + 1 + 8 + 1);
209   if (fastcall)
210     *p++ = FASTCALL_PREFIX;
211   sprintf (p, "%s@" HOST_WIDE_INT_PRINT_DEC, old_str, total);
212
213   return get_identifier (new_str);
214 }
215
216 /* Maybe decorate and get a new identifier for the DECL of a stdcall or
217    fastcall function. The original identifier is supplied in ID. */
218
219 static tree
220 i386_pe_maybe_mangle_decl_assembler_name (tree decl, tree id)
221 {
222   tree new_id = NULL_TREE;
223
224   if (TREE_CODE (decl) == FUNCTION_DECL)
225     { 
226       tree type_attributes = TYPE_ATTRIBUTES (TREE_TYPE (decl));
227       if (lookup_attribute ("stdcall", type_attributes))
228         new_id = gen_stdcall_or_fastcall_suffix (decl, id, false);
229       else if (lookup_attribute ("fastcall", type_attributes))
230         new_id = gen_stdcall_or_fastcall_suffix (decl, id, true);
231     }
232
233   return new_id;
234 }
235
236 /* This is used as a target hook to modify the DECL_ASSEMBLER_NAME
237    in the language-independent default hook
238    langhooks,c:lhd_set_decl_assembler_name ()
239    and in cp/mangle,c:mangle_decl ().  */
240 tree
241 i386_pe_mangle_decl_assembler_name (tree decl, tree id)
242 {
243   tree new_id = i386_pe_maybe_mangle_decl_assembler_name (decl, id);   
244
245   return (new_id ? new_id : id);
246 }
247
248 void
249 i386_pe_encode_section_info (tree decl, rtx rtl, int first)
250 {
251   rtx symbol;
252   int flags;
253
254   /* Do this last, due to our frobbing of DECL_DLLIMPORT_P above.  */
255   default_encode_section_info (decl, rtl, first);
256
257   /* Careful not to prod global register variables.  */
258   if (!MEM_P (rtl))
259     return;
260
261   symbol = XEXP (rtl, 0);
262   gcc_assert (GET_CODE (symbol) == SYMBOL_REF);
263
264   switch (TREE_CODE (decl))
265     {
266     case FUNCTION_DECL:
267       /* FIXME:  Imported stdcall names are not modified by the Ada frontend.
268          Check and decorate the RTL name now.  */
269       if  (strcmp (lang_hooks.name, "GNU Ada") == 0)
270         {
271           tree new_id;
272           tree old_id = DECL_ASSEMBLER_NAME (decl);
273           const char* asm_str = IDENTIFIER_POINTER (old_id);
274           /* Do not change the identifier if a verbatim asmspec
275              or if stdcall suffix already added. */
276           if (!(*asm_str == '*' || strchr (asm_str, '@'))
277               && (new_id = i386_pe_maybe_mangle_decl_assembler_name (decl,
278                                                                      old_id)))
279             XSTR (symbol, 0) = IDENTIFIER_POINTER (new_id);
280         }
281       break;
282
283     case VAR_DECL:
284       if (lookup_attribute ("selectany", DECL_ATTRIBUTES (decl)))
285         {
286           if (DECL_INITIAL (decl)
287               /* If an object is initialized with a ctor, the static
288                  initialization and destruction code for it is present in
289                  each unit defining the object.  The code that calls the
290                  ctor is protected by a link-once guard variable, so that
291                  the object still has link-once semantics,  */
292               || TYPE_NEEDS_CONSTRUCTING (TREE_TYPE (decl)))
293             make_decl_one_only (decl, DECL_ASSEMBLER_NAME (decl));
294           else
295             error ("%q+D:'selectany' attribute applies only to "
296                    "initialized objects", decl);
297         }
298       break;
299
300     default:
301       return;
302     }
303
304   /* Mark the decl so we can tell from the rtl whether the object is
305      dllexport'd or dllimport'd.  tree.c: merge_dllimport_decl_attributes
306      handles dllexport/dllimport override semantics.  */
307   flags = (SYMBOL_REF_FLAGS (symbol) &
308            ~(SYMBOL_FLAG_DLLIMPORT | SYMBOL_FLAG_DLLEXPORT));
309   if (i386_pe_determine_dllexport_p (decl))
310     flags |= SYMBOL_FLAG_DLLEXPORT;
311   else if (i386_pe_determine_dllimport_p (decl))
312     flags |= SYMBOL_FLAG_DLLIMPORT;
313  
314   SYMBOL_REF_FLAGS (symbol) = flags;
315 }
316
317 bool
318 i386_pe_binds_local_p (const_tree exp)
319 {
320   /* PE does not do dynamic binding.  Indeed, the only kind of
321      non-local reference comes from a dllimport'd symbol.  */
322   if ((TREE_CODE (exp) == VAR_DECL || TREE_CODE (exp) == FUNCTION_DECL)
323       && DECL_DLLIMPORT_P (exp))
324     return false;
325
326   /* Or a weak one, now that they are supported.  */
327   if ((TREE_CODE (exp) == VAR_DECL || TREE_CODE (exp) == FUNCTION_DECL)
328       && DECL_WEAK (exp))
329     /* But x64 gets confused and attempts to use unsupported GOTPCREL
330        relocations if we tell it the truth, so we still return true in
331        that case until the deeper problem can be fixed.  */
332     return (TARGET_64BIT && DEFAULT_ABI == MS_ABI);
333
334   return true;
335 }
336
337 /* Also strip the fastcall prefix and stdcall suffix.  */
338
339 const char *
340 i386_pe_strip_name_encoding_full (const char *str)
341 {
342   const char *p;
343   const char *name = default_strip_name_encoding (str);
344
345   /* Strip leading '@' on fastcall symbols.  */
346   if (*name == '@')
347     name++;
348
349   /* Strip trailing "@n".  */
350   p = strchr (name, '@');
351   if (p)
352     return ggc_alloc_string (name, p - name);
353
354   return name;
355 }
356
357 void
358 i386_pe_unique_section (tree decl, int reloc)
359 {
360   int len;
361   const char *name, *prefix;
362   char *string;
363
364   name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));
365   name = i386_pe_strip_name_encoding_full (name);
366
367   /* The object is put in, for example, section .text$foo.
368      The linker will then ultimately place them in .text
369      (everything from the $ on is stripped). Don't put
370      read-only data in .rdata section to avoid a PE linker
371      bug when .rdata$* grouped sections are used in code
372      without a .rdata section.  */
373   if (TREE_CODE (decl) == FUNCTION_DECL)
374     prefix = ".text$";
375   else if (decl_readonly_section (decl, reloc))
376     prefix = ".rdata$";
377   else
378     prefix = ".data$";
379   len = strlen (name) + strlen (prefix);
380   string = XALLOCAVEC (char, len + 1);
381   sprintf (string, "%s%s", prefix, name);
382
383   DECL_SECTION_NAME (decl) = build_string (len, string);
384 }
385
386 /* Select a set of attributes for section NAME based on the properties
387    of DECL and whether or not RELOC indicates that DECL's initializer
388    might contain runtime relocations.
389
390    We make the section read-only and executable for a function decl,
391    read-only for a const data decl, and writable for a non-const data decl.
392
393    If the section has already been defined, to not allow it to have
394    different attributes, as (1) this is ambiguous since we're not seeing
395    all the declarations up front and (2) some assemblers (e.g. SVR4)
396    do not recognize section redefinitions.  */
397 /* ??? This differs from the "standard" PE implementation in that we
398    handle the SHARED variable attribute.  Should this be done for all
399    PE targets?  */
400
401 #define SECTION_PE_SHARED       SECTION_MACH_DEP
402
403 unsigned int
404 i386_pe_section_type_flags (tree decl, const char *name, int reloc)
405 {
406   static htab_t htab;
407   unsigned int flags;
408   unsigned int **slot;
409
410   /* The names we put in the hashtable will always be the unique
411      versions given to us by the stringtable, so we can just use
412      their addresses as the keys.  */
413   if (!htab)
414     htab = htab_create (31, htab_hash_pointer, htab_eq_pointer, NULL);
415
416   if (decl && TREE_CODE (decl) == FUNCTION_DECL)
417     flags = SECTION_CODE;
418   else if (decl && decl_readonly_section (decl, reloc))
419     flags = 0;
420   else if (current_function_decl
421            && cfun
422            && crtl->subsections.unlikely_text_section_name
423            && strcmp (name, crtl->subsections.unlikely_text_section_name) == 0)
424     flags = SECTION_CODE;
425   else if (!decl
426            && (!current_function_decl || !cfun)
427            && strcmp (name, UNLIKELY_EXECUTED_TEXT_SECTION_NAME) == 0)
428     flags = SECTION_CODE;
429   else
430     {
431       flags = SECTION_WRITE;
432
433       if (decl && TREE_CODE (decl) == VAR_DECL
434           && lookup_attribute ("shared", DECL_ATTRIBUTES (decl)))
435         flags |= SECTION_PE_SHARED;
436     }
437
438   if (decl && DECL_ONE_ONLY (decl))
439     flags |= SECTION_LINKONCE;
440
441   /* See if we already have an entry for this section.  */
442   slot = (unsigned int **) htab_find_slot (htab, name, INSERT);
443   if (!*slot)
444     {
445       *slot = (unsigned int *) xmalloc (sizeof (unsigned int));
446       **slot = flags;
447     }
448   else
449     {
450       if (decl && **slot != flags)
451         error ("%q+D causes a section type conflict", decl);
452     }
453
454   return flags;
455 }
456
457 void
458 i386_pe_asm_named_section (const char *name, unsigned int flags, 
459                            tree decl)
460 {
461   char flagchars[8], *f = flagchars;
462
463   if ((flags & (SECTION_CODE | SECTION_WRITE)) == 0)
464     /* readonly data */
465     {
466       *f++ ='d';  /* This is necessary for older versions of gas.  */
467       *f++ ='r';
468     }
469   else  
470     {
471       if (flags & SECTION_CODE)
472         *f++ = 'x';
473       if (flags & SECTION_WRITE)
474         *f++ = 'w';
475       if (flags & SECTION_PE_SHARED)
476         *f++ = 's';
477     }
478
479   /* LTO sections need 1-byte alignment to avoid confusing the
480      zlib decompression algorithm with trailing zero pad bytes.  */
481   if (strncmp (name, LTO_SECTION_NAME_PREFIX,
482                         strlen (LTO_SECTION_NAME_PREFIX)) == 0)
483     *f++ = '0';
484
485   *f = '\0';
486
487   fprintf (asm_out_file, "\t.section\t%s,\"%s\"\n", name, flagchars);
488
489   if (flags & SECTION_LINKONCE)
490     {
491       /* Functions may have been compiled at various levels of
492          optimization so we can't use `same_size' here.
493          Instead, have the linker pick one, without warning.
494          If 'selectany' attribute has been specified,  MS compiler
495          sets 'discard' characteristic, rather than telling linker
496          to warn of size or content mismatch, so do the same.  */ 
497       bool discard = (flags & SECTION_CODE)
498                       || lookup_attribute ("selectany",
499                                            DECL_ATTRIBUTES (decl));      
500       fprintf (asm_out_file, "\t.linkonce %s\n",
501                (discard  ? "discard" : "same_size"));
502     }
503 }
504
505 /* Beware, DECL may be NULL if compile_file() is emitting the LTO marker.  */
506
507 void
508 i386_pe_asm_output_aligned_decl_common (FILE *stream, tree decl,
509                                         const char *name, HOST_WIDE_INT size,
510                                         HOST_WIDE_INT align ATTRIBUTE_UNUSED)
511 {
512   HOST_WIDE_INT rounded;
513
514   /* Compute as in assemble_noswitch_variable, since we don't have
515      support for aligned common on older binutils.  We must also
516      avoid emitting a common symbol of size zero, as this is the
517      overloaded representation that indicates an undefined external
518      symbol in the PE object file format.  */
519   rounded = size ? size : 1;
520   rounded += (BIGGEST_ALIGNMENT / BITS_PER_UNIT) - 1;
521   rounded = (rounded / (BIGGEST_ALIGNMENT / BITS_PER_UNIT)
522              * (BIGGEST_ALIGNMENT / BITS_PER_UNIT));
523   
524   i386_pe_maybe_record_exported_symbol (decl, name, 1);
525
526   fprintf (stream, "\t.comm\t");
527   assemble_name (stream, name);
528   if (use_pe_aligned_common)
529     fprintf (stream, ", " HOST_WIDE_INT_PRINT_DEC ", %d\n",
530            size ? size : (HOST_WIDE_INT) 1,
531            exact_log2 (align) - exact_log2 (CHAR_BIT));
532   else
533     fprintf (stream, ", " HOST_WIDE_INT_PRINT_DEC "\t" ASM_COMMENT_START
534            " " HOST_WIDE_INT_PRINT_DEC "\n", rounded, size);
535 }
536 \f
537 /* The Microsoft linker requires that every function be marked as
538    DT_FCN.  When using gas on cygwin, we must emit appropriate .type
539    directives.  */
540
541 #include "gsyms.h"
542
543 /* Mark a function appropriately.  This should only be called for
544    functions for which we are not emitting COFF debugging information.
545    FILE is the assembler output file, NAME is the name of the
546    function, and PUB is nonzero if the function is globally
547    visible.  */
548
549 void
550 i386_pe_declare_function_type (FILE *file, const char *name, int pub)
551 {
552   fprintf (file, "\t.def\t");
553   assemble_name (file, name);
554   fprintf (file, ";\t.scl\t%d;\t.type\t%d;\t.endef\n",
555            pub ? (int) C_EXT : (int) C_STAT,
556            (int) DT_FCN << N_BTSHFT);
557 }
558
559 /* Keep a list of external functions.  */
560
561 struct GTY(()) extern_list
562 {
563   struct extern_list *next;
564   tree decl;
565   const char *name;
566 };
567
568 static GTY(()) struct extern_list *extern_head;
569
570 /* Assemble an external function reference.  We need to keep a list of
571    these, so that we can output the function types at the end of the
572    assembly.  We can't output the types now, because we might see a
573    definition of the function later on and emit debugging information
574    for it then.  */
575
576 void
577 i386_pe_record_external_function (tree decl, const char *name)
578 {
579   struct extern_list *p;
580
581   p = ggc_alloc_extern_list ();
582   p->next = extern_head;
583   p->decl = decl;
584   p->name = name;
585   extern_head = p;
586 }
587
588 /* Keep a list of exported symbols.  */
589
590 struct GTY(()) export_list
591 {
592   struct export_list *next;
593   const char *name;
594   int is_data;          /* used to type tag exported symbols.  */
595 };
596
597 static GTY(()) struct export_list *export_head;
598
599 /* Assemble an export symbol entry.  We need to keep a list of
600    these, so that we can output the export list at the end of the
601    assembly.  We used to output these export symbols in each function,
602    but that causes problems with GNU ld when the sections are
603    linkonce.  Beware, DECL may be NULL if compile_file() is emitting
604    the LTO marker.  */
605
606 void
607 i386_pe_maybe_record_exported_symbol (tree decl, const char *name, int is_data)
608 {
609   rtx symbol;
610   struct export_list *p;
611
612   if (!decl)
613     return;
614
615   symbol = XEXP (DECL_RTL (decl), 0);
616   gcc_assert (GET_CODE (symbol) == SYMBOL_REF);
617   if (!SYMBOL_REF_DLLEXPORT_P (symbol))
618     return;
619
620   gcc_assert (TREE_PUBLIC (decl));
621
622   p = ggc_alloc_export_list ();
623   p->next = export_head;
624   p->name = name;
625   p->is_data = is_data;
626   export_head = p;
627 }
628
629 #ifdef CXX_WRAP_SPEC_LIST
630
631 /*  Hash table equality helper function.  */
632
633 static int
634 wrapper_strcmp (const void *x, const void *y)
635 {
636   return !strcmp ((const char *) x, (const char *) y);
637 }
638
639 /* Search for a function named TARGET in the list of library wrappers
640    we are using, returning a pointer to it if found or NULL if not.
641    This function might be called on quite a few symbols, and we only
642    have the list of names of wrapped functions available to us as a
643    spec string, so first time round we lazily initialise a hash table
644    to make things quicker.  */
645
646 static const char *
647 i386_find_on_wrapper_list (const char *target)
648 {
649   static char first_time = 1;
650   static htab_t wrappers;
651
652   if (first_time)
653     {
654       /* Beware that this is not a complicated parser, it assumes
655          that any sequence of non-whitespace beginning with an
656          underscore is one of the wrapped symbols.  For now that's
657          adequate to distinguish symbols from spec substitutions
658          and command-line options.  */
659       static char wrapper_list_buffer[] = CXX_WRAP_SPEC_LIST;
660       char *bufptr;
661       /* Breaks up the char array into separated strings
662          strings and enter them into the hash table.  */
663       wrappers = htab_create_alloc (8, htab_hash_string, wrapper_strcmp,
664         0, xcalloc, free);
665       for (bufptr = wrapper_list_buffer; *bufptr; ++bufptr)
666         {
667           char *found = NULL;
668           if (ISSPACE (*bufptr))
669             continue;
670           if (*bufptr == '_')
671             found = bufptr;
672           while (*bufptr && !ISSPACE (*bufptr))
673             ++bufptr;
674           if (*bufptr)
675             *bufptr = 0;
676           if (found)
677             *htab_find_slot (wrappers, found, INSERT) = found;
678         }
679       first_time = 0;
680     }
681
682   return (const char *) htab_find (wrappers, target);
683 }
684
685 #endif /* CXX_WRAP_SPEC_LIST */
686
687 /* This is called at the end of assembly.  For each external function
688    which has not been defined, we output a declaration now.  We also
689    output the .drectve section.  */
690
691 void
692 i386_pe_file_end (void)
693 {
694   struct extern_list *p;
695
696   for (p = extern_head; p != NULL; p = p->next)
697     {
698       tree decl;
699
700       decl = p->decl;
701
702       /* Positively ensure only one declaration for any given symbol.  */
703       if (! TREE_ASM_WRITTEN (decl)
704           && TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl)))
705         {
706 #ifdef CXX_WRAP_SPEC_LIST
707           /* To ensure the DLL that provides the corresponding real
708              functions is still loaded at runtime, we must reference
709              the real function so that an (unused) import is created.  */
710           const char *realsym = i386_find_on_wrapper_list (p->name);
711           if (realsym)
712             i386_pe_declare_function_type (asm_out_file,
713                 concat ("__real_", realsym, NULL), TREE_PUBLIC (decl));
714 #endif /* CXX_WRAP_SPEC_LIST */
715           TREE_ASM_WRITTEN (decl) = 1;
716           i386_pe_declare_function_type (asm_out_file, p->name,
717                                          TREE_PUBLIC (decl));
718         }
719     }
720
721   if (export_head)
722     {
723       struct export_list *q;
724       drectve_section ();
725       for (q = export_head; q != NULL; q = q->next)
726         {
727           fprintf (asm_out_file, "\t.ascii \" -export:\\\"%s\\\"%s\"\n",
728                    default_strip_name_encoding (q->name),
729                    (q->is_data ? ",data" : ""));
730         }
731     }
732 }
733
734 \f
735 /* x64 Structured Exception Handling unwind info.  */
736
737 struct seh_frame_state
738 {
739   /* SEH records saves relative to the "current" stack pointer, whether
740      or not there's a frame pointer in place.  This tracks the current
741      stack pointer offset from the CFA.  */
742   HOST_WIDE_INT sp_offset;
743
744   /* The CFA is located at CFA_REG + CFA_OFFSET.  */
745   HOST_WIDE_INT cfa_offset;
746   rtx cfa_reg;
747 };
748
749 /* Set up data structures beginning output for SEH.  */
750
751 void
752 i386_pe_seh_init (FILE *f)
753 {
754   struct seh_frame_state *seh;
755
756   if (!TARGET_SEH)
757     return;
758   if (cfun->is_thunk)
759     return;
760
761   /* We cannot support DRAP with SEH.  We turned off support for it by
762      re-defining MAX_STACK_ALIGNMENT when SEH is enabled.  */
763   gcc_assert (!stack_realign_drap);
764
765   seh = XCNEW (struct seh_frame_state);
766   cfun->machine->seh = seh;
767
768   seh->sp_offset = INCOMING_FRAME_SP_OFFSET;
769   seh->cfa_offset = INCOMING_FRAME_SP_OFFSET;
770   seh->cfa_reg = stack_pointer_rtx;
771
772   fputs ("\t.seh_proc\t", f);
773   assemble_name (f, IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (cfun->decl)));
774   fputc ('\n', f);
775 }
776
777 void
778 i386_pe_seh_end_prologue (FILE *f)
779 {
780   struct seh_frame_state *seh;
781
782   if (!TARGET_SEH)
783     return;
784   if (cfun->is_thunk)
785     return;
786   seh = cfun->machine->seh;
787
788   /* Emit an assembler directive to set up the frame pointer.  Always do
789      this last.  The documentation talks about doing this "before" any
790      other code that uses offsets, but (experimentally) that's after we
791      emit the codes in reverse order (handled by the assembler).  */
792   if (seh->cfa_reg != stack_pointer_rtx)
793     {
794       HOST_WIDE_INT offset = seh->sp_offset - seh->cfa_offset;
795
796       gcc_assert ((offset & 15) == 0);
797       gcc_assert (IN_RANGE (offset, 0, 240));
798
799       fputs ("\t.seh_setframe\t", f);
800       print_reg (seh->cfa_reg, 0, f);
801       fprintf (f, ", " HOST_WIDE_INT_PRINT_DEC "\n", offset);
802     }
803
804   XDELETE (seh);
805   cfun->machine->seh = NULL;
806
807   fputs ("\t.seh_endprologue\n", f);
808 }
809
810 static void
811 i386_pe_seh_fini (FILE *f)
812 {
813   if (!TARGET_SEH)
814     return;
815   if (cfun->is_thunk)
816     return;
817   fputs ("\t.seh_endproc\n", f);
818 }
819
820 /* Emit an assembler directive to save REG via a PUSH.  */
821
822 static void
823 seh_emit_push (FILE *f, struct seh_frame_state *seh, rtx reg)
824 {
825   unsigned int regno = REGNO (reg);
826
827   gcc_checking_assert (GENERAL_REGNO_P (regno));
828
829   seh->sp_offset += UNITS_PER_WORD;
830   if (seh->cfa_reg == stack_pointer_rtx)
831     seh->cfa_offset += UNITS_PER_WORD;
832
833   fputs ("\t.seh_pushreg\t", f);
834   print_reg (reg, 0, f);
835   fputc ('\n', f);
836 }
837
838 /* Emit an assembler directive to save REG at CFA - CFA_OFFSET.  */
839
840 static void
841 seh_emit_save (FILE *f, struct seh_frame_state *seh,
842                rtx reg, HOST_WIDE_INT cfa_offset)
843 {
844   unsigned int regno = REGNO (reg);
845   HOST_WIDE_INT offset;
846
847   /* Negative save offsets are of course not supported, since that
848      would be a store below the stack pointer and thus clobberable.  */
849   gcc_assert (seh->sp_offset >= cfa_offset);
850   offset = seh->sp_offset - cfa_offset;
851
852   fputs ((SSE_REGNO_P (regno) ? "\t.seh_savexmm\t"
853          : GENERAL_REGNO_P (regno) ?  "\t.seh_savereg\t"
854          : (gcc_unreachable (), "")), f);
855   print_reg (reg, 0, f);
856   fprintf (f, ", " HOST_WIDE_INT_PRINT_DEC "\n", offset);
857 }
858
859 /* Emit an assembler directive to adjust RSP by OFFSET.  */
860
861 static void
862 seh_emit_stackalloc (FILE *f, struct seh_frame_state *seh,
863                      HOST_WIDE_INT offset)
864 {
865   /* We're only concerned with prologue stack allocations, which all
866      are subtractions from the stack pointer.  */
867   gcc_assert (offset < 0);
868   offset = -offset;
869
870   if (seh->cfa_reg == stack_pointer_rtx)
871     seh->cfa_offset += offset;
872   seh->sp_offset += offset;
873
874   fprintf (f, "\t.seh_stackalloc\t" HOST_WIDE_INT_PRINT_DEC "\n", offset);
875 }
876
877 /* Process REG_CFA_ADJUST_CFA for SEH.  */
878
879 static void
880 seh_cfa_adjust_cfa (FILE *f, struct seh_frame_state *seh, rtx pat)
881 {
882   rtx dest, src;
883   HOST_WIDE_INT reg_offset = 0;
884   unsigned int dest_regno;
885
886   dest = SET_DEST (pat);
887   src = SET_SRC (pat);
888
889   if (GET_CODE (src) == PLUS)
890     {
891       reg_offset = INTVAL (XEXP (src, 1));
892       src = XEXP (src, 0);
893     }
894   else if (GET_CODE (src) == MINUS)
895     {
896       reg_offset = -INTVAL (XEXP (src, 1));
897       src = XEXP (src, 0);
898     }
899   gcc_assert (src == stack_pointer_rtx);
900   gcc_assert (seh->cfa_reg == stack_pointer_rtx);
901   dest_regno = REGNO (dest);
902
903   if (dest_regno == STACK_POINTER_REGNUM)
904     seh_emit_stackalloc (f, seh, reg_offset);
905   else if (dest_regno == HARD_FRAME_POINTER_REGNUM)
906     {
907       seh->cfa_reg = dest;
908       seh->cfa_offset -= reg_offset;
909     }
910   else
911     gcc_unreachable ();
912 }
913
914 /* Process REG_CFA_OFFSET for SEH.  */
915
916 static void
917 seh_cfa_offset (FILE *f, struct seh_frame_state *seh, rtx pat)
918 {
919   rtx dest, src;
920   HOST_WIDE_INT reg_offset;
921
922   dest = SET_DEST (pat);
923   src = SET_SRC (pat);
924
925   gcc_assert (MEM_P (dest));
926   dest = XEXP (dest, 0);
927   if (REG_P (dest))
928     reg_offset = 0;
929   else
930     {
931       gcc_assert (GET_CODE (dest) == PLUS);
932       reg_offset = INTVAL (XEXP (dest, 1));
933       dest = XEXP (dest, 0);
934     }
935   gcc_assert (dest == seh->cfa_reg);
936
937   seh_emit_save (f, seh, src, seh->cfa_offset - reg_offset);
938 }
939
940 /* Process a FRAME_RELATED_EXPR for SEH.  */
941
942 static void
943 seh_frame_related_expr (FILE *f, struct seh_frame_state *seh, rtx pat)
944 {
945   rtx dest, src;
946   HOST_WIDE_INT addend;
947
948   /* See the full loop in dwarf2out_frame_debug_expr.  */
949   if (GET_CODE (pat) == PARALLEL || GET_CODE (pat) == SEQUENCE)
950     {
951       int i, n = XVECLEN (pat, 0), pass, npass;
952
953       npass = (GET_CODE (pat) == PARALLEL ? 2 : 1);
954       for (pass = 0; pass < npass; ++pass)
955         for (i = 0; i < n; ++i)
956           {
957             rtx ele = XVECEXP (pat, 0, i);
958
959             if (GET_CODE (ele) != SET)
960               continue;
961             dest = SET_DEST (ele);
962
963             /* Process each member of the PARALLEL independently.  The first
964                member is always processed; others only if they are marked.  */
965             if (i == 0 || RTX_FRAME_RELATED_P (ele))
966               {
967                 /* Evaluate all register saves in the first pass and all
968                    register updates in the second pass.  */
969                 if ((MEM_P (dest) ^ pass) || npass == 1)
970                   seh_frame_related_expr (f, seh, ele);
971               }
972           }
973       return;
974     }
975
976   dest = SET_DEST (pat);
977   src = SET_SRC (pat);
978
979   switch (GET_CODE (dest))
980     {
981     case REG:
982       switch (GET_CODE (src))
983         {
984         case REG:
985           /* REG = REG: This should be establishing a frame pointer.  */
986           gcc_assert (src == stack_pointer_rtx);
987           gcc_assert (dest == hard_frame_pointer_rtx);
988           seh_cfa_adjust_cfa (f, seh, pat);
989           break;
990
991         case PLUS:
992           addend = INTVAL (XEXP (src, 1));
993           src = XEXP (src, 0);
994           if (dest == hard_frame_pointer_rtx)
995             seh_cfa_adjust_cfa (f, seh, pat);
996           else if (dest == stack_pointer_rtx)
997             {
998               gcc_assert (src == stack_pointer_rtx);
999               seh_emit_stackalloc (f, seh, addend);
1000             }
1001           else
1002             gcc_unreachable ();
1003           break;
1004
1005         default:
1006           gcc_unreachable ();
1007         }
1008       break;
1009
1010     case MEM:
1011       /* A save of some kind.  */
1012       dest = XEXP (dest, 0);
1013       if (GET_CODE (dest) == PRE_DEC)
1014         {
1015           gcc_checking_assert (GET_MODE (src) == Pmode);
1016           gcc_checking_assert (REG_P (src));
1017           seh_emit_push (f, seh, src);
1018         }
1019       else
1020         seh_cfa_offset (f, seh, pat);
1021       break;
1022
1023     default:
1024       gcc_unreachable ();
1025     }
1026 }
1027
1028 /* This function looks at a single insn and emits any SEH directives
1029    required for unwind of this insn.  */
1030
1031 void
1032 i386_pe_seh_unwind_emit (FILE *asm_out_file, rtx insn)
1033 {
1034   rtx note, pat;
1035   bool handled_one = false;
1036   struct seh_frame_state *seh;
1037
1038   if (!TARGET_SEH)
1039     return;
1040
1041   /* We free the SEH data once done with the prologue.  Ignore those
1042      RTX_FRAME_RELATED_P insns that are associated with the epilogue.  */
1043   seh = cfun->machine->seh;
1044   if (seh == NULL)
1045     return;
1046
1047   if (NOTE_P (insn) || !RTX_FRAME_RELATED_P (insn))
1048     return;
1049
1050   for (note = REG_NOTES (insn); note ; note = XEXP (note, 1))
1051     {
1052       pat = XEXP (note, 0);
1053       switch (REG_NOTE_KIND (note))
1054         {
1055         case REG_FRAME_RELATED_EXPR:
1056           goto found;
1057
1058         case REG_CFA_DEF_CFA:
1059         case REG_CFA_EXPRESSION:
1060           /* Only emitted with DRAP, which we disable.  */
1061           gcc_unreachable ();
1062           break;
1063
1064         case REG_CFA_REGISTER:
1065           /* Only emitted in epilogues, which we skip.  */
1066           gcc_unreachable ();
1067
1068         case REG_CFA_ADJUST_CFA:
1069           if (pat == NULL)
1070             {
1071               pat = PATTERN (insn);
1072               if (GET_CODE (pat) == PARALLEL)
1073                 pat = XVECEXP (pat, 0, 0);
1074             }
1075           seh_cfa_adjust_cfa (asm_out_file, seh, pat);
1076           handled_one = true;
1077           break;
1078
1079         case REG_CFA_OFFSET:
1080           if (pat == NULL)
1081             pat = single_set (insn);
1082           seh_cfa_offset (asm_out_file, seh, pat);
1083           handled_one = true;
1084           break;
1085
1086         default:
1087           break;
1088         }
1089     }
1090   if (handled_one)
1091     return;
1092   pat = PATTERN (insn);
1093  found:
1094   seh_frame_related_expr (asm_out_file, seh, pat);
1095 }
1096 \f
1097 void
1098 i386_pe_start_function (FILE *f, const char *name, tree decl)
1099 {
1100   i386_pe_maybe_record_exported_symbol (decl, name, 0);
1101   if (write_symbols != SDB_DEBUG)
1102     i386_pe_declare_function_type (f, name, TREE_PUBLIC (decl));
1103   ASM_OUTPUT_FUNCTION_LABEL (f, name, decl);
1104 }
1105
1106 void
1107 i386_pe_end_function (FILE *f, const char *name ATTRIBUTE_UNUSED,
1108                       tree decl ATTRIBUTE_UNUSED)
1109 {
1110   i386_pe_seh_fini (f);
1111 }
1112 \f
1113
1114 #include "gt-winnt.h"