PowerPC ld segfault on script discarding dynamic sections
[external/binutils.git] / gold / powerpc.cc
1 // powerpc.cc -- powerpc target support for gold.
2
3 // Copyright (C) 2008-2017 Free Software Foundation, Inc.
4 // Written by David S. Miller <davem@davemloft.net>
5 //        and David Edelsohn <edelsohn@gnu.org>
6
7 // This file is part of gold.
8
9 // This program is free software; you can redistribute it and/or modify
10 // it under the terms of the GNU General Public License as published by
11 // the Free Software Foundation; either version 3 of the License, or
12 // (at your option) any later version.
13
14 // This program is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 // GNU General Public License for more details.
18
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
22 // MA 02110-1301, USA.
23
24 #include "gold.h"
25
26 #include <set>
27 #include <algorithm>
28 #include "elfcpp.h"
29 #include "dwarf.h"
30 #include "parameters.h"
31 #include "reloc.h"
32 #include "powerpc.h"
33 #include "object.h"
34 #include "symtab.h"
35 #include "layout.h"
36 #include "output.h"
37 #include "copy-relocs.h"
38 #include "target.h"
39 #include "target-reloc.h"
40 #include "target-select.h"
41 #include "tls.h"
42 #include "errors.h"
43 #include "gc.h"
44
45 namespace
46 {
47
48 using namespace gold;
49
50 template<int size, bool big_endian>
51 class Output_data_plt_powerpc;
52
53 template<int size, bool big_endian>
54 class Output_data_brlt_powerpc;
55
56 template<int size, bool big_endian>
57 class Output_data_got_powerpc;
58
59 template<int size, bool big_endian>
60 class Output_data_glink;
61
62 template<int size, bool big_endian>
63 class Stub_table;
64
65 template<int size, bool big_endian>
66 class Output_data_save_res;
67
68 template<int size, bool big_endian>
69 class Target_powerpc;
70
71 struct Stub_table_owner
72 {
73   Stub_table_owner()
74     : output_section(NULL), owner(NULL)
75   { }
76
77   Output_section* output_section;
78   const Output_section::Input_section* owner;
79 };
80
81 inline bool
82 is_branch_reloc(unsigned int r_type);
83
84 template<int size, bool big_endian>
85 class Powerpc_relobj : public Sized_relobj_file<size, big_endian>
86 {
87 public:
88   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
89   typedef Unordered_set<Section_id, Section_id_hash> Section_refs;
90   typedef Unordered_map<Address, Section_refs> Access_from;
91
92   Powerpc_relobj(const std::string& name, Input_file* input_file, off_t offset,
93                  const typename elfcpp::Ehdr<size, big_endian>& ehdr)
94     : Sized_relobj_file<size, big_endian>(name, input_file, offset, ehdr),
95       special_(0), relatoc_(0), toc_(0), no_toc_opt_(),
96       has_small_toc_reloc_(false), opd_valid_(false), opd_ent_(),
97       access_from_map_(), has14_(), stub_table_index_(),
98       e_flags_(ehdr.get_e_flags()), st_other_()
99   {
100     this->set_abiversion(0);
101   }
102
103   ~Powerpc_relobj()
104   { }
105
106   // Read the symbols then set up st_other vector.
107   void
108   do_read_symbols(Read_symbols_data*);
109
110   // Arrange to always relocate .toc first.
111   virtual void
112   do_relocate_sections(
113       const Symbol_table* symtab, const Layout* layout,
114       const unsigned char* pshdrs, Output_file* of,
115       typename Sized_relobj_file<size, big_endian>::Views* pviews);
116
117   // The .toc section index.
118   unsigned int
119   toc_shndx() const
120   {
121     return this->toc_;
122   }
123
124   // Mark .toc entry at OFF as not optimizable.
125   void
126   set_no_toc_opt(Address off)
127   {
128     if (this->no_toc_opt_.empty())
129       this->no_toc_opt_.resize(this->section_size(this->toc_shndx())
130                                / (size / 8));
131     off /= size / 8;
132     if (off < this->no_toc_opt_.size())
133       this->no_toc_opt_[off] = true;
134   }
135
136   // Mark the entire .toc as not optimizable.
137   void
138   set_no_toc_opt()
139   {
140     this->no_toc_opt_.resize(1);
141     this->no_toc_opt_[0] = true;
142   }
143
144   // Return true if code using the .toc entry at OFF should not be edited.
145   bool
146   no_toc_opt(Address off) const
147   {
148     if (this->no_toc_opt_.empty())
149       return false;
150     off /= size / 8;
151     if (off >= this->no_toc_opt_.size())
152       return true;
153     return this->no_toc_opt_[off];
154   }
155
156   // The .got2 section shndx.
157   unsigned int
158   got2_shndx() const
159   {
160     if (size == 32)
161       return this->special_;
162     else
163       return 0;
164   }
165
166   // The .opd section shndx.
167   unsigned int
168   opd_shndx() const
169   {
170     if (size == 32)
171       return 0;
172     else
173       return this->special_;
174   }
175
176   // Init OPD entry arrays.
177   void
178   init_opd(size_t opd_size)
179   {
180     size_t count = this->opd_ent_ndx(opd_size);
181     this->opd_ent_.resize(count);
182   }
183
184   // Return section and offset of function entry for .opd + R_OFF.
185   unsigned int
186   get_opd_ent(Address r_off, Address* value = NULL) const
187   {
188     size_t ndx = this->opd_ent_ndx(r_off);
189     gold_assert(ndx < this->opd_ent_.size());
190     gold_assert(this->opd_ent_[ndx].shndx != 0);
191     if (value != NULL)
192       *value = this->opd_ent_[ndx].off;
193     return this->opd_ent_[ndx].shndx;
194   }
195
196   // Set section and offset of function entry for .opd + R_OFF.
197   void
198   set_opd_ent(Address r_off, unsigned int shndx, Address value)
199   {
200     size_t ndx = this->opd_ent_ndx(r_off);
201     gold_assert(ndx < this->opd_ent_.size());
202     this->opd_ent_[ndx].shndx = shndx;
203     this->opd_ent_[ndx].off = value;
204   }
205
206   // Return discard flag for .opd + R_OFF.
207   bool
208   get_opd_discard(Address r_off) const
209   {
210     size_t ndx = this->opd_ent_ndx(r_off);
211     gold_assert(ndx < this->opd_ent_.size());
212     return this->opd_ent_[ndx].discard;
213   }
214
215   // Set discard flag for .opd + R_OFF.
216   void
217   set_opd_discard(Address r_off)
218   {
219     size_t ndx = this->opd_ent_ndx(r_off);
220     gold_assert(ndx < this->opd_ent_.size());
221     this->opd_ent_[ndx].discard = true;
222   }
223
224   bool
225   opd_valid() const
226   { return this->opd_valid_; }
227
228   void
229   set_opd_valid()
230   { this->opd_valid_ = true; }
231
232   // Examine .rela.opd to build info about function entry points.
233   void
234   scan_opd_relocs(size_t reloc_count,
235                   const unsigned char* prelocs,
236                   const unsigned char* plocal_syms);
237
238   // Returns true if a code sequence loading a TOC entry can be
239   // converted into code calculating a TOC pointer relative offset.
240   bool
241   make_toc_relative(Target_powerpc<size, big_endian>* target,
242                     Address* value);
243
244   // Perform the Sized_relobj_file method, then set up opd info from
245   // .opd relocs.
246   void
247   do_read_relocs(Read_relocs_data*);
248
249   bool
250   do_find_special_sections(Read_symbols_data* sd);
251
252   // Adjust this local symbol value.  Return false if the symbol
253   // should be discarded from the output file.
254   bool
255   do_adjust_local_symbol(Symbol_value<size>* lv) const
256   {
257     if (size == 64 && this->opd_shndx() != 0)
258       {
259         bool is_ordinary;
260         if (lv->input_shndx(&is_ordinary) != this->opd_shndx())
261           return true;
262         if (this->get_opd_discard(lv->input_value()))
263           return false;
264       }
265     return true;
266   }
267
268   Access_from*
269   access_from_map()
270   { return &this->access_from_map_; }
271
272   // Add a reference from SRC_OBJ, SRC_INDX to this object's .opd
273   // section at DST_OFF.
274   void
275   add_reference(Relobj* src_obj,
276                 unsigned int src_indx,
277                 typename elfcpp::Elf_types<size>::Elf_Addr dst_off)
278   {
279     Section_id src_id(src_obj, src_indx);
280     this->access_from_map_[dst_off].insert(src_id);
281   }
282
283   // Add a reference to the code section specified by the .opd entry
284   // at DST_OFF
285   void
286   add_gc_mark(typename elfcpp::Elf_types<size>::Elf_Addr dst_off)
287   {
288     size_t ndx = this->opd_ent_ndx(dst_off);
289     if (ndx >= this->opd_ent_.size())
290       this->opd_ent_.resize(ndx + 1);
291     this->opd_ent_[ndx].gc_mark = true;
292   }
293
294   void
295   process_gc_mark(Symbol_table* symtab)
296   {
297     for (size_t i = 0; i < this->opd_ent_.size(); i++)
298       if (this->opd_ent_[i].gc_mark)
299         {
300           unsigned int shndx = this->opd_ent_[i].shndx;
301           symtab->gc()->worklist().push_back(Section_id(this, shndx));
302         }
303   }
304
305   // Return offset in output GOT section that this object will use
306   // as a TOC pointer.  Won't be just a constant with multi-toc support.
307   Address
308   toc_base_offset() const
309   { return 0x8000; }
310
311   void
312   set_has_small_toc_reloc()
313   { has_small_toc_reloc_ = true; }
314
315   bool
316   has_small_toc_reloc() const
317   { return has_small_toc_reloc_; }
318
319   void
320   set_has_14bit_branch(unsigned int shndx)
321   {
322     if (shndx >= this->has14_.size())
323       this->has14_.resize(shndx + 1);
324     this->has14_[shndx] = true;
325   }
326
327   bool
328   has_14bit_branch(unsigned int shndx) const
329   { return shndx < this->has14_.size() && this->has14_[shndx];  }
330
331   void
332   set_stub_table(unsigned int shndx, unsigned int stub_index)
333   {
334     if (shndx >= this->stub_table_index_.size())
335       this->stub_table_index_.resize(shndx + 1, -1);
336     this->stub_table_index_[shndx] = stub_index;
337   }
338
339   Stub_table<size, big_endian>*
340   stub_table(unsigned int shndx)
341   {
342     if (shndx < this->stub_table_index_.size())
343       {
344         Target_powerpc<size, big_endian>* target
345           = static_cast<Target_powerpc<size, big_endian>*>(
346               parameters->sized_target<size, big_endian>());
347         unsigned int indx = this->stub_table_index_[shndx];
348         if (indx < target->stub_tables().size())
349           return target->stub_tables()[indx];
350       }
351     return NULL;
352   }
353
354   void
355   clear_stub_table()
356   {
357     this->stub_table_index_.clear();
358   }
359
360   int
361   abiversion() const
362   { return this->e_flags_ & elfcpp::EF_PPC64_ABI; }
363
364   // Set ABI version for input and output
365   void
366   set_abiversion(int ver);
367
368   unsigned int
369   ppc64_local_entry_offset(const Symbol* sym) const
370   { return elfcpp::ppc64_decode_local_entry(sym->nonvis() >> 3); }
371
372   unsigned int
373   ppc64_local_entry_offset(unsigned int symndx) const
374   { return elfcpp::ppc64_decode_local_entry(this->st_other_[symndx] >> 5); }
375
376 private:
377   struct Opd_ent
378   {
379     unsigned int shndx;
380     bool discard : 1;
381     bool gc_mark : 1;
382     Address off;
383   };
384
385   // Return index into opd_ent_ array for .opd entry at OFF.
386   // .opd entries are 24 bytes long, but they can be spaced 16 bytes
387   // apart when the language doesn't use the last 8-byte word, the
388   // environment pointer.  Thus dividing the entry section offset by
389   // 16 will give an index into opd_ent_ that works for either layout
390   // of .opd.  (It leaves some elements of the vector unused when .opd
391   // entries are spaced 24 bytes apart, but we don't know the spacing
392   // until relocations are processed, and in any case it is possible
393   // for an object to have some entries spaced 16 bytes apart and
394   // others 24 bytes apart.)
395   size_t
396   opd_ent_ndx(size_t off) const
397   { return off >> 4;}
398
399   // For 32-bit the .got2 section shdnx, for 64-bit the .opd section shndx.
400   unsigned int special_;
401
402   // For 64-bit the .rela.toc and .toc section shdnx.
403   unsigned int relatoc_;
404   unsigned int toc_;
405
406   // For 64-bit, an array with one entry per 64-bit word in the .toc
407   // section, set if accesses using that word cannot be optimised.
408   std::vector<bool> no_toc_opt_;
409
410   // For 64-bit, whether this object uses small model relocs to access
411   // the toc.
412   bool has_small_toc_reloc_;
413
414   // Set at the start of gc_process_relocs, when we know opd_ent_
415   // vector is valid.  The flag could be made atomic and set in
416   // do_read_relocs with memory_order_release and then tested with
417   // memory_order_acquire, potentially resulting in fewer entries in
418   // access_from_map_.
419   bool opd_valid_;
420
421   // The first 8-byte word of an OPD entry gives the address of the
422   // entry point of the function.  Relocatable object files have a
423   // relocation on this word.  The following vector records the
424   // section and offset specified by these relocations.
425   std::vector<Opd_ent> opd_ent_;
426
427   // References made to this object's .opd section when running
428   // gc_process_relocs for another object, before the opd_ent_ vector
429   // is valid for this object.
430   Access_from access_from_map_;
431
432   // Whether input section has a 14-bit branch reloc.
433   std::vector<bool> has14_;
434
435   // The stub table to use for a given input section.
436   std::vector<unsigned int> stub_table_index_;
437
438   // Header e_flags
439   elfcpp::Elf_Word e_flags_;
440
441   // ELF st_other field for local symbols.
442   std::vector<unsigned char> st_other_;
443 };
444
445 template<int size, bool big_endian>
446 class Powerpc_dynobj : public Sized_dynobj<size, big_endian>
447 {
448 public:
449   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
450
451   Powerpc_dynobj(const std::string& name, Input_file* input_file, off_t offset,
452                  const typename elfcpp::Ehdr<size, big_endian>& ehdr)
453     : Sized_dynobj<size, big_endian>(name, input_file, offset, ehdr),
454       opd_shndx_(0), opd_ent_(), e_flags_(ehdr.get_e_flags())
455   {
456     this->set_abiversion(0);
457   }
458
459   ~Powerpc_dynobj()
460   { }
461
462   // Call Sized_dynobj::do_read_symbols to read the symbols then
463   // read .opd from a dynamic object, filling in opd_ent_ vector,
464   void
465   do_read_symbols(Read_symbols_data*);
466
467   // The .opd section shndx.
468   unsigned int
469   opd_shndx() const
470   {
471     return this->opd_shndx_;
472   }
473
474   // The .opd section address.
475   Address
476   opd_address() const
477   {
478     return this->opd_address_;
479   }
480
481   // Init OPD entry arrays.
482   void
483   init_opd(size_t opd_size)
484   {
485     size_t count = this->opd_ent_ndx(opd_size);
486     this->opd_ent_.resize(count);
487   }
488
489   // Return section and offset of function entry for .opd + R_OFF.
490   unsigned int
491   get_opd_ent(Address r_off, Address* value = NULL) const
492   {
493     size_t ndx = this->opd_ent_ndx(r_off);
494     gold_assert(ndx < this->opd_ent_.size());
495     gold_assert(this->opd_ent_[ndx].shndx != 0);
496     if (value != NULL)
497       *value = this->opd_ent_[ndx].off;
498     return this->opd_ent_[ndx].shndx;
499   }
500
501   // Set section and offset of function entry for .opd + R_OFF.
502   void
503   set_opd_ent(Address r_off, unsigned int shndx, Address value)
504   {
505     size_t ndx = this->opd_ent_ndx(r_off);
506     gold_assert(ndx < this->opd_ent_.size());
507     this->opd_ent_[ndx].shndx = shndx;
508     this->opd_ent_[ndx].off = value;
509   }
510
511   int
512   abiversion() const
513   { return this->e_flags_ & elfcpp::EF_PPC64_ABI; }
514
515   // Set ABI version for input and output.
516   void
517   set_abiversion(int ver);
518
519 private:
520   // Used to specify extent of executable sections.
521   struct Sec_info
522   {
523     Sec_info(Address start_, Address len_, unsigned int shndx_)
524       : start(start_), len(len_), shndx(shndx_)
525     { }
526
527     bool
528     operator<(const Sec_info& that) const
529     { return this->start < that.start; }
530
531     Address start;
532     Address len;
533     unsigned int shndx;
534   };
535
536   struct Opd_ent
537   {
538     unsigned int shndx;
539     Address off;
540   };
541
542   // Return index into opd_ent_ array for .opd entry at OFF.
543   size_t
544   opd_ent_ndx(size_t off) const
545   { return off >> 4;}
546
547   // For 64-bit the .opd section shndx and address.
548   unsigned int opd_shndx_;
549   Address opd_address_;
550
551   // The first 8-byte word of an OPD entry gives the address of the
552   // entry point of the function.  Records the section and offset
553   // corresponding to the address.  Note that in dynamic objects,
554   // offset is *not* relative to the section.
555   std::vector<Opd_ent> opd_ent_;
556
557   // Header e_flags
558   elfcpp::Elf_Word e_flags_;
559 };
560
561 // Powerpc_copy_relocs class.  Needed to peek at dynamic relocs the
562 // base class will emit.
563
564 template<int sh_type, int size, bool big_endian>
565 class Powerpc_copy_relocs : public Copy_relocs<sh_type, size, big_endian>
566 {
567  public:
568   Powerpc_copy_relocs()
569     : Copy_relocs<sh_type, size, big_endian>(elfcpp::R_POWERPC_COPY)
570   { }
571
572   // Emit any saved relocations which turn out to be needed.  This is
573   // called after all the relocs have been scanned.
574   void
575   emit(Output_data_reloc<sh_type, true, size, big_endian>*);
576 };
577
578 template<int size, bool big_endian>
579 class Target_powerpc : public Sized_target<size, big_endian>
580 {
581  public:
582   typedef
583     Output_data_reloc<elfcpp::SHT_RELA, true, size, big_endian> Reloc_section;
584   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
585   typedef typename elfcpp::Elf_types<size>::Elf_Swxword Signed_address;
586   static const Address invalid_address = static_cast<Address>(0) - 1;
587   // Offset of tp and dtp pointers from start of TLS block.
588   static const Address tp_offset = 0x7000;
589   static const Address dtp_offset = 0x8000;
590
591   Target_powerpc()
592     : Sized_target<size, big_endian>(&powerpc_info),
593       got_(NULL), plt_(NULL), iplt_(NULL), brlt_section_(NULL),
594       glink_(NULL), rela_dyn_(NULL), copy_relocs_(),
595       tlsld_got_offset_(-1U),
596       stub_tables_(), branch_lookup_table_(), branch_info_(),
597       plt_thread_safe_(false), relax_failed_(false), relax_fail_count_(0),
598       stub_group_size_(0), savres_section_(0)
599   {
600   }
601
602   // Process the relocations to determine unreferenced sections for
603   // garbage collection.
604   void
605   gc_process_relocs(Symbol_table* symtab,
606                     Layout* layout,
607                     Sized_relobj_file<size, big_endian>* object,
608                     unsigned int data_shndx,
609                     unsigned int sh_type,
610                     const unsigned char* prelocs,
611                     size_t reloc_count,
612                     Output_section* output_section,
613                     bool needs_special_offset_handling,
614                     size_t local_symbol_count,
615                     const unsigned char* plocal_symbols);
616
617   // Scan the relocations to look for symbol adjustments.
618   void
619   scan_relocs(Symbol_table* symtab,
620               Layout* layout,
621               Sized_relobj_file<size, big_endian>* object,
622               unsigned int data_shndx,
623               unsigned int sh_type,
624               const unsigned char* prelocs,
625               size_t reloc_count,
626               Output_section* output_section,
627               bool needs_special_offset_handling,
628               size_t local_symbol_count,
629               const unsigned char* plocal_symbols);
630
631   // Map input .toc section to output .got section.
632   const char*
633   do_output_section_name(const Relobj*, const char* name, size_t* plen) const
634   {
635     if (size == 64 && strcmp(name, ".toc") == 0)
636       {
637         *plen = 4;
638         return ".got";
639       }
640     return NULL;
641   }
642
643   // Provide linker defined save/restore functions.
644   void
645   define_save_restore_funcs(Layout*, Symbol_table*);
646
647   // No stubs unless a final link.
648   bool
649   do_may_relax() const
650   { return !parameters->options().relocatable(); }
651
652   bool
653   do_relax(int, const Input_objects*, Symbol_table*, Layout*, const Task*);
654
655   void
656   do_plt_fde_location(const Output_data*, unsigned char*,
657                       uint64_t*, off_t*) const;
658
659   // Stash info about branches, for stub generation.
660   void
661   push_branch(Powerpc_relobj<size, big_endian>* ppc_object,
662               unsigned int data_shndx, Address r_offset,
663               unsigned int r_type, unsigned int r_sym, Address addend)
664   {
665     Branch_info info(ppc_object, data_shndx, r_offset, r_type, r_sym, addend);
666     this->branch_info_.push_back(info);
667     if (r_type == elfcpp::R_POWERPC_REL14
668         || r_type == elfcpp::R_POWERPC_REL14_BRTAKEN
669         || r_type == elfcpp::R_POWERPC_REL14_BRNTAKEN)
670       ppc_object->set_has_14bit_branch(data_shndx);
671   }
672
673   void
674   do_define_standard_symbols(Symbol_table*, Layout*);
675
676   // Finalize the sections.
677   void
678   do_finalize_sections(Layout*, const Input_objects*, Symbol_table*);
679
680   // Return the value to use for a dynamic which requires special
681   // treatment.
682   uint64_t
683   do_dynsym_value(const Symbol*) const;
684
685   // Return the PLT address to use for a local symbol.
686   uint64_t
687   do_plt_address_for_local(const Relobj*, unsigned int) const;
688
689   // Return the PLT address to use for a global symbol.
690   uint64_t
691   do_plt_address_for_global(const Symbol*) const;
692
693   // Return the offset to use for the GOT_INDX'th got entry which is
694   // for a local tls symbol specified by OBJECT, SYMNDX.
695   int64_t
696   do_tls_offset_for_local(const Relobj* object,
697                           unsigned int symndx,
698                           unsigned int got_indx) const;
699
700   // Return the offset to use for the GOT_INDX'th got entry which is
701   // for global tls symbol GSYM.
702   int64_t
703   do_tls_offset_for_global(Symbol* gsym, unsigned int got_indx) const;
704
705   void
706   do_function_location(Symbol_location*) const;
707
708   bool
709   do_can_check_for_function_pointers() const
710   { return true; }
711
712   // Adjust -fsplit-stack code which calls non-split-stack code.
713   void
714   do_calls_non_split(Relobj* object, unsigned int shndx,
715                      section_offset_type fnoffset, section_size_type fnsize,
716                      const unsigned char* prelocs, size_t reloc_count,
717                      unsigned char* view, section_size_type view_size,
718                      std::string* from, std::string* to) const;
719
720   // Relocate a section.
721   void
722   relocate_section(const Relocate_info<size, big_endian>*,
723                    unsigned int sh_type,
724                    const unsigned char* prelocs,
725                    size_t reloc_count,
726                    Output_section* output_section,
727                    bool needs_special_offset_handling,
728                    unsigned char* view,
729                    Address view_address,
730                    section_size_type view_size,
731                    const Reloc_symbol_changes*);
732
733   // Scan the relocs during a relocatable link.
734   void
735   scan_relocatable_relocs(Symbol_table* symtab,
736                           Layout* layout,
737                           Sized_relobj_file<size, big_endian>* object,
738                           unsigned int data_shndx,
739                           unsigned int sh_type,
740                           const unsigned char* prelocs,
741                           size_t reloc_count,
742                           Output_section* output_section,
743                           bool needs_special_offset_handling,
744                           size_t local_symbol_count,
745                           const unsigned char* plocal_symbols,
746                           Relocatable_relocs*);
747
748   // Scan the relocs for --emit-relocs.
749   void
750   emit_relocs_scan(Symbol_table* symtab,
751                    Layout* layout,
752                    Sized_relobj_file<size, big_endian>* object,
753                    unsigned int data_shndx,
754                    unsigned int sh_type,
755                    const unsigned char* prelocs,
756                    size_t reloc_count,
757                    Output_section* output_section,
758                    bool needs_special_offset_handling,
759                    size_t local_symbol_count,
760                    const unsigned char* plocal_syms,
761                    Relocatable_relocs* rr);
762
763   // Emit relocations for a section.
764   void
765   relocate_relocs(const Relocate_info<size, big_endian>*,
766                   unsigned int sh_type,
767                   const unsigned char* prelocs,
768                   size_t reloc_count,
769                   Output_section* output_section,
770                   typename elfcpp::Elf_types<size>::Elf_Off
771                     offset_in_output_section,
772                   unsigned char*,
773                   Address view_address,
774                   section_size_type,
775                   unsigned char* reloc_view,
776                   section_size_type reloc_view_size);
777
778   // Return whether SYM is defined by the ABI.
779   bool
780   do_is_defined_by_abi(const Symbol* sym) const
781   {
782     return strcmp(sym->name(), "__tls_get_addr") == 0;
783   }
784
785   // Return the size of the GOT section.
786   section_size_type
787   got_size() const
788   {
789     gold_assert(this->got_ != NULL);
790     return this->got_->data_size();
791   }
792
793   // Get the PLT section.
794   const Output_data_plt_powerpc<size, big_endian>*
795   plt_section() const
796   {
797     gold_assert(this->plt_ != NULL);
798     return this->plt_;
799   }
800
801   // Get the IPLT section.
802   const Output_data_plt_powerpc<size, big_endian>*
803   iplt_section() const
804   {
805     gold_assert(this->iplt_ != NULL);
806     return this->iplt_;
807   }
808
809   // Get the .glink section.
810   const Output_data_glink<size, big_endian>*
811   glink_section() const
812   {
813     gold_assert(this->glink_ != NULL);
814     return this->glink_;
815   }
816
817   Output_data_glink<size, big_endian>*
818   glink_section()
819   {
820     gold_assert(this->glink_ != NULL);
821     return this->glink_;
822   }
823
824   bool has_glink() const
825   { return this->glink_ != NULL; }
826
827   // Get the GOT section.
828   const Output_data_got_powerpc<size, big_endian>*
829   got_section() const
830   {
831     gold_assert(this->got_ != NULL);
832     return this->got_;
833   }
834
835   // Get the GOT section, creating it if necessary.
836   Output_data_got_powerpc<size, big_endian>*
837   got_section(Symbol_table*, Layout*);
838
839   Object*
840   do_make_elf_object(const std::string&, Input_file*, off_t,
841                      const elfcpp::Ehdr<size, big_endian>&);
842
843   // Return the number of entries in the GOT.
844   unsigned int
845   got_entry_count() const
846   {
847     if (this->got_ == NULL)
848       return 0;
849     return this->got_size() / (size / 8);
850   }
851
852   // Return the number of entries in the PLT.
853   unsigned int
854   plt_entry_count() const;
855
856   // Return the offset of the first non-reserved PLT entry.
857   unsigned int
858   first_plt_entry_offset() const
859   {
860     if (size == 32)
861       return 0;
862     if (this->abiversion() >= 2)
863       return 16;
864     return 24;
865   }
866
867   // Return the size of each PLT entry.
868   unsigned int
869   plt_entry_size() const
870   {
871     if (size == 32)
872       return 4;
873     if (this->abiversion() >= 2)
874       return 8;
875     return 24;
876   }
877
878   Output_data_save_res<size, big_endian>*
879   savres_section() const
880   {
881     return this->savres_section_;
882   }
883
884   // Add any special sections for this symbol to the gc work list.
885   // For powerpc64, this adds the code section of a function
886   // descriptor.
887   void
888   do_gc_mark_symbol(Symbol_table* symtab, Symbol* sym) const;
889
890   // Handle target specific gc actions when adding a gc reference from
891   // SRC_OBJ, SRC_SHNDX to a location specified by DST_OBJ, DST_SHNDX
892   // and DST_OFF.  For powerpc64, this adds a referenc to the code
893   // section of a function descriptor.
894   void
895   do_gc_add_reference(Symbol_table* symtab,
896                       Relobj* src_obj,
897                       unsigned int src_shndx,
898                       Relobj* dst_obj,
899                       unsigned int dst_shndx,
900                       Address dst_off) const;
901
902   typedef std::vector<Stub_table<size, big_endian>*> Stub_tables;
903   const Stub_tables&
904   stub_tables() const
905   { return this->stub_tables_; }
906
907   const Output_data_brlt_powerpc<size, big_endian>*
908   brlt_section() const
909   { return this->brlt_section_; }
910
911   void
912   add_branch_lookup_table(Address to)
913   {
914     unsigned int off = this->branch_lookup_table_.size() * (size / 8);
915     this->branch_lookup_table_.insert(std::make_pair(to, off));
916   }
917
918   Address
919   find_branch_lookup_table(Address to)
920   {
921     typename Branch_lookup_table::const_iterator p
922       = this->branch_lookup_table_.find(to);
923     return p == this->branch_lookup_table_.end() ? invalid_address : p->second;
924   }
925
926   void
927   write_branch_lookup_table(unsigned char *oview)
928   {
929     for (typename Branch_lookup_table::const_iterator p
930            = this->branch_lookup_table_.begin();
931          p != this->branch_lookup_table_.end();
932          ++p)
933       {
934         elfcpp::Swap<size, big_endian>::writeval(oview + p->second, p->first);
935       }
936   }
937
938   bool
939   plt_thread_safe() const
940   { return this->plt_thread_safe_; }
941
942   int
943   abiversion () const
944   { return this->processor_specific_flags() & elfcpp::EF_PPC64_ABI; }
945
946   void
947   set_abiversion (int ver)
948   {
949     elfcpp::Elf_Word flags = this->processor_specific_flags();
950     flags &= ~elfcpp::EF_PPC64_ABI;
951     flags |= ver & elfcpp::EF_PPC64_ABI;
952     this->set_processor_specific_flags(flags);
953   }
954
955   // Offset to to save stack slot
956   int
957   stk_toc () const
958   { return this->abiversion() < 2 ? 40 : 24; }
959
960  private:
961
962   class Track_tls
963   {
964   public:
965     enum Tls_get_addr
966     {
967       NOT_EXPECTED = 0,
968       EXPECTED = 1,
969       SKIP = 2,
970       NORMAL = 3
971     };
972
973     Track_tls()
974       : tls_get_addr_(NOT_EXPECTED),
975         relinfo_(NULL), relnum_(0), r_offset_(0)
976     { }
977
978     ~Track_tls()
979     {
980       if (this->tls_get_addr_ != NOT_EXPECTED)
981         this->missing();
982     }
983
984     void
985     missing(void)
986     {
987       if (this->relinfo_ != NULL)
988         gold_error_at_location(this->relinfo_, this->relnum_, this->r_offset_,
989                                _("missing expected __tls_get_addr call"));
990     }
991
992     void
993     expect_tls_get_addr_call(
994         const Relocate_info<size, big_endian>* relinfo,
995         size_t relnum,
996         Address r_offset)
997     {
998       this->tls_get_addr_ = EXPECTED;
999       this->relinfo_ = relinfo;
1000       this->relnum_ = relnum;
1001       this->r_offset_ = r_offset;
1002     }
1003
1004     void
1005     expect_tls_get_addr_call()
1006     { this->tls_get_addr_ = EXPECTED; }
1007
1008     void
1009     skip_next_tls_get_addr_call()
1010     {this->tls_get_addr_ = SKIP; }
1011
1012     Tls_get_addr
1013     maybe_skip_tls_get_addr_call(unsigned int r_type, const Symbol* gsym)
1014     {
1015       bool is_tls_call = ((r_type == elfcpp::R_POWERPC_REL24
1016                            || r_type == elfcpp::R_PPC_PLTREL24)
1017                           && gsym != NULL
1018                           && strcmp(gsym->name(), "__tls_get_addr") == 0);
1019       Tls_get_addr last_tls = this->tls_get_addr_;
1020       this->tls_get_addr_ = NOT_EXPECTED;
1021       if (is_tls_call && last_tls != EXPECTED)
1022         return last_tls;
1023       else if (!is_tls_call && last_tls != NOT_EXPECTED)
1024         {
1025           this->missing();
1026           return EXPECTED;
1027         }
1028       return NORMAL;
1029     }
1030
1031   private:
1032     // What we're up to regarding calls to __tls_get_addr.
1033     // On powerpc, the branch and link insn making a call to
1034     // __tls_get_addr is marked with a relocation, R_PPC64_TLSGD,
1035     // R_PPC64_TLSLD, R_PPC_TLSGD or R_PPC_TLSLD, in addition to the
1036     // usual R_POWERPC_REL24 or R_PPC_PLTREL25 relocation on a call.
1037     // The marker relocation always comes first, and has the same
1038     // symbol as the reloc on the insn setting up the __tls_get_addr
1039     // argument.  This ties the arg setup insn with the call insn,
1040     // allowing ld to safely optimize away the call.  We check that
1041     // every call to __tls_get_addr has a marker relocation, and that
1042     // every marker relocation is on a call to __tls_get_addr.
1043     Tls_get_addr tls_get_addr_;
1044     // Info about the last reloc for error message.
1045     const Relocate_info<size, big_endian>* relinfo_;
1046     size_t relnum_;
1047     Address r_offset_;
1048   };
1049
1050   // The class which scans relocations.
1051   class Scan : protected Track_tls
1052   {
1053   public:
1054     typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
1055
1056     Scan()
1057       : Track_tls(), issued_non_pic_error_(false)
1058     { }
1059
1060     static inline int
1061     get_reference_flags(unsigned int r_type, const Target_powerpc* target);
1062
1063     inline void
1064     local(Symbol_table* symtab, Layout* layout, Target_powerpc* target,
1065           Sized_relobj_file<size, big_endian>* object,
1066           unsigned int data_shndx,
1067           Output_section* output_section,
1068           const elfcpp::Rela<size, big_endian>& reloc, unsigned int r_type,
1069           const elfcpp::Sym<size, big_endian>& lsym,
1070           bool is_discarded);
1071
1072     inline void
1073     global(Symbol_table* symtab, Layout* layout, Target_powerpc* target,
1074            Sized_relobj_file<size, big_endian>* object,
1075            unsigned int data_shndx,
1076            Output_section* output_section,
1077            const elfcpp::Rela<size, big_endian>& reloc, unsigned int r_type,
1078            Symbol* gsym);
1079
1080     inline bool
1081     local_reloc_may_be_function_pointer(Symbol_table* , Layout* ,
1082                                         Target_powerpc* ,
1083                                         Sized_relobj_file<size, big_endian>* relobj,
1084                                         unsigned int ,
1085                                         Output_section* ,
1086                                         const elfcpp::Rela<size, big_endian>& ,
1087                                         unsigned int r_type,
1088                                         const elfcpp::Sym<size, big_endian>&)
1089     {
1090       // PowerPC64 .opd is not folded, so any identical function text
1091       // may be folded and we'll still keep function addresses distinct.
1092       // That means no reloc is of concern here.
1093       if (size == 64)
1094         {
1095           Powerpc_relobj<size, big_endian>* ppcobj = static_cast
1096             <Powerpc_relobj<size, big_endian>*>(relobj);
1097           if (ppcobj->abiversion() == 1)
1098             return false;
1099         }
1100       // For 32-bit and ELFv2, conservatively assume anything but calls to
1101       // function code might be taking the address of the function.
1102       return !is_branch_reloc(r_type);
1103     }
1104
1105     inline bool
1106     global_reloc_may_be_function_pointer(Symbol_table* , Layout* ,
1107                                          Target_powerpc* ,
1108                                          Sized_relobj_file<size, big_endian>* relobj,
1109                                          unsigned int ,
1110                                          Output_section* ,
1111                                          const elfcpp::Rela<size, big_endian>& ,
1112                                          unsigned int r_type,
1113                                          Symbol*)
1114     {
1115       // As above.
1116       if (size == 64)
1117         {
1118           Powerpc_relobj<size, big_endian>* ppcobj = static_cast
1119             <Powerpc_relobj<size, big_endian>*>(relobj);
1120           if (ppcobj->abiversion() == 1)
1121             return false;
1122         }
1123       return !is_branch_reloc(r_type);
1124     }
1125
1126     static bool
1127     reloc_needs_plt_for_ifunc(Target_powerpc<size, big_endian>* target,
1128                               Sized_relobj_file<size, big_endian>* object,
1129                               unsigned int r_type, bool report_err);
1130
1131   private:
1132     static void
1133     unsupported_reloc_local(Sized_relobj_file<size, big_endian>*,
1134                             unsigned int r_type);
1135
1136     static void
1137     unsupported_reloc_global(Sized_relobj_file<size, big_endian>*,
1138                              unsigned int r_type, Symbol*);
1139
1140     static void
1141     generate_tls_call(Symbol_table* symtab, Layout* layout,
1142                       Target_powerpc* target);
1143
1144     void
1145     check_non_pic(Relobj*, unsigned int r_type);
1146
1147     // Whether we have issued an error about a non-PIC compilation.
1148     bool issued_non_pic_error_;
1149   };
1150
1151   bool
1152   symval_for_branch(const Symbol_table* symtab,
1153                     const Sized_symbol<size>* gsym,
1154                     Powerpc_relobj<size, big_endian>* object,
1155                     Address *value, unsigned int *dest_shndx);
1156
1157   // The class which implements relocation.
1158   class Relocate : protected Track_tls
1159   {
1160    public:
1161     // Use 'at' branch hints when true, 'y' when false.
1162     // FIXME maybe: set this with an option.
1163     static const bool is_isa_v2 = true;
1164
1165     Relocate()
1166       : Track_tls()
1167     { }
1168
1169     // Do a relocation.  Return false if the caller should not issue
1170     // any warnings about this relocation.
1171     inline bool
1172     relocate(const Relocate_info<size, big_endian>*, unsigned int,
1173              Target_powerpc*, Output_section*, size_t, const unsigned char*,
1174              const Sized_symbol<size>*, const Symbol_value<size>*,
1175              unsigned char*, typename elfcpp::Elf_types<size>::Elf_Addr,
1176              section_size_type);
1177   };
1178
1179   class Relocate_comdat_behavior
1180   {
1181    public:
1182     // Decide what the linker should do for relocations that refer to
1183     // discarded comdat sections.
1184     inline Comdat_behavior
1185     get(const char* name)
1186     {
1187       gold::Default_comdat_behavior default_behavior;
1188       Comdat_behavior ret = default_behavior.get(name);
1189       if (ret == CB_WARNING)
1190         {
1191           if (size == 32
1192               && (strcmp(name, ".fixup") == 0
1193                   || strcmp(name, ".got2") == 0))
1194             ret = CB_IGNORE;
1195           if (size == 64
1196               && (strcmp(name, ".opd") == 0
1197                   || strcmp(name, ".toc") == 0
1198                   || strcmp(name, ".toc1") == 0))
1199             ret = CB_IGNORE;
1200         }
1201       return ret;
1202     }
1203   };
1204
1205   // Optimize the TLS relocation type based on what we know about the
1206   // symbol.  IS_FINAL is true if the final address of this symbol is
1207   // known at link time.
1208
1209   tls::Tls_optimization
1210   optimize_tls_gd(bool is_final)
1211   {
1212     // If we are generating a shared library, then we can't do anything
1213     // in the linker.
1214     if (parameters->options().shared())
1215       return tls::TLSOPT_NONE;
1216
1217     if (!is_final)
1218       return tls::TLSOPT_TO_IE;
1219     return tls::TLSOPT_TO_LE;
1220   }
1221
1222   tls::Tls_optimization
1223   optimize_tls_ld()
1224   {
1225     if (parameters->options().shared())
1226       return tls::TLSOPT_NONE;
1227
1228     return tls::TLSOPT_TO_LE;
1229   }
1230
1231   tls::Tls_optimization
1232   optimize_tls_ie(bool is_final)
1233   {
1234     if (!is_final || parameters->options().shared())
1235       return tls::TLSOPT_NONE;
1236
1237     return tls::TLSOPT_TO_LE;
1238   }
1239
1240   // Create glink.
1241   void
1242   make_glink_section(Layout*);
1243
1244   // Create the PLT section.
1245   void
1246   make_plt_section(Symbol_table*, Layout*);
1247
1248   void
1249   make_iplt_section(Symbol_table*, Layout*);
1250
1251   void
1252   make_brlt_section(Layout*);
1253
1254   // Create a PLT entry for a global symbol.
1255   void
1256   make_plt_entry(Symbol_table*, Layout*, Symbol*);
1257
1258   // Create a PLT entry for a local IFUNC symbol.
1259   void
1260   make_local_ifunc_plt_entry(Symbol_table*, Layout*,
1261                              Sized_relobj_file<size, big_endian>*,
1262                              unsigned int);
1263
1264
1265   // Create a GOT entry for local dynamic __tls_get_addr.
1266   unsigned int
1267   tlsld_got_offset(Symbol_table* symtab, Layout* layout,
1268                    Sized_relobj_file<size, big_endian>* object);
1269
1270   unsigned int
1271   tlsld_got_offset() const
1272   {
1273     return this->tlsld_got_offset_;
1274   }
1275
1276   // Get the dynamic reloc section, creating it if necessary.
1277   Reloc_section*
1278   rela_dyn_section(Layout*);
1279
1280   // Similarly, but for ifunc symbols get the one for ifunc.
1281   Reloc_section*
1282   rela_dyn_section(Symbol_table*, Layout*, bool for_ifunc);
1283
1284   // Copy a relocation against a global symbol.
1285   void
1286   copy_reloc(Symbol_table* symtab, Layout* layout,
1287              Sized_relobj_file<size, big_endian>* object,
1288              unsigned int shndx, Output_section* output_section,
1289              Symbol* sym, const elfcpp::Rela<size, big_endian>& reloc)
1290   {
1291     unsigned int r_type = elfcpp::elf_r_type<size>(reloc.get_r_info());
1292     this->copy_relocs_.copy_reloc(symtab, layout,
1293                                   symtab->get_sized_symbol<size>(sym),
1294                                   object, shndx, output_section,
1295                                   r_type, reloc.get_r_offset(),
1296                                   reloc.get_r_addend(),
1297                                   this->rela_dyn_section(layout));
1298   }
1299
1300   // Look over all the input sections, deciding where to place stubs.
1301   void
1302   group_sections(Layout*, const Task*, bool);
1303
1304   // Sort output sections by address.
1305   struct Sort_sections
1306   {
1307     bool
1308     operator()(const Output_section* sec1, const Output_section* sec2)
1309     { return sec1->address() < sec2->address(); }
1310   };
1311
1312   class Branch_info
1313   {
1314    public:
1315     Branch_info(Powerpc_relobj<size, big_endian>* ppc_object,
1316                 unsigned int data_shndx,
1317                 Address r_offset,
1318                 unsigned int r_type,
1319                 unsigned int r_sym,
1320                 Address addend)
1321       : object_(ppc_object), shndx_(data_shndx), offset_(r_offset),
1322         r_type_(r_type), r_sym_(r_sym), addend_(addend)
1323     { }
1324
1325     ~Branch_info()
1326     { }
1327
1328     // If this branch needs a plt call stub, or a long branch stub, make one.
1329     bool
1330     make_stub(Stub_table<size, big_endian>*,
1331               Stub_table<size, big_endian>*,
1332               Symbol_table*) const;
1333
1334    private:
1335     // The branch location..
1336     Powerpc_relobj<size, big_endian>* object_;
1337     unsigned int shndx_;
1338     Address offset_;
1339     // ..and the branch type and destination.
1340     unsigned int r_type_;
1341     unsigned int r_sym_;
1342     Address addend_;
1343   };
1344
1345   // Information about this specific target which we pass to the
1346   // general Target structure.
1347   static Target::Target_info powerpc_info;
1348
1349   // The types of GOT entries needed for this platform.
1350   // These values are exposed to the ABI in an incremental link.
1351   // Do not renumber existing values without changing the version
1352   // number of the .gnu_incremental_inputs section.
1353   enum Got_type
1354   {
1355     GOT_TYPE_STANDARD,
1356     GOT_TYPE_TLSGD,     // double entry for @got@tlsgd
1357     GOT_TYPE_DTPREL,    // entry for @got@dtprel
1358     GOT_TYPE_TPREL      // entry for @got@tprel
1359   };
1360
1361   // The GOT section.
1362   Output_data_got_powerpc<size, big_endian>* got_;
1363   // The PLT section.  This is a container for a table of addresses,
1364   // and their relocations.  Each address in the PLT has a dynamic
1365   // relocation (R_*_JMP_SLOT) and each address will have a
1366   // corresponding entry in .glink for lazy resolution of the PLT.
1367   // ppc32 initialises the PLT to point at the .glink entry, while
1368   // ppc64 leaves this to ld.so.  To make a call via the PLT, the
1369   // linker adds a stub that loads the PLT entry into ctr then
1370   // branches to ctr.  There may be more than one stub for each PLT
1371   // entry.  DT_JMPREL points at the first PLT dynamic relocation and
1372   // DT_PLTRELSZ gives the total size of PLT dynamic relocations.
1373   Output_data_plt_powerpc<size, big_endian>* plt_;
1374   // The IPLT section.  Like plt_, this is a container for a table of
1375   // addresses and their relocations, specifically for STT_GNU_IFUNC
1376   // functions that resolve locally (STT_GNU_IFUNC functions that
1377   // don't resolve locally go in PLT).  Unlike plt_, these have no
1378   // entry in .glink for lazy resolution, and the relocation section
1379   // does not have a 1-1 correspondence with IPLT addresses.  In fact,
1380   // the relocation section may contain relocations against
1381   // STT_GNU_IFUNC symbols at locations outside of IPLT.  The
1382   // relocation section will appear at the end of other dynamic
1383   // relocations, so that ld.so applies these relocations after other
1384   // dynamic relocations.  In a static executable, the relocation
1385   // section is emitted and marked with __rela_iplt_start and
1386   // __rela_iplt_end symbols.
1387   Output_data_plt_powerpc<size, big_endian>* iplt_;
1388   // Section holding long branch destinations.
1389   Output_data_brlt_powerpc<size, big_endian>* brlt_section_;
1390   // The .glink section.
1391   Output_data_glink<size, big_endian>* glink_;
1392   // The dynamic reloc section.
1393   Reloc_section* rela_dyn_;
1394   // Relocs saved to avoid a COPY reloc.
1395   Powerpc_copy_relocs<elfcpp::SHT_RELA, size, big_endian> copy_relocs_;
1396   // Offset of the GOT entry for local dynamic __tls_get_addr calls.
1397   unsigned int tlsld_got_offset_;
1398
1399   Stub_tables stub_tables_;
1400   typedef Unordered_map<Address, unsigned int> Branch_lookup_table;
1401   Branch_lookup_table branch_lookup_table_;
1402
1403   typedef std::vector<Branch_info> Branches;
1404   Branches branch_info_;
1405
1406   bool plt_thread_safe_;
1407
1408   bool relax_failed_;
1409   int relax_fail_count_;
1410   int32_t stub_group_size_;
1411
1412   Output_data_save_res<size, big_endian> *savres_section_;
1413 };
1414
1415 template<>
1416 Target::Target_info Target_powerpc<32, true>::powerpc_info =
1417 {
1418   32,                   // size
1419   true,                 // is_big_endian
1420   elfcpp::EM_PPC,       // machine_code
1421   false,                // has_make_symbol
1422   false,                // has_resolve
1423   false,                // has_code_fill
1424   true,                 // is_default_stack_executable
1425   false,                // can_icf_inline_merge_sections
1426   '\0',                 // wrap_char
1427   "/usr/lib/ld.so.1",   // dynamic_linker
1428   0x10000000,           // default_text_segment_address
1429   64 * 1024,            // abi_pagesize (overridable by -z max-page-size)
1430   4 * 1024,             // common_pagesize (overridable by -z common-page-size)
1431   false,                // isolate_execinstr
1432   0,                    // rosegment_gap
1433   elfcpp::SHN_UNDEF,    // small_common_shndx
1434   elfcpp::SHN_UNDEF,    // large_common_shndx
1435   0,                    // small_common_section_flags
1436   0,                    // large_common_section_flags
1437   NULL,                 // attributes_section
1438   NULL,                 // attributes_vendor
1439   "_start",             // entry_symbol_name
1440   32,                   // hash_entry_size
1441 };
1442
1443 template<>
1444 Target::Target_info Target_powerpc<32, false>::powerpc_info =
1445 {
1446   32,                   // size
1447   false,                // is_big_endian
1448   elfcpp::EM_PPC,       // machine_code
1449   false,                // has_make_symbol
1450   false,                // has_resolve
1451   false,                // has_code_fill
1452   true,                 // is_default_stack_executable
1453   false,                // can_icf_inline_merge_sections
1454   '\0',                 // wrap_char
1455   "/usr/lib/ld.so.1",   // dynamic_linker
1456   0x10000000,           // default_text_segment_address
1457   64 * 1024,            // abi_pagesize (overridable by -z max-page-size)
1458   4 * 1024,             // common_pagesize (overridable by -z common-page-size)
1459   false,                // isolate_execinstr
1460   0,                    // rosegment_gap
1461   elfcpp::SHN_UNDEF,    // small_common_shndx
1462   elfcpp::SHN_UNDEF,    // large_common_shndx
1463   0,                    // small_common_section_flags
1464   0,                    // large_common_section_flags
1465   NULL,                 // attributes_section
1466   NULL,                 // attributes_vendor
1467   "_start",             // entry_symbol_name
1468   32,                   // hash_entry_size
1469 };
1470
1471 template<>
1472 Target::Target_info Target_powerpc<64, true>::powerpc_info =
1473 {
1474   64,                   // size
1475   true,                 // is_big_endian
1476   elfcpp::EM_PPC64,     // machine_code
1477   false,                // has_make_symbol
1478   false,                // has_resolve
1479   false,                // has_code_fill
1480   true,                 // is_default_stack_executable
1481   false,                // can_icf_inline_merge_sections
1482   '\0',                 // wrap_char
1483   "/usr/lib/ld.so.1",   // dynamic_linker
1484   0x10000000,           // default_text_segment_address
1485   64 * 1024,            // abi_pagesize (overridable by -z max-page-size)
1486   4 * 1024,             // common_pagesize (overridable by -z common-page-size)
1487   false,                // isolate_execinstr
1488   0,                    // rosegment_gap
1489   elfcpp::SHN_UNDEF,    // small_common_shndx
1490   elfcpp::SHN_UNDEF,    // large_common_shndx
1491   0,                    // small_common_section_flags
1492   0,                    // large_common_section_flags
1493   NULL,                 // attributes_section
1494   NULL,                 // attributes_vendor
1495   "_start",             // entry_symbol_name
1496   32,                   // hash_entry_size
1497 };
1498
1499 template<>
1500 Target::Target_info Target_powerpc<64, false>::powerpc_info =
1501 {
1502   64,                   // size
1503   false,                // is_big_endian
1504   elfcpp::EM_PPC64,     // machine_code
1505   false,                // has_make_symbol
1506   false,                // has_resolve
1507   false,                // has_code_fill
1508   true,                 // is_default_stack_executable
1509   false,                // can_icf_inline_merge_sections
1510   '\0',                 // wrap_char
1511   "/usr/lib/ld.so.1",   // dynamic_linker
1512   0x10000000,           // default_text_segment_address
1513   64 * 1024,            // abi_pagesize (overridable by -z max-page-size)
1514   4 * 1024,             // common_pagesize (overridable by -z common-page-size)
1515   false,                // isolate_execinstr
1516   0,                    // rosegment_gap
1517   elfcpp::SHN_UNDEF,    // small_common_shndx
1518   elfcpp::SHN_UNDEF,    // large_common_shndx
1519   0,                    // small_common_section_flags
1520   0,                    // large_common_section_flags
1521   NULL,                 // attributes_section
1522   NULL,                 // attributes_vendor
1523   "_start",             // entry_symbol_name
1524   32,                   // hash_entry_size
1525 };
1526
1527 inline bool
1528 is_branch_reloc(unsigned int r_type)
1529 {
1530   return (r_type == elfcpp::R_POWERPC_REL24
1531           || r_type == elfcpp::R_PPC_PLTREL24
1532           || r_type == elfcpp::R_PPC_LOCAL24PC
1533           || r_type == elfcpp::R_POWERPC_REL14
1534           || r_type == elfcpp::R_POWERPC_REL14_BRTAKEN
1535           || r_type == elfcpp::R_POWERPC_REL14_BRNTAKEN
1536           || r_type == elfcpp::R_POWERPC_ADDR24
1537           || r_type == elfcpp::R_POWERPC_ADDR14
1538           || r_type == elfcpp::R_POWERPC_ADDR14_BRTAKEN
1539           || r_type == elfcpp::R_POWERPC_ADDR14_BRNTAKEN);
1540 }
1541
1542 // If INSN is an opcode that may be used with an @tls operand, return
1543 // the transformed insn for TLS optimisation, otherwise return 0.  If
1544 // REG is non-zero only match an insn with RB or RA equal to REG.
1545 uint32_t
1546 at_tls_transform(uint32_t insn, unsigned int reg)
1547 {
1548   if ((insn & (0x3f << 26)) != 31 << 26)
1549     return 0;
1550
1551   unsigned int rtra;
1552   if (reg == 0 || ((insn >> 11) & 0x1f) == reg)
1553     rtra = insn & ((1 << 26) - (1 << 16));
1554   else if (((insn >> 16) & 0x1f) == reg)
1555     rtra = (insn & (0x1f << 21)) | ((insn & (0x1f << 11)) << 5);
1556   else
1557     return 0;
1558
1559   if ((insn & (0x3ff << 1)) == 266 << 1)
1560     // add -> addi
1561     insn = 14 << 26;
1562   else if ((insn & (0x1f << 1)) == 23 << 1
1563            && ((insn & (0x1f << 6)) < 14 << 6
1564                || ((insn & (0x1f << 6)) >= 16 << 6
1565                    && (insn & (0x1f << 6)) < 24 << 6)))
1566     // load and store indexed -> dform
1567     insn = (32 | ((insn >> 6) & 0x1f)) << 26;
1568   else if ((insn & (((0x1a << 5) | 0x1f) << 1)) == 21 << 1)
1569     // ldx, ldux, stdx, stdux -> ld, ldu, std, stdu
1570     insn = ((58 | ((insn >> 6) & 4)) << 26) | ((insn >> 6) & 1);
1571   else if ((insn & (((0x1f << 5) | 0x1f) << 1)) == 341 << 1)
1572     // lwax -> lwa
1573     insn = (58 << 26) | 2;
1574   else
1575     return 0;
1576   insn |= rtra;
1577   return insn;
1578 }
1579
1580
1581 template<int size, bool big_endian>
1582 class Powerpc_relocate_functions
1583 {
1584 public:
1585   enum Overflow_check
1586   {
1587     CHECK_NONE,
1588     CHECK_SIGNED,
1589     CHECK_UNSIGNED,
1590     CHECK_BITFIELD,
1591     CHECK_LOW_INSN,
1592     CHECK_HIGH_INSN
1593   };
1594
1595   enum Status
1596   {
1597     STATUS_OK,
1598     STATUS_OVERFLOW
1599   };
1600
1601 private:
1602   typedef Powerpc_relocate_functions<size, big_endian> This;
1603   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
1604   typedef typename elfcpp::Elf_types<size>::Elf_Swxword SignedAddress;
1605
1606   template<int valsize>
1607   static inline bool
1608   has_overflow_signed(Address value)
1609   {
1610     // limit = 1 << (valsize - 1) without shift count exceeding size of type
1611     Address limit = static_cast<Address>(1) << ((valsize - 1) >> 1);
1612     limit <<= ((valsize - 1) >> 1);
1613     limit <<= ((valsize - 1) - 2 * ((valsize - 1) >> 1));
1614     return value + limit > (limit << 1) - 1;
1615   }
1616
1617   template<int valsize>
1618   static inline bool
1619   has_overflow_unsigned(Address value)
1620   {
1621     Address limit = static_cast<Address>(1) << ((valsize - 1) >> 1);
1622     limit <<= ((valsize - 1) >> 1);
1623     limit <<= ((valsize - 1) - 2 * ((valsize - 1) >> 1));
1624     return value > (limit << 1) - 1;
1625   }
1626
1627   template<int valsize>
1628   static inline bool
1629   has_overflow_bitfield(Address value)
1630   {
1631     return (has_overflow_unsigned<valsize>(value)
1632             && has_overflow_signed<valsize>(value));
1633   }
1634
1635   template<int valsize>
1636   static inline Status
1637   overflowed(Address value, Overflow_check overflow)
1638   {
1639     if (overflow == CHECK_SIGNED)
1640       {
1641         if (has_overflow_signed<valsize>(value))
1642           return STATUS_OVERFLOW;
1643       }
1644     else if (overflow == CHECK_UNSIGNED)
1645       {
1646         if (has_overflow_unsigned<valsize>(value))
1647           return STATUS_OVERFLOW;
1648       }
1649     else if (overflow == CHECK_BITFIELD)
1650       {
1651         if (has_overflow_bitfield<valsize>(value))
1652           return STATUS_OVERFLOW;
1653       }
1654     return STATUS_OK;
1655   }
1656
1657   // Do a simple RELA relocation
1658   template<int fieldsize, int valsize>
1659   static inline Status
1660   rela(unsigned char* view, Address value, Overflow_check overflow)
1661   {
1662     typedef typename elfcpp::Swap<fieldsize, big_endian>::Valtype Valtype;
1663     Valtype* wv = reinterpret_cast<Valtype*>(view);
1664     elfcpp::Swap<fieldsize, big_endian>::writeval(wv, value);
1665     return overflowed<valsize>(value, overflow);
1666   }
1667
1668   template<int fieldsize, int valsize>
1669   static inline Status
1670   rela(unsigned char* view,
1671        unsigned int right_shift,
1672        typename elfcpp::Valtype_base<fieldsize>::Valtype dst_mask,
1673        Address value,
1674        Overflow_check overflow)
1675   {
1676     typedef typename elfcpp::Swap<fieldsize, big_endian>::Valtype Valtype;
1677     Valtype* wv = reinterpret_cast<Valtype*>(view);
1678     Valtype val = elfcpp::Swap<fieldsize, big_endian>::readval(wv);
1679     Valtype reloc = value >> right_shift;
1680     val &= ~dst_mask;
1681     reloc &= dst_mask;
1682     elfcpp::Swap<fieldsize, big_endian>::writeval(wv, val | reloc);
1683     return overflowed<valsize>(value >> right_shift, overflow);
1684   }
1685
1686   // Do a simple RELA relocation, unaligned.
1687   template<int fieldsize, int valsize>
1688   static inline Status
1689   rela_ua(unsigned char* view, Address value, Overflow_check overflow)
1690   {
1691     elfcpp::Swap_unaligned<fieldsize, big_endian>::writeval(view, value);
1692     return overflowed<valsize>(value, overflow);
1693   }
1694
1695   template<int fieldsize, int valsize>
1696   static inline Status
1697   rela_ua(unsigned char* view,
1698           unsigned int right_shift,
1699           typename elfcpp::Valtype_base<fieldsize>::Valtype dst_mask,
1700           Address value,
1701           Overflow_check overflow)
1702   {
1703     typedef typename elfcpp::Swap_unaligned<fieldsize, big_endian>::Valtype
1704       Valtype;
1705     Valtype val = elfcpp::Swap<fieldsize, big_endian>::readval(view);
1706     Valtype reloc = value >> right_shift;
1707     val &= ~dst_mask;
1708     reloc &= dst_mask;
1709     elfcpp::Swap_unaligned<fieldsize, big_endian>::writeval(view, val | reloc);
1710     return overflowed<valsize>(value >> right_shift, overflow);
1711   }
1712
1713 public:
1714   // R_PPC64_ADDR64: (Symbol + Addend)
1715   static inline void
1716   addr64(unsigned char* view, Address value)
1717   { This::template rela<64,64>(view, value, CHECK_NONE); }
1718
1719   // R_PPC64_UADDR64: (Symbol + Addend) unaligned
1720   static inline void
1721   addr64_u(unsigned char* view, Address value)
1722   { This::template rela_ua<64,64>(view, value, CHECK_NONE); }
1723
1724   // R_POWERPC_ADDR32: (Symbol + Addend)
1725   static inline Status
1726   addr32(unsigned char* view, Address value, Overflow_check overflow)
1727   { return This::template rela<32,32>(view, value, overflow); }
1728
1729   // R_POWERPC_UADDR32: (Symbol + Addend) unaligned
1730   static inline Status
1731   addr32_u(unsigned char* view, Address value, Overflow_check overflow)
1732   { return This::template rela_ua<32,32>(view, value, overflow); }
1733
1734   // R_POWERPC_ADDR24: (Symbol + Addend) & 0x3fffffc
1735   static inline Status
1736   addr24(unsigned char* view, Address value, Overflow_check overflow)
1737   {
1738     Status stat = This::template rela<32,26>(view, 0, 0x03fffffc,
1739                                              value, overflow);
1740     if (overflow != CHECK_NONE && (value & 3) != 0)
1741       stat = STATUS_OVERFLOW;
1742     return stat;
1743   }
1744
1745   // R_POWERPC_ADDR16: (Symbol + Addend) & 0xffff
1746   static inline Status
1747   addr16(unsigned char* view, Address value, Overflow_check overflow)
1748   { return This::template rela<16,16>(view, value, overflow); }
1749
1750   // R_POWERPC_ADDR16: (Symbol + Addend) & 0xffff, unaligned
1751   static inline Status
1752   addr16_u(unsigned char* view, Address value, Overflow_check overflow)
1753   { return This::template rela_ua<16,16>(view, value, overflow); }
1754
1755   // R_POWERPC_ADDR16_DS: (Symbol + Addend) & 0xfffc
1756   static inline Status
1757   addr16_ds(unsigned char* view, Address value, Overflow_check overflow)
1758   {
1759     Status stat = This::template rela<16,16>(view, 0, 0xfffc, value, overflow);
1760     if ((value & 3) != 0)
1761       stat = STATUS_OVERFLOW;
1762     return stat;
1763   }
1764
1765   // R_POWERPC_ADDR16_DQ: (Symbol + Addend) & 0xfff0
1766   static inline Status
1767   addr16_dq(unsigned char* view, Address value, Overflow_check overflow)
1768   {
1769     Status stat = This::template rela<16,16>(view, 0, 0xfff0, value, overflow);
1770     if ((value & 15) != 0)
1771       stat = STATUS_OVERFLOW;
1772     return stat;
1773   }
1774
1775   // R_POWERPC_ADDR16_HI: ((Symbol + Addend) >> 16) & 0xffff
1776   static inline void
1777   addr16_hi(unsigned char* view, Address value)
1778   { This::template rela<16,16>(view, 16, 0xffff, value, CHECK_NONE); }
1779
1780   // R_POWERPC_ADDR16_HA: ((Symbol + Addend + 0x8000) >> 16) & 0xffff
1781   static inline void
1782   addr16_ha(unsigned char* view, Address value)
1783   { This::addr16_hi(view, value + 0x8000); }
1784
1785   // R_POWERPC_ADDR16_HIGHER: ((Symbol + Addend) >> 32) & 0xffff
1786   static inline void
1787   addr16_hi2(unsigned char* view, Address value)
1788   { This::template rela<16,16>(view, 32, 0xffff, value, CHECK_NONE); }
1789
1790   // R_POWERPC_ADDR16_HIGHERA: ((Symbol + Addend + 0x8000) >> 32) & 0xffff
1791   static inline void
1792   addr16_ha2(unsigned char* view, Address value)
1793   { This::addr16_hi2(view, value + 0x8000); }
1794
1795   // R_POWERPC_ADDR16_HIGHEST: ((Symbol + Addend) >> 48) & 0xffff
1796   static inline void
1797   addr16_hi3(unsigned char* view, Address value)
1798   { This::template rela<16,16>(view, 48, 0xffff, value, CHECK_NONE); }
1799
1800   // R_POWERPC_ADDR16_HIGHESTA: ((Symbol + Addend + 0x8000) >> 48) & 0xffff
1801   static inline void
1802   addr16_ha3(unsigned char* view, Address value)
1803   { This::addr16_hi3(view, value + 0x8000); }
1804
1805   // R_POWERPC_ADDR14: (Symbol + Addend) & 0xfffc
1806   static inline Status
1807   addr14(unsigned char* view, Address value, Overflow_check overflow)
1808   {
1809     Status stat = This::template rela<32,16>(view, 0, 0xfffc, value, overflow);
1810     if (overflow != CHECK_NONE && (value & 3) != 0)
1811       stat = STATUS_OVERFLOW;
1812     return stat;
1813   }
1814
1815   // R_POWERPC_REL16DX_HA
1816   static inline Status
1817   addr16dx_ha(unsigned char *view, Address value, Overflow_check overflow)
1818   {
1819     typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
1820     Valtype* wv = reinterpret_cast<Valtype*>(view);
1821     Valtype val = elfcpp::Swap<32, big_endian>::readval(wv);
1822     value += 0x8000;
1823     value = static_cast<SignedAddress>(value) >> 16;
1824     val |= (value & 0xffc1) | ((value & 0x3e) << 15);
1825     elfcpp::Swap<32, big_endian>::writeval(wv, val);
1826     return overflowed<16>(value, overflow);
1827   }
1828 };
1829
1830 // Set ABI version for input and output.
1831
1832 template<int size, bool big_endian>
1833 void
1834 Powerpc_relobj<size, big_endian>::set_abiversion(int ver)
1835 {
1836   this->e_flags_ |= ver;
1837   if (this->abiversion() != 0)
1838     {
1839       Target_powerpc<size, big_endian>* target =
1840         static_cast<Target_powerpc<size, big_endian>*>(
1841            parameters->sized_target<size, big_endian>());
1842       if (target->abiversion() == 0)
1843         target->set_abiversion(this->abiversion());
1844       else if (target->abiversion() != this->abiversion())
1845         gold_error(_("%s: ABI version %d is not compatible "
1846                      "with ABI version %d output"),
1847                    this->name().c_str(),
1848                    this->abiversion(), target->abiversion());
1849
1850     }
1851 }
1852
1853 // Stash away the index of .got2, .opd, .rela.toc, and .toc in a
1854 // relocatable object, if such sections exists.
1855
1856 template<int size, bool big_endian>
1857 bool
1858 Powerpc_relobj<size, big_endian>::do_find_special_sections(
1859     Read_symbols_data* sd)
1860 {
1861   const unsigned char* const pshdrs = sd->section_headers->data();
1862   const unsigned char* namesu = sd->section_names->data();
1863   const char* names = reinterpret_cast<const char*>(namesu);
1864   section_size_type names_size = sd->section_names_size;
1865   const unsigned char* s;
1866
1867   s = this->template find_shdr<size, big_endian>(pshdrs,
1868                                                  size == 32 ? ".got2" : ".opd",
1869                                                  names, names_size, NULL);
1870   if (s != NULL)
1871     {
1872       unsigned int ndx = (s - pshdrs) / elfcpp::Elf_sizes<size>::shdr_size;
1873       this->special_ = ndx;
1874       if (size == 64)
1875         {
1876           if (this->abiversion() == 0)
1877             this->set_abiversion(1);
1878           else if (this->abiversion() > 1)
1879             gold_error(_("%s: .opd invalid in abiv%d"),
1880                        this->name().c_str(), this->abiversion());
1881         }
1882     }
1883   if (size == 64)
1884     {
1885       s = this->template find_shdr<size, big_endian>(pshdrs, ".rela.toc",
1886                                                      names, names_size, NULL);
1887       if (s != NULL)
1888         {
1889           unsigned int ndx = (s - pshdrs) / elfcpp::Elf_sizes<size>::shdr_size;
1890           this->relatoc_ = ndx;
1891           typename elfcpp::Shdr<size, big_endian> shdr(s);
1892           this->toc_ = this->adjust_shndx(shdr.get_sh_info());
1893         }
1894     }
1895   return Sized_relobj_file<size, big_endian>::do_find_special_sections(sd);
1896 }
1897
1898 // Examine .rela.opd to build info about function entry points.
1899
1900 template<int size, bool big_endian>
1901 void
1902 Powerpc_relobj<size, big_endian>::scan_opd_relocs(
1903     size_t reloc_count,
1904     const unsigned char* prelocs,
1905     const unsigned char* plocal_syms)
1906 {
1907   if (size == 64)
1908     {
1909       typedef typename elfcpp::Rela<size, big_endian> Reltype;
1910       const int reloc_size = elfcpp::Elf_sizes<size>::rela_size;
1911       const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
1912       Address expected_off = 0;
1913       bool regular = true;
1914       unsigned int opd_ent_size = 0;
1915
1916       for (size_t i = 0; i < reloc_count; ++i, prelocs += reloc_size)
1917         {
1918           Reltype reloc(prelocs);
1919           typename elfcpp::Elf_types<size>::Elf_WXword r_info
1920             = reloc.get_r_info();
1921           unsigned int r_type = elfcpp::elf_r_type<size>(r_info);
1922           if (r_type == elfcpp::R_PPC64_ADDR64)
1923             {
1924               unsigned int r_sym = elfcpp::elf_r_sym<size>(r_info);
1925               typename elfcpp::Elf_types<size>::Elf_Addr value;
1926               bool is_ordinary;
1927               unsigned int shndx;
1928               if (r_sym < this->local_symbol_count())
1929                 {
1930                   typename elfcpp::Sym<size, big_endian>
1931                     lsym(plocal_syms + r_sym * sym_size);
1932                   shndx = lsym.get_st_shndx();
1933                   shndx = this->adjust_sym_shndx(r_sym, shndx, &is_ordinary);
1934                   value = lsym.get_st_value();
1935                 }
1936               else
1937                 shndx = this->symbol_section_and_value(r_sym, &value,
1938                                                        &is_ordinary);
1939               this->set_opd_ent(reloc.get_r_offset(), shndx,
1940                                 value + reloc.get_r_addend());
1941               if (i == 2)
1942                 {
1943                   expected_off = reloc.get_r_offset();
1944                   opd_ent_size = expected_off;
1945                 }
1946               else if (expected_off != reloc.get_r_offset())
1947                 regular = false;
1948               expected_off += opd_ent_size;
1949             }
1950           else if (r_type == elfcpp::R_PPC64_TOC)
1951             {
1952               if (expected_off - opd_ent_size + 8 != reloc.get_r_offset())
1953                 regular = false;
1954             }
1955           else
1956             {
1957               gold_warning(_("%s: unexpected reloc type %u in .opd section"),
1958                            this->name().c_str(), r_type);
1959               regular = false;
1960             }
1961         }
1962       if (reloc_count <= 2)
1963         opd_ent_size = this->section_size(this->opd_shndx());
1964       if (opd_ent_size != 24 && opd_ent_size != 16)
1965         regular = false;
1966       if (!regular)
1967         {
1968           gold_warning(_("%s: .opd is not a regular array of opd entries"),
1969                        this->name().c_str());
1970           opd_ent_size = 0;
1971         }
1972     }
1973 }
1974
1975 // Returns true if a code sequence loading the TOC entry at VALUE
1976 // relative to the TOC pointer can be converted into code calculating
1977 // a TOC pointer relative offset.
1978 // If so, the TOC pointer relative offset is stored to VALUE.
1979
1980 template<int size, bool big_endian>
1981 bool
1982 Powerpc_relobj<size, big_endian>::make_toc_relative(
1983     Target_powerpc<size, big_endian>* target,
1984     Address* value)
1985 {
1986   if (size != 64)
1987     return false;
1988
1989   // With -mcmodel=medium code it is quite possible to have
1990   // toc-relative relocs referring to objects outside the TOC.
1991   // Don't try to look at a non-existent TOC.
1992   if (this->toc_shndx() == 0)
1993     return false;
1994
1995   // Convert VALUE back to an address by adding got_base (see below),
1996   // then to an offset in the TOC by subtracting the TOC output
1997   // section address and the TOC output offset.  Since this TOC output
1998   // section and the got output section are one and the same, we can
1999   // omit adding and subtracting the output section address.
2000   Address off = (*value + this->toc_base_offset()
2001                  - this->output_section_offset(this->toc_shndx()));
2002   // Is this offset in the TOC?  -mcmodel=medium code may be using
2003   // TOC relative access to variables outside the TOC.  Those of
2004   // course can't be optimized.  We also don't try to optimize code
2005   // that is using a different object's TOC.
2006   if (off >= this->section_size(this->toc_shndx()))
2007     return false;
2008
2009   if (this->no_toc_opt(off))
2010     return false;
2011
2012   section_size_type vlen;
2013   unsigned char* view = this->get_output_view(this->toc_shndx(), &vlen);
2014   Address addr = elfcpp::Swap<size, big_endian>::readval(view + off);
2015   // The TOC pointer
2016   Address got_base = (target->got_section()->output_section()->address()
2017                       + this->toc_base_offset());
2018   addr -= got_base;
2019   if (addr + (uint64_t) 0x80008000 >= (uint64_t) 1 << 32)
2020     return false;
2021
2022   *value = addr;
2023   return true;
2024 }
2025
2026 // Perform the Sized_relobj_file method, then set up opd info from
2027 // .opd relocs.
2028
2029 template<int size, bool big_endian>
2030 void
2031 Powerpc_relobj<size, big_endian>::do_read_relocs(Read_relocs_data* rd)
2032 {
2033   Sized_relobj_file<size, big_endian>::do_read_relocs(rd);
2034   if (size == 64)
2035     {
2036       for (Read_relocs_data::Relocs_list::iterator p = rd->relocs.begin();
2037            p != rd->relocs.end();
2038            ++p)
2039         {
2040           if (p->data_shndx == this->opd_shndx())
2041             {
2042               uint64_t opd_size = this->section_size(this->opd_shndx());
2043               gold_assert(opd_size == static_cast<size_t>(opd_size));
2044               if (opd_size != 0)
2045                 {
2046                   this->init_opd(opd_size);
2047                   this->scan_opd_relocs(p->reloc_count, p->contents->data(),
2048                                         rd->local_symbols->data());
2049                 }
2050               break;
2051             }
2052         }
2053     }
2054 }
2055
2056 // Read the symbols then set up st_other vector.
2057
2058 template<int size, bool big_endian>
2059 void
2060 Powerpc_relobj<size, big_endian>::do_read_symbols(Read_symbols_data* sd)
2061 {
2062   this->base_read_symbols(sd);
2063   if (size == 64)
2064     {
2065       const int shdr_size = elfcpp::Elf_sizes<size>::shdr_size;
2066       const unsigned char* const pshdrs = sd->section_headers->data();
2067       const unsigned int loccount = this->do_local_symbol_count();
2068       if (loccount != 0)
2069         {
2070           this->st_other_.resize(loccount);
2071           const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
2072           off_t locsize = loccount * sym_size;
2073           const unsigned int symtab_shndx = this->symtab_shndx();
2074           const unsigned char *psymtab = pshdrs + symtab_shndx * shdr_size;
2075           typename elfcpp::Shdr<size, big_endian> shdr(psymtab);
2076           const unsigned char* psyms = this->get_view(shdr.get_sh_offset(),
2077                                                       locsize, true, false);
2078           psyms += sym_size;
2079           for (unsigned int i = 1; i < loccount; ++i, psyms += sym_size)
2080             {
2081               elfcpp::Sym<size, big_endian> sym(psyms);
2082               unsigned char st_other = sym.get_st_other();
2083               this->st_other_[i] = st_other;
2084               if ((st_other & elfcpp::STO_PPC64_LOCAL_MASK) != 0)
2085                 {
2086                   if (this->abiversion() == 0)
2087                     this->set_abiversion(2);
2088                   else if (this->abiversion() < 2)
2089                     gold_error(_("%s: local symbol %d has invalid st_other"
2090                                  " for ABI version 1"),
2091                                this->name().c_str(), i);
2092                 }
2093             }
2094         }
2095     }
2096 }
2097
2098 template<int size, bool big_endian>
2099 void
2100 Powerpc_dynobj<size, big_endian>::set_abiversion(int ver)
2101 {
2102   this->e_flags_ |= ver;
2103   if (this->abiversion() != 0)
2104     {
2105       Target_powerpc<size, big_endian>* target =
2106         static_cast<Target_powerpc<size, big_endian>*>(
2107           parameters->sized_target<size, big_endian>());
2108       if (target->abiversion() == 0)
2109         target->set_abiversion(this->abiversion());
2110       else if (target->abiversion() != this->abiversion())
2111         gold_error(_("%s: ABI version %d is not compatible "
2112                      "with ABI version %d output"),
2113                    this->name().c_str(),
2114                    this->abiversion(), target->abiversion());
2115
2116     }
2117 }
2118
2119 // Call Sized_dynobj::base_read_symbols to read the symbols then
2120 // read .opd from a dynamic object, filling in opd_ent_ vector,
2121
2122 template<int size, bool big_endian>
2123 void
2124 Powerpc_dynobj<size, big_endian>::do_read_symbols(Read_symbols_data* sd)
2125 {
2126   this->base_read_symbols(sd);
2127   if (size == 64)
2128     {
2129       const int shdr_size = elfcpp::Elf_sizes<size>::shdr_size;
2130       const unsigned char* const pshdrs = sd->section_headers->data();
2131       const unsigned char* namesu = sd->section_names->data();
2132       const char* names = reinterpret_cast<const char*>(namesu);
2133       const unsigned char* s = NULL;
2134       const unsigned char* opd;
2135       section_size_type opd_size;
2136
2137       // Find and read .opd section.
2138       while (1)
2139         {
2140           s = this->template find_shdr<size, big_endian>(pshdrs, ".opd", names,
2141                                                          sd->section_names_size,
2142                                                          s);
2143           if (s == NULL)
2144             return;
2145
2146           typename elfcpp::Shdr<size, big_endian> shdr(s);
2147           if (shdr.get_sh_type() == elfcpp::SHT_PROGBITS
2148               && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0)
2149             {
2150               if (this->abiversion() == 0)
2151                 this->set_abiversion(1);
2152               else if (this->abiversion() > 1)
2153                 gold_error(_("%s: .opd invalid in abiv%d"),
2154                            this->name().c_str(), this->abiversion());
2155
2156               this->opd_shndx_ = (s - pshdrs) / shdr_size;
2157               this->opd_address_ = shdr.get_sh_addr();
2158               opd_size = convert_to_section_size_type(shdr.get_sh_size());
2159               opd = this->get_view(shdr.get_sh_offset(), opd_size,
2160                                    true, false);
2161               break;
2162             }
2163         }
2164
2165       // Build set of executable sections.
2166       // Using a set is probably overkill.  There is likely to be only
2167       // a few executable sections, typically .init, .text and .fini,
2168       // and they are generally grouped together.
2169       typedef std::set<Sec_info> Exec_sections;
2170       Exec_sections exec_sections;
2171       s = pshdrs;
2172       for (unsigned int i = 1; i < this->shnum(); ++i, s += shdr_size)
2173         {
2174           typename elfcpp::Shdr<size, big_endian> shdr(s);
2175           if (shdr.get_sh_type() == elfcpp::SHT_PROGBITS
2176               && ((shdr.get_sh_flags()
2177                    & (elfcpp::SHF_ALLOC | elfcpp::SHF_EXECINSTR))
2178                   == (elfcpp::SHF_ALLOC | elfcpp::SHF_EXECINSTR))
2179               && shdr.get_sh_size() != 0)
2180             {
2181               exec_sections.insert(Sec_info(shdr.get_sh_addr(),
2182                                             shdr.get_sh_size(), i));
2183             }
2184         }
2185       if (exec_sections.empty())
2186         return;
2187
2188       // Look over the OPD entries.  This is complicated by the fact
2189       // that some binaries will use two-word entries while others
2190       // will use the standard three-word entries.  In most cases
2191       // the third word (the environment pointer for languages like
2192       // Pascal) is unused and will be zero.  If the third word is
2193       // used it should not be pointing into executable sections,
2194       // I think.
2195       this->init_opd(opd_size);
2196       for (const unsigned char* p = opd; p < opd + opd_size; p += 8)
2197         {
2198           typedef typename elfcpp::Swap<64, big_endian>::Valtype Valtype;
2199           const Valtype* valp = reinterpret_cast<const Valtype*>(p);
2200           Valtype val = elfcpp::Swap<64, big_endian>::readval(valp);
2201           if (val == 0)
2202             // Chances are that this is the third word of an OPD entry.
2203             continue;
2204           typename Exec_sections::const_iterator e
2205             = exec_sections.upper_bound(Sec_info(val, 0, 0));
2206           if (e != exec_sections.begin())
2207             {
2208               --e;
2209               if (e->start <= val && val < e->start + e->len)
2210                 {
2211                   // We have an address in an executable section.
2212                   // VAL ought to be the function entry, set it up.
2213                   this->set_opd_ent(p - opd, e->shndx, val);
2214                   // Skip second word of OPD entry, the TOC pointer.
2215                   p += 8;
2216                 }
2217             }
2218           // If we didn't match any executable sections, we likely
2219           // have a non-zero third word in the OPD entry.
2220         }
2221     }
2222 }
2223
2224 // Relocate sections.
2225
2226 template<int size, bool big_endian>
2227 void
2228 Powerpc_relobj<size, big_endian>::do_relocate_sections(
2229     const Symbol_table* symtab, const Layout* layout,
2230     const unsigned char* pshdrs, Output_file* of,
2231     typename Sized_relobj_file<size, big_endian>::Views* pviews)
2232 {
2233   unsigned int start = 1;
2234   if (size == 64
2235       && this->relatoc_ != 0
2236       && !parameters->options().relocatable())
2237     {
2238       // Relocate .toc first.
2239       this->relocate_section_range(symtab, layout, pshdrs, of, pviews,
2240                                    this->relatoc_, this->relatoc_);
2241       this->relocate_section_range(symtab, layout, pshdrs, of, pviews,
2242                                    1, this->relatoc_ - 1);
2243       start = this->relatoc_ + 1;
2244     }
2245   this->relocate_section_range(symtab, layout, pshdrs, of, pviews,
2246                                start, this->shnum() - 1);
2247 }
2248
2249 // Set up some symbols.
2250
2251 template<int size, bool big_endian>
2252 void
2253 Target_powerpc<size, big_endian>::do_define_standard_symbols(
2254     Symbol_table* symtab,
2255     Layout* layout)
2256 {
2257   if (size == 32)
2258     {
2259       // Define _GLOBAL_OFFSET_TABLE_ to ensure it isn't seen as
2260       // undefined when scanning relocs (and thus requires
2261       // non-relative dynamic relocs).  The proper value will be
2262       // updated later.
2263       Symbol *gotsym = symtab->lookup("_GLOBAL_OFFSET_TABLE_", NULL);
2264       if (gotsym != NULL && gotsym->is_undefined())
2265         {
2266           Target_powerpc<size, big_endian>* target =
2267             static_cast<Target_powerpc<size, big_endian>*>(
2268                 parameters->sized_target<size, big_endian>());
2269           Output_data_got_powerpc<size, big_endian>* got
2270             = target->got_section(symtab, layout);
2271           symtab->define_in_output_data("_GLOBAL_OFFSET_TABLE_", NULL,
2272                                         Symbol_table::PREDEFINED,
2273                                         got, 0, 0,
2274                                         elfcpp::STT_OBJECT,
2275                                         elfcpp::STB_LOCAL,
2276                                         elfcpp::STV_HIDDEN, 0,
2277                                         false, false);
2278         }
2279
2280       // Define _SDA_BASE_ at the start of the .sdata section + 32768.
2281       Symbol *sdasym = symtab->lookup("_SDA_BASE_", NULL);
2282       if (sdasym != NULL && sdasym->is_undefined())
2283         {
2284           Output_data_space* sdata = new Output_data_space(4, "** sdata");
2285           Output_section* os
2286             = layout->add_output_section_data(".sdata", 0,
2287                                               elfcpp::SHF_ALLOC
2288                                               | elfcpp::SHF_WRITE,
2289                                               sdata, ORDER_SMALL_DATA, false);
2290           symtab->define_in_output_data("_SDA_BASE_", NULL,
2291                                         Symbol_table::PREDEFINED,
2292                                         os, 32768, 0, elfcpp::STT_OBJECT,
2293                                         elfcpp::STB_LOCAL, elfcpp::STV_HIDDEN,
2294                                         0, false, false);
2295         }
2296     }
2297   else
2298     {
2299       // Define .TOC. as for 32-bit _GLOBAL_OFFSET_TABLE_
2300       Symbol *gotsym = symtab->lookup(".TOC.", NULL);
2301       if (gotsym != NULL && gotsym->is_undefined())
2302         {
2303           Target_powerpc<size, big_endian>* target =
2304             static_cast<Target_powerpc<size, big_endian>*>(
2305                 parameters->sized_target<size, big_endian>());
2306           Output_data_got_powerpc<size, big_endian>* got
2307             = target->got_section(symtab, layout);
2308           symtab->define_in_output_data(".TOC.", NULL,
2309                                         Symbol_table::PREDEFINED,
2310                                         got, 0x8000, 0,
2311                                         elfcpp::STT_OBJECT,
2312                                         elfcpp::STB_LOCAL,
2313                                         elfcpp::STV_HIDDEN, 0,
2314                                         false, false);
2315         }
2316     }
2317 }
2318
2319 // Set up PowerPC target specific relobj.
2320
2321 template<int size, bool big_endian>
2322 Object*
2323 Target_powerpc<size, big_endian>::do_make_elf_object(
2324     const std::string& name,
2325     Input_file* input_file,
2326     off_t offset, const elfcpp::Ehdr<size, big_endian>& ehdr)
2327 {
2328   int et = ehdr.get_e_type();
2329   // ET_EXEC files are valid input for --just-symbols/-R,
2330   // and we treat them as relocatable objects.
2331   if (et == elfcpp::ET_REL
2332       || (et == elfcpp::ET_EXEC && input_file->just_symbols()))
2333     {
2334       Powerpc_relobj<size, big_endian>* obj =
2335         new Powerpc_relobj<size, big_endian>(name, input_file, offset, ehdr);
2336       obj->setup();
2337       return obj;
2338     }
2339   else if (et == elfcpp::ET_DYN)
2340     {
2341       Powerpc_dynobj<size, big_endian>* obj =
2342         new Powerpc_dynobj<size, big_endian>(name, input_file, offset, ehdr);
2343       obj->setup();
2344       return obj;
2345     }
2346   else
2347     {
2348       gold_error(_("%s: unsupported ELF file type %d"), name.c_str(), et);
2349       return NULL;
2350     }
2351 }
2352
2353 template<int size, bool big_endian>
2354 class Output_data_got_powerpc : public Output_data_got<size, big_endian>
2355 {
2356 public:
2357   typedef typename elfcpp::Elf_types<size>::Elf_Addr Valtype;
2358   typedef Output_data_reloc<elfcpp::SHT_RELA, true, size, big_endian> Rela_dyn;
2359
2360   Output_data_got_powerpc(Symbol_table* symtab, Layout* layout)
2361     : Output_data_got<size, big_endian>(),
2362       symtab_(symtab), layout_(layout),
2363       header_ent_cnt_(size == 32 ? 3 : 1),
2364       header_index_(size == 32 ? 0x2000 : 0)
2365   {
2366     if (size == 64)
2367       this->set_addralign(256);
2368   }
2369
2370   // Override all the Output_data_got methods we use so as to first call
2371   // reserve_ent().
2372   bool
2373   add_global(Symbol* gsym, unsigned int got_type)
2374   {
2375     this->reserve_ent();
2376     return Output_data_got<size, big_endian>::add_global(gsym, got_type);
2377   }
2378
2379   bool
2380   add_global_plt(Symbol* gsym, unsigned int got_type)
2381   {
2382     this->reserve_ent();
2383     return Output_data_got<size, big_endian>::add_global_plt(gsym, got_type);
2384   }
2385
2386   bool
2387   add_global_tls(Symbol* gsym, unsigned int got_type)
2388   { return this->add_global_plt(gsym, got_type); }
2389
2390   void
2391   add_global_with_rel(Symbol* gsym, unsigned int got_type,
2392                       Output_data_reloc_generic* rel_dyn, unsigned int r_type)
2393   {
2394     this->reserve_ent();
2395     Output_data_got<size, big_endian>::
2396       add_global_with_rel(gsym, got_type, rel_dyn, r_type);
2397   }
2398
2399   void
2400   add_global_pair_with_rel(Symbol* gsym, unsigned int got_type,
2401                            Output_data_reloc_generic* rel_dyn,
2402                            unsigned int r_type_1, unsigned int r_type_2)
2403   {
2404     this->reserve_ent(2);
2405     Output_data_got<size, big_endian>::
2406       add_global_pair_with_rel(gsym, got_type, rel_dyn, r_type_1, r_type_2);
2407   }
2408
2409   bool
2410   add_local(Relobj* object, unsigned int sym_index, unsigned int got_type)
2411   {
2412     this->reserve_ent();
2413     return Output_data_got<size, big_endian>::add_local(object, sym_index,
2414                                                         got_type);
2415   }
2416
2417   bool
2418   add_local_plt(Relobj* object, unsigned int sym_index, unsigned int got_type)
2419   {
2420     this->reserve_ent();
2421     return Output_data_got<size, big_endian>::add_local_plt(object, sym_index,
2422                                                             got_type);
2423   }
2424
2425   bool
2426   add_local_tls(Relobj* object, unsigned int sym_index, unsigned int got_type)
2427   { return this->add_local_plt(object, sym_index, got_type); }
2428
2429   void
2430   add_local_tls_pair(Relobj* object, unsigned int sym_index,
2431                      unsigned int got_type,
2432                      Output_data_reloc_generic* rel_dyn,
2433                      unsigned int r_type)
2434   {
2435     this->reserve_ent(2);
2436     Output_data_got<size, big_endian>::
2437       add_local_tls_pair(object, sym_index, got_type, rel_dyn, r_type);
2438   }
2439
2440   unsigned int
2441   add_constant(Valtype constant)
2442   {
2443     this->reserve_ent();
2444     return Output_data_got<size, big_endian>::add_constant(constant);
2445   }
2446
2447   unsigned int
2448   add_constant_pair(Valtype c1, Valtype c2)
2449   {
2450     this->reserve_ent(2);
2451     return Output_data_got<size, big_endian>::add_constant_pair(c1, c2);
2452   }
2453
2454   // Offset of _GLOBAL_OFFSET_TABLE_.
2455   unsigned int
2456   g_o_t() const
2457   {
2458     return this->got_offset(this->header_index_);
2459   }
2460
2461   // Offset of base used to access the GOT/TOC.
2462   // The got/toc pointer reg will be set to this value.
2463   Valtype
2464   got_base_offset(const Powerpc_relobj<size, big_endian>* object) const
2465   {
2466     if (size == 32)
2467       return this->g_o_t();
2468     else
2469       return (this->output_section()->address()
2470               + object->toc_base_offset()
2471               - this->address());
2472   }
2473
2474   // Ensure our GOT has a header.
2475   void
2476   set_final_data_size()
2477   {
2478     if (this->header_ent_cnt_ != 0)
2479       this->make_header();
2480     Output_data_got<size, big_endian>::set_final_data_size();
2481   }
2482
2483   // First word of GOT header needs some values that are not
2484   // handled by Output_data_got so poke them in here.
2485   // For 32-bit, address of .dynamic, for 64-bit, address of TOCbase.
2486   void
2487   do_write(Output_file* of)
2488   {
2489     Valtype val = 0;
2490     if (size == 32 && this->layout_->dynamic_data() != NULL)
2491       val = this->layout_->dynamic_section()->address();
2492     if (size == 64)
2493       val = this->output_section()->address() + 0x8000;
2494     this->replace_constant(this->header_index_, val);
2495     Output_data_got<size, big_endian>::do_write(of);
2496   }
2497
2498 private:
2499   void
2500   reserve_ent(unsigned int cnt = 1)
2501   {
2502     if (this->header_ent_cnt_ == 0)
2503       return;
2504     if (this->num_entries() + cnt > this->header_index_)
2505       this->make_header();
2506   }
2507
2508   void
2509   make_header()
2510   {
2511     this->header_ent_cnt_ = 0;
2512     this->header_index_ = this->num_entries();
2513     if (size == 32)
2514       {
2515         Output_data_got<size, big_endian>::add_constant(0);
2516         Output_data_got<size, big_endian>::add_constant(0);
2517         Output_data_got<size, big_endian>::add_constant(0);
2518
2519         // Define _GLOBAL_OFFSET_TABLE_ at the header
2520         Symbol *gotsym = this->symtab_->lookup("_GLOBAL_OFFSET_TABLE_", NULL);
2521         if (gotsym != NULL)
2522           {
2523             Sized_symbol<size>* sym = static_cast<Sized_symbol<size>*>(gotsym);
2524             sym->set_value(this->g_o_t());
2525           }
2526         else
2527           this->symtab_->define_in_output_data("_GLOBAL_OFFSET_TABLE_", NULL,
2528                                                Symbol_table::PREDEFINED,
2529                                                this, this->g_o_t(), 0,
2530                                                elfcpp::STT_OBJECT,
2531                                                elfcpp::STB_LOCAL,
2532                                                elfcpp::STV_HIDDEN, 0,
2533                                                false, false);
2534       }
2535     else
2536       Output_data_got<size, big_endian>::add_constant(0);
2537   }
2538
2539   // Stashed pointers.
2540   Symbol_table* symtab_;
2541   Layout* layout_;
2542
2543   // GOT header size.
2544   unsigned int header_ent_cnt_;
2545   // GOT header index.
2546   unsigned int header_index_;
2547 };
2548
2549 // Get the GOT section, creating it if necessary.
2550
2551 template<int size, bool big_endian>
2552 Output_data_got_powerpc<size, big_endian>*
2553 Target_powerpc<size, big_endian>::got_section(Symbol_table* symtab,
2554                                               Layout* layout)
2555 {
2556   if (this->got_ == NULL)
2557     {
2558       gold_assert(symtab != NULL && layout != NULL);
2559
2560       this->got_
2561         = new Output_data_got_powerpc<size, big_endian>(symtab, layout);
2562
2563       layout->add_output_section_data(".got", elfcpp::SHT_PROGBITS,
2564                                       elfcpp::SHF_ALLOC | elfcpp::SHF_WRITE,
2565                                       this->got_, ORDER_DATA, false);
2566     }
2567
2568   return this->got_;
2569 }
2570
2571 // Get the dynamic reloc section, creating it if necessary.
2572
2573 template<int size, bool big_endian>
2574 typename Target_powerpc<size, big_endian>::Reloc_section*
2575 Target_powerpc<size, big_endian>::rela_dyn_section(Layout* layout)
2576 {
2577   if (this->rela_dyn_ == NULL)
2578     {
2579       gold_assert(layout != NULL);
2580       this->rela_dyn_ = new Reloc_section(parameters->options().combreloc());
2581       layout->add_output_section_data(".rela.dyn", elfcpp::SHT_RELA,
2582                                       elfcpp::SHF_ALLOC, this->rela_dyn_,
2583                                       ORDER_DYNAMIC_RELOCS, false);
2584     }
2585   return this->rela_dyn_;
2586 }
2587
2588 // Similarly, but for ifunc symbols get the one for ifunc.
2589
2590 template<int size, bool big_endian>
2591 typename Target_powerpc<size, big_endian>::Reloc_section*
2592 Target_powerpc<size, big_endian>::rela_dyn_section(Symbol_table* symtab,
2593                                                    Layout* layout,
2594                                                    bool for_ifunc)
2595 {
2596   if (!for_ifunc)
2597     return this->rela_dyn_section(layout);
2598
2599   if (this->iplt_ == NULL)
2600     this->make_iplt_section(symtab, layout);
2601   return this->iplt_->rel_plt();
2602 }
2603
2604 class Stub_control
2605 {
2606  public:
2607   // Determine the stub group size.  The group size is the absolute
2608   // value of the parameter --stub-group-size.  If --stub-group-size
2609   // is passed a negative value, we restrict stubs to be always after
2610   // the stubbed branches.
2611   Stub_control(int32_t size, bool no_size_errors, bool multi_os)
2612     : stub_group_size_(abs(size)), stubs_always_after_branch_(size < 0),
2613       suppress_size_errors_(no_size_errors), multi_os_(multi_os),
2614       state_(NO_GROUP), group_size_(0), group_start_addr_(0),
2615       owner_(NULL), output_section_(NULL)
2616   {
2617   }
2618
2619   // Return true iff input section can be handled by current stub
2620   // group.
2621   bool
2622   can_add_to_stub_group(Output_section* o,
2623                         const Output_section::Input_section* i,
2624                         bool has14);
2625
2626   const Output_section::Input_section*
2627   owner()
2628   { return owner_; }
2629
2630   Output_section*
2631   output_section()
2632   { return output_section_; }
2633
2634   void
2635   set_output_and_owner(Output_section* o,
2636                        const Output_section::Input_section* i)
2637   {
2638     this->output_section_ = o;
2639     this->owner_ = i;
2640   }
2641
2642  private:
2643   typedef enum
2644   {
2645     // Initial state.
2646     NO_GROUP,
2647     // Adding group sections before the stubs.
2648     FINDING_STUB_SECTION,
2649     // Adding group sections after the stubs.
2650     HAS_STUB_SECTION
2651   } State;
2652
2653   uint32_t stub_group_size_;
2654   bool stubs_always_after_branch_;
2655   bool suppress_size_errors_;
2656   // True if a stub group can serve multiple output sections.
2657   bool multi_os_;
2658   State state_;
2659   // Current max size of group.  Starts at stub_group_size_ but is
2660   // reduced to stub_group_size_/1024 on seeing a section with
2661   // external conditional branches.
2662   uint32_t group_size_;
2663   uint64_t group_start_addr_;
2664   // owner_ and output_section_ specify the section to which stubs are
2665   // attached.  The stubs are placed at the end of this section.
2666   const Output_section::Input_section* owner_;
2667   Output_section* output_section_;
2668 };
2669
2670 // Return true iff input section can be handled by current stub
2671 // group.  Sections are presented to this function in order,
2672 // so the first section is the head of the group.
2673
2674 bool
2675 Stub_control::can_add_to_stub_group(Output_section* o,
2676                                     const Output_section::Input_section* i,
2677                                     bool has14)
2678 {
2679   bool whole_sec = o->order() == ORDER_INIT || o->order() == ORDER_FINI;
2680   uint64_t this_size;
2681   uint64_t start_addr = o->address();
2682
2683   if (whole_sec)
2684     // .init and .fini sections are pasted together to form a single
2685     // function.  We can't be adding stubs in the middle of the function.
2686     this_size = o->data_size();
2687   else
2688     {
2689       start_addr += i->relobj()->output_section_offset(i->shndx());
2690       this_size = i->data_size();
2691     }
2692
2693   uint64_t end_addr = start_addr + this_size;
2694   uint32_t group_size = this->stub_group_size_;
2695   if (has14)
2696     this->group_size_ = group_size = group_size >> 10;
2697
2698   if (this_size > group_size && !this->suppress_size_errors_)
2699     gold_warning(_("%s:%s exceeds group size"),
2700                  i->relobj()->name().c_str(),
2701                  i->relobj()->section_name(i->shndx()).c_str());
2702
2703   gold_debug(DEBUG_TARGET, "maybe add%s %s:%s size=%#llx total=%#llx",
2704              has14 ? " 14bit" : "",
2705              i->relobj()->name().c_str(),
2706              i->relobj()->section_name(i->shndx()).c_str(),
2707              (long long) this_size,
2708              (this->state_ == NO_GROUP
2709               ? this_size
2710               : (long long) end_addr - this->group_start_addr_));
2711
2712   if (this->state_ == NO_GROUP)
2713     {
2714       // Only here on very first use of Stub_control
2715       this->owner_ = i;
2716       this->output_section_ = o;
2717       this->state_ = FINDING_STUB_SECTION;
2718       this->group_size_ = group_size;
2719       this->group_start_addr_ = start_addr;
2720       return true;
2721     }
2722   else if (!this->multi_os_ && this->output_section_ != o)
2723     ;
2724   else if (this->state_ == HAS_STUB_SECTION)
2725     {
2726       // Can we add this section, which is after the stubs, to the
2727       // group?
2728       if (end_addr - this->group_start_addr_ <= this->group_size_)
2729         return true;
2730     }
2731   else if (this->state_ == FINDING_STUB_SECTION)
2732     {
2733       if ((whole_sec && this->output_section_ == o)
2734           || end_addr - this->group_start_addr_ <= this->group_size_)
2735         {
2736           // Stubs are added at the end of "owner_".
2737           this->owner_ = i;
2738           this->output_section_ = o;
2739           return true;
2740         }
2741       // The group before the stubs has reached maximum size.
2742       // Now see about adding sections after the stubs to the
2743       // group.  If the current section has a 14-bit branch and
2744       // the group before the stubs exceeds group_size_ (because
2745       // they didn't have 14-bit branches), don't add sections
2746       // after the stubs:  The size of stubs for such a large
2747       // group may exceed the reach of a 14-bit branch.
2748       if (!this->stubs_always_after_branch_
2749           && this_size <= this->group_size_
2750           && start_addr - this->group_start_addr_ <= this->group_size_)
2751         {
2752           gold_debug(DEBUG_TARGET, "adding after stubs");
2753           this->state_ = HAS_STUB_SECTION;
2754           this->group_start_addr_ = start_addr;
2755           return true;
2756         }
2757     }
2758   else
2759     gold_unreachable();
2760
2761   gold_debug(DEBUG_TARGET,
2762              !this->multi_os_ && this->output_section_ != o
2763              ? "nope, new output section\n"
2764              : "nope, didn't fit\n");
2765
2766   // The section fails to fit in the current group.  Set up a few
2767   // things for the next group.  owner_ and output_section_ will be
2768   // set later after we've retrieved those values for the current
2769   // group.
2770   this->state_ = FINDING_STUB_SECTION;
2771   this->group_size_ = group_size;
2772   this->group_start_addr_ = start_addr;
2773   return false;
2774 }
2775
2776 // Look over all the input sections, deciding where to place stubs.
2777
2778 template<int size, bool big_endian>
2779 void
2780 Target_powerpc<size, big_endian>::group_sections(Layout* layout,
2781                                                  const Task*,
2782                                                  bool no_size_errors)
2783 {
2784   Stub_control stub_control(this->stub_group_size_, no_size_errors,
2785                             parameters->options().stub_group_multi());
2786
2787   // Group input sections and insert stub table
2788   Stub_table_owner* table_owner = NULL;
2789   std::vector<Stub_table_owner*> tables;
2790   Layout::Section_list section_list;
2791   layout->get_executable_sections(&section_list);
2792   std::stable_sort(section_list.begin(), section_list.end(), Sort_sections());
2793   for (Layout::Section_list::iterator o = section_list.begin();
2794        o != section_list.end();
2795        ++o)
2796     {
2797       typedef Output_section::Input_section_list Input_section_list;
2798       for (Input_section_list::const_iterator i
2799              = (*o)->input_sections().begin();
2800            i != (*o)->input_sections().end();
2801            ++i)
2802         {
2803           if (i->is_input_section()
2804               || i->is_relaxed_input_section())
2805             {
2806               Powerpc_relobj<size, big_endian>* ppcobj = static_cast
2807                 <Powerpc_relobj<size, big_endian>*>(i->relobj());
2808               bool has14 = ppcobj->has_14bit_branch(i->shndx());
2809               if (!stub_control.can_add_to_stub_group(*o, &*i, has14))
2810                 {
2811                   table_owner->output_section = stub_control.output_section();
2812                   table_owner->owner = stub_control.owner();
2813                   stub_control.set_output_and_owner(*o, &*i);
2814                   table_owner = NULL;
2815                 }
2816               if (table_owner == NULL)
2817                 {
2818                   table_owner = new Stub_table_owner;
2819                   tables.push_back(table_owner);
2820                 }
2821               ppcobj->set_stub_table(i->shndx(), tables.size() - 1);
2822             }
2823         }
2824     }
2825   if (table_owner != NULL)
2826     {
2827       table_owner->output_section = stub_control.output_section();
2828       table_owner->owner = stub_control.owner();;
2829     }
2830   for (typename std::vector<Stub_table_owner*>::iterator t = tables.begin();
2831        t != tables.end();
2832        ++t)
2833     {
2834       Stub_table<size, big_endian>* stub_table;
2835
2836       if ((*t)->owner->is_input_section())
2837         stub_table = new Stub_table<size, big_endian>(this,
2838                                                       (*t)->output_section,
2839                                                       (*t)->owner);
2840       else if ((*t)->owner->is_relaxed_input_section())
2841         stub_table = static_cast<Stub_table<size, big_endian>*>(
2842                         (*t)->owner->relaxed_input_section());
2843       else
2844         gold_unreachable();
2845       this->stub_tables_.push_back(stub_table);
2846       delete *t;
2847     }
2848 }
2849
2850 static unsigned long
2851 max_branch_delta (unsigned int r_type)
2852 {
2853   if (r_type == elfcpp::R_POWERPC_REL14
2854       || r_type == elfcpp::R_POWERPC_REL14_BRTAKEN
2855       || r_type == elfcpp::R_POWERPC_REL14_BRNTAKEN)
2856     return 1L << 15;
2857   if (r_type == elfcpp::R_POWERPC_REL24
2858       || r_type == elfcpp::R_PPC_PLTREL24
2859       || r_type == elfcpp::R_PPC_LOCAL24PC)
2860     return 1L << 25;
2861   return 0;
2862 }
2863
2864 // If this branch needs a plt call stub, or a long branch stub, make one.
2865
2866 template<int size, bool big_endian>
2867 bool
2868 Target_powerpc<size, big_endian>::Branch_info::make_stub(
2869     Stub_table<size, big_endian>* stub_table,
2870     Stub_table<size, big_endian>* ifunc_stub_table,
2871     Symbol_table* symtab) const
2872 {
2873   Symbol* sym = this->object_->global_symbol(this->r_sym_);
2874   if (sym != NULL && sym->is_forwarder())
2875     sym = symtab->resolve_forwards(sym);
2876   const Sized_symbol<size>* gsym = static_cast<const Sized_symbol<size>*>(sym);
2877   Target_powerpc<size, big_endian>* target =
2878     static_cast<Target_powerpc<size, big_endian>*>(
2879       parameters->sized_target<size, big_endian>());
2880   bool ok = true;
2881
2882   if (gsym != NULL
2883       ? gsym->use_plt_offset(Scan::get_reference_flags(this->r_type_, target))
2884       : this->object_->local_has_plt_offset(this->r_sym_))
2885     {
2886       if (size == 64
2887           && gsym != NULL
2888           && target->abiversion() >= 2
2889           && !parameters->options().output_is_position_independent()
2890           && !is_branch_reloc(this->r_type_))
2891         target->glink_section()->add_global_entry(gsym);
2892       else
2893         {
2894           if (stub_table == NULL)
2895             stub_table = this->object_->stub_table(this->shndx_);
2896           if (stub_table == NULL)
2897             {
2898               // This is a ref from a data section to an ifunc symbol.
2899               stub_table = ifunc_stub_table;
2900             }
2901           gold_assert(stub_table != NULL);
2902           Address from = this->object_->get_output_section_offset(this->shndx_);
2903           if (from != invalid_address)
2904             from += (this->object_->output_section(this->shndx_)->address()
2905                      + this->offset_);
2906           if (gsym != NULL)
2907             ok = stub_table->add_plt_call_entry(from,
2908                                                 this->object_, gsym,
2909                                                 this->r_type_, this->addend_);
2910           else
2911             ok = stub_table->add_plt_call_entry(from,
2912                                                 this->object_, this->r_sym_,
2913                                                 this->r_type_, this->addend_);
2914         }
2915     }
2916   else
2917     {
2918       Address max_branch_offset = max_branch_delta(this->r_type_);
2919       if (max_branch_offset == 0)
2920         return true;
2921       Address from = this->object_->get_output_section_offset(this->shndx_);
2922       gold_assert(from != invalid_address);
2923       from += (this->object_->output_section(this->shndx_)->address()
2924                + this->offset_);
2925       Address to;
2926       if (gsym != NULL)
2927         {
2928           switch (gsym->source())
2929             {
2930             case Symbol::FROM_OBJECT:
2931               {
2932                 Object* symobj = gsym->object();
2933                 if (symobj->is_dynamic()
2934                     || symobj->pluginobj() != NULL)
2935                   return true;
2936                 bool is_ordinary;
2937                 unsigned int shndx = gsym->shndx(&is_ordinary);
2938                 if (shndx == elfcpp::SHN_UNDEF)
2939                   return true;
2940               }
2941               break;
2942
2943             case Symbol::IS_UNDEFINED:
2944               return true;
2945
2946             default:
2947               break;
2948             }
2949           Symbol_table::Compute_final_value_status status;
2950           to = symtab->compute_final_value<size>(gsym, &status);
2951           if (status != Symbol_table::CFVS_OK)
2952             return true;
2953           if (size == 64)
2954             to += this->object_->ppc64_local_entry_offset(gsym);
2955         }
2956       else
2957         {
2958           const Symbol_value<size>* psymval
2959             = this->object_->local_symbol(this->r_sym_);
2960           Symbol_value<size> symval;
2961           if (psymval->is_section_symbol())
2962             symval.set_is_section_symbol();
2963           typedef Sized_relobj_file<size, big_endian> ObjType;
2964           typename ObjType::Compute_final_local_value_status status
2965             = this->object_->compute_final_local_value(this->r_sym_, psymval,
2966                                                        &symval, symtab);
2967           if (status != ObjType::CFLV_OK
2968               || !symval.has_output_value())
2969             return true;
2970           to = symval.value(this->object_, 0);
2971           if (size == 64)
2972             to += this->object_->ppc64_local_entry_offset(this->r_sym_);
2973         }
2974       if (!(size == 32 && this->r_type_ == elfcpp::R_PPC_PLTREL24))
2975         to += this->addend_;
2976       if (stub_table == NULL)
2977         stub_table = this->object_->stub_table(this->shndx_);
2978       if (size == 64 && target->abiversion() < 2)
2979         {
2980           unsigned int dest_shndx;
2981           if (!target->symval_for_branch(symtab, gsym, this->object_,
2982                                          &to, &dest_shndx))
2983             return true;
2984         }
2985       Address delta = to - from;
2986       if (delta + max_branch_offset >= 2 * max_branch_offset)
2987         {
2988           if (stub_table == NULL)
2989             {
2990               gold_warning(_("%s:%s: branch in non-executable section,"
2991                              " no long branch stub for you"),
2992                            this->object_->name().c_str(),
2993                            this->object_->section_name(this->shndx_).c_str());
2994               return true;
2995             }
2996           bool save_res = (size == 64
2997                            && gsym != NULL
2998                            && gsym->source() == Symbol::IN_OUTPUT_DATA
2999                            && gsym->output_data() == target->savres_section());
3000           ok = stub_table->add_long_branch_entry(this->object_,
3001                                                  this->r_type_,
3002                                                  from, to, save_res);
3003         }
3004     }
3005   if (!ok)
3006     gold_debug(DEBUG_TARGET,
3007                "branch at %s:%s+%#lx\n"
3008                "can't reach stub attached to %s:%s",
3009                this->object_->name().c_str(),
3010                this->object_->section_name(this->shndx_).c_str(),
3011                (unsigned long) this->offset_,
3012                stub_table->relobj()->name().c_str(),
3013                stub_table->relobj()->section_name(stub_table->shndx()).c_str());
3014
3015   return ok;
3016 }
3017
3018 // Relaxation hook.  This is where we do stub generation.
3019
3020 template<int size, bool big_endian>
3021 bool
3022 Target_powerpc<size, big_endian>::do_relax(int pass,
3023                                            const Input_objects*,
3024                                            Symbol_table* symtab,
3025                                            Layout* layout,
3026                                            const Task* task)
3027 {
3028   unsigned int prev_brlt_size = 0;
3029   if (pass == 1)
3030     {
3031       bool thread_safe
3032         = this->abiversion() < 2 && parameters->options().plt_thread_safe();
3033       if (size == 64
3034           && this->abiversion() < 2
3035           && !thread_safe
3036           && !parameters->options().user_set_plt_thread_safe())
3037         {
3038           static const char* const thread_starter[] =
3039             {
3040               "pthread_create",
3041               /* libstdc++ */
3042               "_ZNSt6thread15_M_start_threadESt10shared_ptrINS_10_Impl_baseEE",
3043               /* librt */
3044               "aio_init", "aio_read", "aio_write", "aio_fsync", "lio_listio",
3045               "mq_notify", "create_timer",
3046               /* libanl */
3047               "getaddrinfo_a",
3048               /* libgomp */
3049               "GOMP_parallel",
3050               "GOMP_parallel_start",
3051               "GOMP_parallel_loop_static",
3052               "GOMP_parallel_loop_static_start",
3053               "GOMP_parallel_loop_dynamic",
3054               "GOMP_parallel_loop_dynamic_start",
3055               "GOMP_parallel_loop_guided",
3056               "GOMP_parallel_loop_guided_start",
3057               "GOMP_parallel_loop_runtime",
3058               "GOMP_parallel_loop_runtime_start",
3059               "GOMP_parallel_sections",
3060               "GOMP_parallel_sections_start",
3061               /* libgo */
3062               "__go_go",
3063             };
3064
3065           if (parameters->options().shared())
3066             thread_safe = true;
3067           else
3068             {
3069               for (unsigned int i = 0;
3070                    i < sizeof(thread_starter) / sizeof(thread_starter[0]);
3071                    i++)
3072                 {
3073                   Symbol* sym = symtab->lookup(thread_starter[i], NULL);
3074                   thread_safe = (sym != NULL
3075                                  && sym->in_reg()
3076                                  && sym->in_real_elf());
3077                   if (thread_safe)
3078                     break;
3079                 }
3080             }
3081         }
3082       this->plt_thread_safe_ = thread_safe;
3083     }
3084
3085   if (pass == 1)
3086     {
3087       this->stub_group_size_ = parameters->options().stub_group_size();
3088       bool no_size_errors = true;
3089       if (this->stub_group_size_ == 1)
3090         this->stub_group_size_ = 0x1c00000;
3091       else if (this->stub_group_size_ == -1)
3092         this->stub_group_size_ = -0x1e00000;
3093       else
3094         no_size_errors = false;
3095       this->group_sections(layout, task, no_size_errors);
3096     }
3097   else if (this->relax_failed_ && this->relax_fail_count_ < 3)
3098     {
3099       this->branch_lookup_table_.clear();
3100       for (typename Stub_tables::iterator p = this->stub_tables_.begin();
3101            p != this->stub_tables_.end();
3102            ++p)
3103         {
3104           (*p)->clear_stubs(true);
3105         }
3106       this->stub_tables_.clear();
3107       this->stub_group_size_ = this->stub_group_size_ / 4 * 3;
3108       gold_info(_("%s: stub group size is too large; retrying with %#x"),
3109                 program_name, this->stub_group_size_);
3110       this->group_sections(layout, task, true);
3111     }
3112
3113   // We need address of stub tables valid for make_stub.
3114   for (typename Stub_tables::iterator p = this->stub_tables_.begin();
3115        p != this->stub_tables_.end();
3116        ++p)
3117     {
3118       const Powerpc_relobj<size, big_endian>* object
3119         = static_cast<const Powerpc_relobj<size, big_endian>*>((*p)->relobj());
3120       Address off = object->get_output_section_offset((*p)->shndx());
3121       gold_assert(off != invalid_address);
3122       Output_section* os = (*p)->output_section();
3123       (*p)->set_address_and_size(os, off);
3124     }
3125
3126   if (pass != 1)
3127     {
3128       // Clear plt call stubs, long branch stubs and branch lookup table.
3129       prev_brlt_size = this->branch_lookup_table_.size();
3130       this->branch_lookup_table_.clear();
3131       for (typename Stub_tables::iterator p = this->stub_tables_.begin();
3132            p != this->stub_tables_.end();
3133            ++p)
3134         {
3135           (*p)->clear_stubs(false);
3136         }
3137     }
3138
3139   // Build all the stubs.
3140   this->relax_failed_ = false;
3141   Stub_table<size, big_endian>* ifunc_stub_table
3142     = this->stub_tables_.size() == 0 ? NULL : this->stub_tables_[0];
3143   Stub_table<size, big_endian>* one_stub_table
3144     = this->stub_tables_.size() != 1 ? NULL : ifunc_stub_table;
3145   for (typename Branches::const_iterator b = this->branch_info_.begin();
3146        b != this->branch_info_.end();
3147        b++)
3148     {
3149       if (!b->make_stub(one_stub_table, ifunc_stub_table, symtab)
3150           && !this->relax_failed_)
3151         {
3152           this->relax_failed_ = true;
3153           this->relax_fail_count_++;
3154           if (this->relax_fail_count_ < 3)
3155             return true;
3156         }
3157     }
3158
3159   // Did anything change size?
3160   unsigned int num_huge_branches = this->branch_lookup_table_.size();
3161   bool again = num_huge_branches != prev_brlt_size;
3162   if (size == 64 && num_huge_branches != 0)
3163     this->make_brlt_section(layout);
3164   if (size == 64 && again)
3165     this->brlt_section_->set_current_size(num_huge_branches);
3166
3167   typedef Unordered_set<Output_section*> Output_sections;
3168   Output_sections os_need_update;
3169   for (typename Stub_tables::iterator p = this->stub_tables_.begin();
3170        p != this->stub_tables_.end();
3171        ++p)
3172     {
3173       if ((*p)->size_update())
3174         {
3175           again = true;
3176           (*p)->add_eh_frame(layout);
3177           os_need_update.insert((*p)->output_section());
3178         }
3179     }
3180
3181   // Set output section offsets for all input sections in an output
3182   // section that just changed size.  Anything past the stubs will
3183   // need updating.
3184   for (typename Output_sections::iterator p = os_need_update.begin();
3185        p != os_need_update.end();
3186        p++)
3187     {
3188       Output_section* os = *p;
3189       Address off = 0;
3190       typedef Output_section::Input_section_list Input_section_list;
3191       for (Input_section_list::const_iterator i = os->input_sections().begin();
3192            i != os->input_sections().end();
3193            ++i)
3194         {
3195           off = align_address(off, i->addralign());
3196           if (i->is_input_section() || i->is_relaxed_input_section())
3197             i->relobj()->set_section_offset(i->shndx(), off);
3198           if (i->is_relaxed_input_section())
3199             {
3200               Stub_table<size, big_endian>* stub_table
3201                 = static_cast<Stub_table<size, big_endian>*>(
3202                     i->relaxed_input_section());
3203               Address stub_table_size = stub_table->set_address_and_size(os, off);
3204               off += stub_table_size;
3205               // After a few iterations, set current stub table size
3206               // as min size threshold, so later stub tables can only
3207               // grow in size.
3208               if (pass >= 4)
3209                 stub_table->set_min_size_threshold(stub_table_size);
3210             }
3211           else
3212             off += i->data_size();
3213         }
3214       // If .branch_lt is part of this output section, then we have
3215       // just done the offset adjustment.
3216       os->clear_section_offsets_need_adjustment();
3217     }
3218
3219   if (size == 64
3220       && !again
3221       && num_huge_branches != 0
3222       && parameters->options().output_is_position_independent())
3223     {
3224       // Fill in the BRLT relocs.
3225       this->brlt_section_->reset_brlt_sizes();
3226       for (typename Branch_lookup_table::const_iterator p
3227              = this->branch_lookup_table_.begin();
3228            p != this->branch_lookup_table_.end();
3229            ++p)
3230         {
3231           this->brlt_section_->add_reloc(p->first, p->second);
3232         }
3233       this->brlt_section_->finalize_brlt_sizes();
3234     }
3235   return again;
3236 }
3237
3238 template<int size, bool big_endian>
3239 void
3240 Target_powerpc<size, big_endian>::do_plt_fde_location(const Output_data* plt,
3241                                                       unsigned char* oview,
3242                                                       uint64_t* paddress,
3243                                                       off_t* plen) const
3244 {
3245   uint64_t address = plt->address();
3246   off_t len = plt->data_size();
3247
3248   if (plt == this->glink_)
3249     {
3250       // See Output_data_glink::do_write() for glink contents.
3251       if (len == 0)
3252         {
3253           gold_assert(parameters->doing_static_link());
3254           // Static linking may need stubs, to support ifunc and long
3255           // branches.  We need to create an output section for
3256           // .eh_frame early in the link process, to have a place to
3257           // attach stub .eh_frame info.  We also need to have
3258           // registered a CIE that matches the stub CIE.  Both of
3259           // these requirements are satisfied by creating an FDE and
3260           // CIE for .glink, even though static linking will leave
3261           // .glink zero length.
3262           // ??? Hopefully generating an FDE with a zero address range
3263           // won't confuse anything that consumes .eh_frame info.
3264         }
3265       else if (size == 64)
3266         {
3267           // There is one word before __glink_PLTresolve
3268           address += 8;
3269           len -= 8;
3270         }
3271       else if (parameters->options().output_is_position_independent())
3272         {
3273           // There are two FDEs for a position independent glink.
3274           // The first covers the branch table, the second
3275           // __glink_PLTresolve at the end of glink.
3276           off_t resolve_size = this->glink_->pltresolve_size;
3277           if (oview[9] == elfcpp::DW_CFA_nop)
3278             len -= resolve_size;
3279           else
3280             {
3281               address += len - resolve_size;
3282               len = resolve_size;
3283             }
3284         }
3285     }
3286   else
3287     {
3288       // Must be a stub table.
3289       const Stub_table<size, big_endian>* stub_table
3290         = static_cast<const Stub_table<size, big_endian>*>(plt);
3291       uint64_t stub_address = stub_table->stub_address();
3292       len -= stub_address - address;
3293       address = stub_address;
3294     }
3295
3296   *paddress = address;
3297   *plen = len;
3298 }
3299
3300 // A class to handle the PLT data.
3301
3302 template<int size, bool big_endian>
3303 class Output_data_plt_powerpc : public Output_section_data_build
3304 {
3305  public:
3306   typedef Output_data_reloc<elfcpp::SHT_RELA, true,
3307                             size, big_endian> Reloc_section;
3308
3309   Output_data_plt_powerpc(Target_powerpc<size, big_endian>* targ,
3310                           Reloc_section* plt_rel,
3311                           const char* name)
3312     : Output_section_data_build(size == 32 ? 4 : 8),
3313       rel_(plt_rel),
3314       targ_(targ),
3315       name_(name)
3316   { }
3317
3318   // Add an entry to the PLT.
3319   void
3320   add_entry(Symbol*);
3321
3322   void
3323   add_ifunc_entry(Symbol*);
3324
3325   void
3326   add_local_ifunc_entry(Sized_relobj_file<size, big_endian>*, unsigned int);
3327
3328   // Return the .rela.plt section data.
3329   Reloc_section*
3330   rel_plt() const
3331   {
3332     return this->rel_;
3333   }
3334
3335   // Return the number of PLT entries.
3336   unsigned int
3337   entry_count() const
3338   {
3339     if (this->current_data_size() == 0)
3340       return 0;
3341     return ((this->current_data_size() - this->first_plt_entry_offset())
3342             / this->plt_entry_size());
3343   }
3344
3345  protected:
3346   void
3347   do_adjust_output_section(Output_section* os)
3348   {
3349     os->set_entsize(0);
3350   }
3351
3352   // Write to a map file.
3353   void
3354   do_print_to_mapfile(Mapfile* mapfile) const
3355   { mapfile->print_output_data(this, this->name_); }
3356
3357  private:
3358   // Return the offset of the first non-reserved PLT entry.
3359   unsigned int
3360   first_plt_entry_offset() const
3361   {
3362     // IPLT has no reserved entry.
3363     if (this->name_[3] == 'I')
3364       return 0;
3365     return this->targ_->first_plt_entry_offset();
3366   }
3367
3368   // Return the size of each PLT entry.
3369   unsigned int
3370   plt_entry_size() const
3371   {
3372     return this->targ_->plt_entry_size();
3373   }
3374
3375   // Write out the PLT data.
3376   void
3377   do_write(Output_file*);
3378
3379   // The reloc section.
3380   Reloc_section* rel_;
3381   // Allows access to .glink for do_write.
3382   Target_powerpc<size, big_endian>* targ_;
3383   // What to report in map file.
3384   const char *name_;
3385 };
3386
3387 // Add an entry to the PLT.
3388
3389 template<int size, bool big_endian>
3390 void
3391 Output_data_plt_powerpc<size, big_endian>::add_entry(Symbol* gsym)
3392 {
3393   if (!gsym->has_plt_offset())
3394     {
3395       section_size_type off = this->current_data_size();
3396       if (off == 0)
3397         off += this->first_plt_entry_offset();
3398       gsym->set_plt_offset(off);
3399       gsym->set_needs_dynsym_entry();
3400       unsigned int dynrel = elfcpp::R_POWERPC_JMP_SLOT;
3401       this->rel_->add_global(gsym, dynrel, this, off, 0);
3402       off += this->plt_entry_size();
3403       this->set_current_data_size(off);
3404     }
3405 }
3406
3407 // Add an entry for a global ifunc symbol that resolves locally, to the IPLT.
3408
3409 template<int size, bool big_endian>
3410 void
3411 Output_data_plt_powerpc<size, big_endian>::add_ifunc_entry(Symbol* gsym)
3412 {
3413   if (!gsym->has_plt_offset())
3414     {
3415       section_size_type off = this->current_data_size();
3416       gsym->set_plt_offset(off);
3417       unsigned int dynrel = elfcpp::R_POWERPC_IRELATIVE;
3418       if (size == 64 && this->targ_->abiversion() < 2)
3419         dynrel = elfcpp::R_PPC64_JMP_IREL;
3420       this->rel_->add_symbolless_global_addend(gsym, dynrel, this, off, 0);
3421       off += this->plt_entry_size();
3422       this->set_current_data_size(off);
3423     }
3424 }
3425
3426 // Add an entry for a local ifunc symbol to the IPLT.
3427
3428 template<int size, bool big_endian>
3429 void
3430 Output_data_plt_powerpc<size, big_endian>::add_local_ifunc_entry(
3431     Sized_relobj_file<size, big_endian>* relobj,
3432     unsigned int local_sym_index)
3433 {
3434   if (!relobj->local_has_plt_offset(local_sym_index))
3435     {
3436       section_size_type off = this->current_data_size();
3437       relobj->set_local_plt_offset(local_sym_index, off);
3438       unsigned int dynrel = elfcpp::R_POWERPC_IRELATIVE;
3439       if (size == 64 && this->targ_->abiversion() < 2)
3440         dynrel = elfcpp::R_PPC64_JMP_IREL;
3441       this->rel_->add_symbolless_local_addend(relobj, local_sym_index, dynrel,
3442                                               this, off, 0);
3443       off += this->plt_entry_size();
3444       this->set_current_data_size(off);
3445     }
3446 }
3447
3448 static const uint32_t add_0_11_11       = 0x7c0b5a14;
3449 static const uint32_t add_2_2_11        = 0x7c425a14;
3450 static const uint32_t add_2_2_12        = 0x7c426214;
3451 static const uint32_t add_3_3_2         = 0x7c631214;
3452 static const uint32_t add_3_3_13        = 0x7c636a14;
3453 static const uint32_t add_11_0_11       = 0x7d605a14;
3454 static const uint32_t add_11_2_11       = 0x7d625a14;
3455 static const uint32_t add_11_11_2       = 0x7d6b1214;
3456 static const uint32_t addi_0_12         = 0x380c0000;
3457 static const uint32_t addi_2_2          = 0x38420000;
3458 static const uint32_t addi_3_3          = 0x38630000;
3459 static const uint32_t addi_11_11        = 0x396b0000;
3460 static const uint32_t addi_12_1         = 0x39810000;
3461 static const uint32_t addi_12_12        = 0x398c0000;
3462 static const uint32_t addis_0_2         = 0x3c020000;
3463 static const uint32_t addis_0_13        = 0x3c0d0000;
3464 static const uint32_t addis_2_12        = 0x3c4c0000;
3465 static const uint32_t addis_11_2        = 0x3d620000;
3466 static const uint32_t addis_11_11       = 0x3d6b0000;
3467 static const uint32_t addis_11_30       = 0x3d7e0000;
3468 static const uint32_t addis_12_1        = 0x3d810000;
3469 static const uint32_t addis_12_2        = 0x3d820000;
3470 static const uint32_t addis_12_12       = 0x3d8c0000;
3471 static const uint32_t b                 = 0x48000000;
3472 static const uint32_t bcl_20_31         = 0x429f0005;
3473 static const uint32_t bctr              = 0x4e800420;
3474 static const uint32_t blr               = 0x4e800020;
3475 static const uint32_t bnectr_p4         = 0x4ce20420;
3476 static const uint32_t cmpld_7_12_0      = 0x7fac0040;
3477 static const uint32_t cmpldi_2_0        = 0x28220000;
3478 static const uint32_t cror_15_15_15     = 0x4def7b82;
3479 static const uint32_t cror_31_31_31     = 0x4ffffb82;
3480 static const uint32_t ld_0_1            = 0xe8010000;
3481 static const uint32_t ld_0_12           = 0xe80c0000;
3482 static const uint32_t ld_2_1            = 0xe8410000;
3483 static const uint32_t ld_2_2            = 0xe8420000;
3484 static const uint32_t ld_2_11           = 0xe84b0000;
3485 static const uint32_t ld_2_12           = 0xe84c0000;
3486 static const uint32_t ld_11_2           = 0xe9620000;
3487 static const uint32_t ld_11_11          = 0xe96b0000;
3488 static const uint32_t ld_12_2           = 0xe9820000;
3489 static const uint32_t ld_12_11          = 0xe98b0000;
3490 static const uint32_t ld_12_12          = 0xe98c0000;
3491 static const uint32_t lfd_0_1           = 0xc8010000;
3492 static const uint32_t li_0_0            = 0x38000000;
3493 static const uint32_t li_12_0           = 0x39800000;
3494 static const uint32_t lis_0             = 0x3c000000;
3495 static const uint32_t lis_2             = 0x3c400000;
3496 static const uint32_t lis_11            = 0x3d600000;
3497 static const uint32_t lis_12            = 0x3d800000;
3498 static const uint32_t lvx_0_12_0        = 0x7c0c00ce;
3499 static const uint32_t lwz_0_12          = 0x800c0000;
3500 static const uint32_t lwz_11_11         = 0x816b0000;
3501 static const uint32_t lwz_11_30         = 0x817e0000;
3502 static const uint32_t lwz_12_12         = 0x818c0000;
3503 static const uint32_t lwzu_0_12         = 0x840c0000;
3504 static const uint32_t mflr_0            = 0x7c0802a6;
3505 static const uint32_t mflr_11           = 0x7d6802a6;
3506 static const uint32_t mflr_12           = 0x7d8802a6;
3507 static const uint32_t mtctr_0           = 0x7c0903a6;
3508 static const uint32_t mtctr_11          = 0x7d6903a6;
3509 static const uint32_t mtctr_12          = 0x7d8903a6;
3510 static const uint32_t mtlr_0            = 0x7c0803a6;
3511 static const uint32_t mtlr_12           = 0x7d8803a6;
3512 static const uint32_t nop               = 0x60000000;
3513 static const uint32_t ori_0_0_0         = 0x60000000;
3514 static const uint32_t srdi_0_0_2        = 0x7800f082;
3515 static const uint32_t std_0_1           = 0xf8010000;
3516 static const uint32_t std_0_12          = 0xf80c0000;
3517 static const uint32_t std_2_1           = 0xf8410000;
3518 static const uint32_t stfd_0_1          = 0xd8010000;
3519 static const uint32_t stvx_0_12_0       = 0x7c0c01ce;
3520 static const uint32_t sub_11_11_12      = 0x7d6c5850;
3521 static const uint32_t sub_12_12_11      = 0x7d8b6050;
3522 static const uint32_t xor_2_12_12       = 0x7d826278;
3523 static const uint32_t xor_11_12_12      = 0x7d8b6278;
3524
3525 // Write out the PLT.
3526
3527 template<int size, bool big_endian>
3528 void
3529 Output_data_plt_powerpc<size, big_endian>::do_write(Output_file* of)
3530 {
3531   if (size == 32 && this->name_[3] != 'I')
3532     {
3533       const section_size_type offset = this->offset();
3534       const section_size_type oview_size
3535         = convert_to_section_size_type(this->data_size());
3536       unsigned char* const oview = of->get_output_view(offset, oview_size);
3537       unsigned char* pov = oview;
3538       unsigned char* endpov = oview + oview_size;
3539
3540       // The address of the .glink branch table
3541       const Output_data_glink<size, big_endian>* glink
3542         = this->targ_->glink_section();
3543       elfcpp::Elf_types<32>::Elf_Addr branch_tab = glink->address();
3544
3545       while (pov < endpov)
3546         {
3547           elfcpp::Swap<32, big_endian>::writeval(pov, branch_tab);
3548           pov += 4;
3549           branch_tab += 4;
3550         }
3551
3552       of->write_output_view(offset, oview_size, oview);
3553     }
3554 }
3555
3556 // Create the PLT section.
3557
3558 template<int size, bool big_endian>
3559 void
3560 Target_powerpc<size, big_endian>::make_plt_section(Symbol_table* symtab,
3561                                                    Layout* layout)
3562 {
3563   if (this->plt_ == NULL)
3564     {
3565       if (this->got_ == NULL)
3566         this->got_section(symtab, layout);
3567
3568       if (this->glink_ == NULL)
3569         make_glink_section(layout);
3570
3571       // Ensure that .rela.dyn always appears before .rela.plt  This is
3572       // necessary due to how, on PowerPC and some other targets, .rela.dyn
3573       // needs to include .rela.plt in its range.
3574       this->rela_dyn_section(layout);
3575
3576       Reloc_section* plt_rel = new Reloc_section(false);
3577       layout->add_output_section_data(".rela.plt", elfcpp::SHT_RELA,
3578                                       elfcpp::SHF_ALLOC, plt_rel,
3579                                       ORDER_DYNAMIC_PLT_RELOCS, false);
3580       this->plt_
3581         = new Output_data_plt_powerpc<size, big_endian>(this, plt_rel,
3582                                                         "** PLT");
3583       layout->add_output_section_data(".plt",
3584                                       (size == 32
3585                                        ? elfcpp::SHT_PROGBITS
3586                                        : elfcpp::SHT_NOBITS),
3587                                       elfcpp::SHF_ALLOC | elfcpp::SHF_WRITE,
3588                                       this->plt_,
3589                                       (size == 32
3590                                        ? ORDER_SMALL_DATA
3591                                        : ORDER_SMALL_BSS),
3592                                       false);
3593
3594       Output_section* rela_plt_os = plt_rel->output_section();
3595       rela_plt_os->set_info_section(this->plt_->output_section());
3596     }
3597 }
3598
3599 // Create the IPLT section.
3600
3601 template<int size, bool big_endian>
3602 void
3603 Target_powerpc<size, big_endian>::make_iplt_section(Symbol_table* symtab,
3604                                                     Layout* layout)
3605 {
3606   if (this->iplt_ == NULL)
3607     {
3608       this->make_plt_section(symtab, layout);
3609
3610       Reloc_section* iplt_rel = new Reloc_section(false);
3611       if (this->rela_dyn_->output_section())
3612         this->rela_dyn_->output_section()->add_output_section_data(iplt_rel);
3613       this->iplt_
3614         = new Output_data_plt_powerpc<size, big_endian>(this, iplt_rel,
3615                                                         "** IPLT");
3616       if (this->plt_->output_section())
3617         this->plt_->output_section()->add_output_section_data(this->iplt_);
3618     }
3619 }
3620
3621 // A section for huge long branch addresses, similar to plt section.
3622
3623 template<int size, bool big_endian>
3624 class Output_data_brlt_powerpc : public Output_section_data_build
3625 {
3626  public:
3627   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
3628   typedef Output_data_reloc<elfcpp::SHT_RELA, true,
3629                             size, big_endian> Reloc_section;
3630
3631   Output_data_brlt_powerpc(Target_powerpc<size, big_endian>* targ,
3632                            Reloc_section* brlt_rel)
3633     : Output_section_data_build(size == 32 ? 4 : 8),
3634       rel_(brlt_rel),
3635       targ_(targ)
3636   { }
3637
3638   void
3639   reset_brlt_sizes()
3640   {
3641     this->reset_data_size();
3642     this->rel_->reset_data_size();
3643   }
3644
3645   void
3646   finalize_brlt_sizes()
3647   {
3648     this->finalize_data_size();
3649     this->rel_->finalize_data_size();
3650   }
3651
3652   // Add a reloc for an entry in the BRLT.
3653   void
3654   add_reloc(Address to, unsigned int off)
3655   { this->rel_->add_relative(elfcpp::R_POWERPC_RELATIVE, this, off, to); }
3656
3657   // Update section and reloc section size.
3658   void
3659   set_current_size(unsigned int num_branches)
3660   {
3661     this->reset_address_and_file_offset();
3662     this->set_current_data_size(num_branches * 16);
3663     this->finalize_data_size();
3664     Output_section* os = this->output_section();
3665     os->set_section_offsets_need_adjustment();
3666     if (this->rel_ != NULL)
3667       {
3668         const unsigned int reloc_size = elfcpp::Elf_sizes<size>::rela_size;
3669         this->rel_->reset_address_and_file_offset();
3670         this->rel_->set_current_data_size(num_branches * reloc_size);
3671         this->rel_->finalize_data_size();
3672         Output_section* os = this->rel_->output_section();
3673         os->set_section_offsets_need_adjustment();
3674       }
3675   }
3676
3677  protected:
3678   void
3679   do_adjust_output_section(Output_section* os)
3680   {
3681     os->set_entsize(0);
3682   }
3683
3684   // Write to a map file.
3685   void
3686   do_print_to_mapfile(Mapfile* mapfile) const
3687   { mapfile->print_output_data(this, "** BRLT"); }
3688
3689  private:
3690   // Write out the BRLT data.
3691   void
3692   do_write(Output_file*);
3693
3694   // The reloc section.
3695   Reloc_section* rel_;
3696   Target_powerpc<size, big_endian>* targ_;
3697 };
3698
3699 // Make the branch lookup table section.
3700
3701 template<int size, bool big_endian>
3702 void
3703 Target_powerpc<size, big_endian>::make_brlt_section(Layout* layout)
3704 {
3705   if (size == 64 && this->brlt_section_ == NULL)
3706     {
3707       Reloc_section* brlt_rel = NULL;
3708       bool is_pic = parameters->options().output_is_position_independent();
3709       if (is_pic)
3710         {
3711           // When PIC we can't fill in .branch_lt (like .plt it can be
3712           // a bss style section) but must initialise at runtime via
3713           // dynamic relocations.
3714           this->rela_dyn_section(layout);
3715           brlt_rel = new Reloc_section(false);
3716           if (this->rela_dyn_->output_section())
3717             this->rela_dyn_->output_section()
3718               ->add_output_section_data(brlt_rel);
3719         }
3720       this->brlt_section_
3721         = new Output_data_brlt_powerpc<size, big_endian>(this, brlt_rel);
3722       if (this->plt_ && is_pic && this->plt_->output_section())
3723         this->plt_->output_section()
3724           ->add_output_section_data(this->brlt_section_);
3725       else
3726         layout->add_output_section_data(".branch_lt",
3727                                         (is_pic ? elfcpp::SHT_NOBITS
3728                                          : elfcpp::SHT_PROGBITS),
3729                                         elfcpp::SHF_ALLOC | elfcpp::SHF_WRITE,
3730                                         this->brlt_section_,
3731                                         (is_pic ? ORDER_SMALL_BSS
3732                                          : ORDER_SMALL_DATA),
3733                                         false);
3734     }
3735 }
3736
3737 // Write out .branch_lt when non-PIC.
3738
3739 template<int size, bool big_endian>
3740 void
3741 Output_data_brlt_powerpc<size, big_endian>::do_write(Output_file* of)
3742 {
3743   if (size == 64 && !parameters->options().output_is_position_independent())
3744     {
3745       const section_size_type offset = this->offset();
3746       const section_size_type oview_size
3747         = convert_to_section_size_type(this->data_size());
3748       unsigned char* const oview = of->get_output_view(offset, oview_size);
3749
3750       this->targ_->write_branch_lookup_table(oview);
3751       of->write_output_view(offset, oview_size, oview);
3752     }
3753 }
3754
3755 static inline uint32_t
3756 l(uint32_t a)
3757 {
3758   return a & 0xffff;
3759 }
3760
3761 static inline uint32_t
3762 hi(uint32_t a)
3763 {
3764   return l(a >> 16);
3765 }
3766
3767 static inline uint32_t
3768 ha(uint32_t a)
3769 {
3770   return hi(a + 0x8000);
3771 }
3772
3773 template<int size>
3774 struct Eh_cie
3775 {
3776   static const unsigned char eh_frame_cie[12];
3777 };
3778
3779 template<int size>
3780 const unsigned char Eh_cie<size>::eh_frame_cie[] =
3781 {
3782   1,                                    // CIE version.
3783   'z', 'R', 0,                          // Augmentation string.
3784   4,                                    // Code alignment.
3785   0x80 - size / 8 ,                     // Data alignment.
3786   65,                                   // RA reg.
3787   1,                                    // Augmentation size.
3788   (elfcpp::DW_EH_PE_pcrel
3789    | elfcpp::DW_EH_PE_sdata4),          // FDE encoding.
3790   elfcpp::DW_CFA_def_cfa, 1, 0          // def_cfa: r1 offset 0.
3791 };
3792
3793 // Describe __glink_PLTresolve use of LR, 64-bit version ABIv1.
3794 static const unsigned char glink_eh_frame_fde_64v1[] =
3795 {
3796   0, 0, 0, 0,                           // Replaced with offset to .glink.
3797   0, 0, 0, 0,                           // Replaced with size of .glink.
3798   0,                                    // Augmentation size.
3799   elfcpp::DW_CFA_advance_loc + 1,
3800   elfcpp::DW_CFA_register, 65, 12,
3801   elfcpp::DW_CFA_advance_loc + 4,
3802   elfcpp::DW_CFA_restore_extended, 65
3803 };
3804
3805 // Describe __glink_PLTresolve use of LR, 64-bit version ABIv2.
3806 static const unsigned char glink_eh_frame_fde_64v2[] =
3807 {
3808   0, 0, 0, 0,                           // Replaced with offset to .glink.
3809   0, 0, 0, 0,                           // Replaced with size of .glink.
3810   0,                                    // Augmentation size.
3811   elfcpp::DW_CFA_advance_loc + 1,
3812   elfcpp::DW_CFA_register, 65, 0,
3813   elfcpp::DW_CFA_advance_loc + 4,
3814   elfcpp::DW_CFA_restore_extended, 65
3815 };
3816
3817 // Describe __glink_PLTresolve use of LR, 32-bit version.
3818 static const unsigned char glink_eh_frame_fde_32[] =
3819 {
3820   0, 0, 0, 0,                           // Replaced with offset to .glink.
3821   0, 0, 0, 0,                           // Replaced with size of .glink.
3822   0,                                    // Augmentation size.
3823   elfcpp::DW_CFA_advance_loc + 2,
3824   elfcpp::DW_CFA_register, 65, 0,
3825   elfcpp::DW_CFA_advance_loc + 4,
3826   elfcpp::DW_CFA_restore_extended, 65
3827 };
3828
3829 static const unsigned char default_fde[] =
3830 {
3831   0, 0, 0, 0,                           // Replaced with offset to stubs.
3832   0, 0, 0, 0,                           // Replaced with size of stubs.
3833   0,                                    // Augmentation size.
3834   elfcpp::DW_CFA_nop,                   // Pad.
3835   elfcpp::DW_CFA_nop,
3836   elfcpp::DW_CFA_nop
3837 };
3838
3839 template<bool big_endian>
3840 static inline void
3841 write_insn(unsigned char* p, uint32_t v)
3842 {
3843   elfcpp::Swap<32, big_endian>::writeval(p, v);
3844 }
3845
3846 // Stub_table holds information about plt and long branch stubs.
3847 // Stubs are built in an area following some input section determined
3848 // by group_sections().  This input section is converted to a relaxed
3849 // input section allowing it to be resized to accommodate the stubs
3850
3851 template<int size, bool big_endian>
3852 class Stub_table : public Output_relaxed_input_section
3853 {
3854  public:
3855   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
3856   static const Address invalid_address = static_cast<Address>(0) - 1;
3857
3858   Stub_table(Target_powerpc<size, big_endian>* targ,
3859              Output_section* output_section,
3860              const Output_section::Input_section* owner)
3861     : Output_relaxed_input_section(owner->relobj(), owner->shndx(),
3862                                    owner->relobj()
3863                                    ->section_addralign(owner->shndx())),
3864       targ_(targ), plt_call_stubs_(), long_branch_stubs_(),
3865       orig_data_size_(owner->current_data_size()),
3866       plt_size_(0), last_plt_size_(0),
3867       branch_size_(0), last_branch_size_(0), min_size_threshold_(0),
3868       eh_frame_added_(false), need_save_res_(false)
3869   {
3870     this->set_output_section(output_section);
3871
3872     std::vector<Output_relaxed_input_section*> new_relaxed;
3873     new_relaxed.push_back(this);
3874     output_section->convert_input_sections_to_relaxed_sections(new_relaxed);
3875   }
3876
3877   // Add a plt call stub.
3878   bool
3879   add_plt_call_entry(Address,
3880                      const Sized_relobj_file<size, big_endian>*,
3881                      const Symbol*,
3882                      unsigned int,
3883                      Address);
3884
3885   bool
3886   add_plt_call_entry(Address,
3887                      const Sized_relobj_file<size, big_endian>*,
3888                      unsigned int,
3889                      unsigned int,
3890                      Address);
3891
3892   // Find a given plt call stub.
3893   Address
3894   find_plt_call_entry(const Symbol*) const;
3895
3896   Address
3897   find_plt_call_entry(const Sized_relobj_file<size, big_endian>*,
3898                       unsigned int) const;
3899
3900   Address
3901   find_plt_call_entry(const Sized_relobj_file<size, big_endian>*,
3902                       const Symbol*,
3903                       unsigned int,
3904                       Address) const;
3905
3906   Address
3907   find_plt_call_entry(const Sized_relobj_file<size, big_endian>*,
3908                       unsigned int,
3909                       unsigned int,
3910                       Address) const;
3911
3912   // Add a long branch stub.
3913   bool
3914   add_long_branch_entry(const Powerpc_relobj<size, big_endian>*,
3915                         unsigned int, Address, Address, bool);
3916
3917   Address
3918   find_long_branch_entry(const Powerpc_relobj<size, big_endian>*,
3919                          Address) const;
3920
3921   bool
3922   can_reach_stub(Address from, unsigned int off, unsigned int r_type)
3923   {
3924     Address max_branch_offset = max_branch_delta(r_type);
3925     if (max_branch_offset == 0)
3926       return true;
3927     gold_assert(from != invalid_address);
3928     Address loc = off + this->stub_address();
3929     return loc - from + max_branch_offset < 2 * max_branch_offset;
3930   }
3931
3932   void
3933   clear_stubs(bool all)
3934   {
3935     this->plt_call_stubs_.clear();
3936     this->plt_size_ = 0;
3937     this->long_branch_stubs_.clear();
3938     this->branch_size_ = 0;
3939     this->need_save_res_ = false;
3940     if (all)
3941       {
3942         this->last_plt_size_ = 0;
3943         this->last_branch_size_ = 0;
3944       }
3945   }
3946
3947   Address
3948   set_address_and_size(const Output_section* os, Address off)
3949   {
3950     Address start_off = off;
3951     off += this->orig_data_size_;
3952     Address my_size = this->plt_size_ + this->branch_size_;
3953     if (this->need_save_res_)
3954       my_size += this->targ_->savres_section()->data_size();
3955     if (my_size != 0)
3956       off = align_address(off, this->stub_align());
3957     // Include original section size and alignment padding in size
3958     my_size += off - start_off;
3959     // Ensure new size is always larger than min size
3960     // threshold. Alignment requirement is included in "my_size", so
3961     // increase "my_size" does not invalidate alignment.
3962     if (my_size < this->min_size_threshold_)
3963       my_size = this->min_size_threshold_;
3964     this->reset_address_and_file_offset();
3965     this->set_current_data_size(my_size);
3966     this->set_address_and_file_offset(os->address() + start_off,
3967                                       os->offset() + start_off);
3968     return my_size;
3969   }
3970
3971   Address
3972   stub_address() const
3973   {
3974     return align_address(this->address() + this->orig_data_size_,
3975                          this->stub_align());
3976   }
3977
3978   Address
3979   stub_offset() const
3980   {
3981     return align_address(this->offset() + this->orig_data_size_,
3982                          this->stub_align());
3983   }
3984
3985   section_size_type
3986   plt_size() const
3987   { return this->plt_size_; }
3988
3989   void set_min_size_threshold(Address min_size)
3990   { this->min_size_threshold_ = min_size; }
3991
3992   bool
3993   size_update()
3994   {
3995     Output_section* os = this->output_section();
3996     if (os->addralign() < this->stub_align())
3997       {
3998         os->set_addralign(this->stub_align());
3999         // FIXME: get rid of the insane checkpointing.
4000         // We can't increase alignment of the input section to which
4001         // stubs are attached;  The input section may be .init which
4002         // is pasted together with other .init sections to form a
4003         // function.  Aligning might insert zero padding resulting in
4004         // sigill.  However we do need to increase alignment of the
4005         // output section so that the align_address() on offset in
4006         // set_address_and_size() adds the same padding as the
4007         // align_address() on address in stub_address().
4008         // What's more, we need this alignment for the layout done in
4009         // relaxation_loop_body() so that the output section starts at
4010         // a suitably aligned address.
4011         os->checkpoint_set_addralign(this->stub_align());
4012       }
4013     if (this->last_plt_size_ != this->plt_size_
4014         || this->last_branch_size_ != this->branch_size_)
4015       {
4016         this->last_plt_size_ = this->plt_size_;
4017         this->last_branch_size_ = this->branch_size_;
4018         return true;
4019       }
4020     return false;
4021   }
4022
4023   // Add .eh_frame info for this stub section.  Unlike other linker
4024   // generated .eh_frame this is added late in the link, because we
4025   // only want the .eh_frame info if this particular stub section is
4026   // non-empty.
4027   void
4028   add_eh_frame(Layout* layout)
4029   {
4030     if (!this->eh_frame_added_)
4031       {
4032         if (!parameters->options().ld_generated_unwind_info())
4033           return;
4034
4035         // Since we add stub .eh_frame info late, it must be placed
4036         // after all other linker generated .eh_frame info so that
4037         // merge mapping need not be updated for input sections.
4038         // There is no provision to use a different CIE to that used
4039         // by .glink.
4040         if (!this->targ_->has_glink())
4041           return;
4042
4043         layout->add_eh_frame_for_plt(this,
4044                                      Eh_cie<size>::eh_frame_cie,
4045                                      sizeof (Eh_cie<size>::eh_frame_cie),
4046                                      default_fde,
4047                                      sizeof (default_fde));
4048         this->eh_frame_added_ = true;
4049       }
4050   }
4051
4052   Target_powerpc<size, big_endian>*
4053   targ() const
4054   { return targ_; }
4055
4056  private:
4057   class Plt_stub_ent;
4058   class Plt_stub_ent_hash;
4059   typedef Unordered_map<Plt_stub_ent, unsigned int,
4060                         Plt_stub_ent_hash> Plt_stub_entries;
4061
4062   // Alignment of stub section.
4063   unsigned int
4064   stub_align() const
4065   {
4066     if (size == 32)
4067       return 16;
4068     unsigned int min_align = 32;
4069     unsigned int user_align = 1 << parameters->options().plt_align();
4070     return std::max(user_align, min_align);
4071   }
4072
4073   // Return the plt offset for the given call stub.
4074   Address
4075   plt_off(typename Plt_stub_entries::const_iterator p, bool* is_iplt) const
4076   {
4077     const Symbol* gsym = p->first.sym_;
4078     if (gsym != NULL)
4079       {
4080         *is_iplt = (gsym->type() == elfcpp::STT_GNU_IFUNC
4081                     && gsym->can_use_relative_reloc(false));
4082         return gsym->plt_offset();
4083       }
4084     else
4085       {
4086         *is_iplt = true;
4087         const Sized_relobj_file<size, big_endian>* relobj = p->first.object_;
4088         unsigned int local_sym_index = p->first.locsym_;
4089         return relobj->local_plt_offset(local_sym_index);
4090       }
4091   }
4092
4093   // Size of a given plt call stub.
4094   unsigned int
4095   plt_call_size(typename Plt_stub_entries::const_iterator p) const
4096   {
4097     if (size == 32)
4098       return 16;
4099
4100     bool is_iplt;
4101     Address plt_addr = this->plt_off(p, &is_iplt);
4102     if (is_iplt)
4103       plt_addr += this->targ_->iplt_section()->address();
4104     else
4105       plt_addr += this->targ_->plt_section()->address();
4106     Address got_addr = this->targ_->got_section()->output_section()->address();
4107     const Powerpc_relobj<size, big_endian>* ppcobj = static_cast
4108       <const Powerpc_relobj<size, big_endian>*>(p->first.object_);
4109     got_addr += ppcobj->toc_base_offset();
4110     Address off = plt_addr - got_addr;
4111     unsigned int bytes = 4 * 4 + 4 * (ha(off) != 0);
4112     if (this->targ_->abiversion() < 2)
4113       {
4114         bool static_chain = parameters->options().plt_static_chain();
4115         bool thread_safe = this->targ_->plt_thread_safe();
4116         bytes += (4
4117                   + 4 * static_chain
4118                   + 8 * thread_safe
4119                   + 4 * (ha(off + 8 + 8 * static_chain) != ha(off)));
4120       }
4121     unsigned int align = 1 << parameters->options().plt_align();
4122     if (align > 1)
4123       bytes = (bytes + align - 1) & -align;
4124     return bytes;
4125   }
4126
4127   // Return long branch stub size.
4128   unsigned int
4129   branch_stub_size(Address to)
4130   {
4131     Address loc
4132       = this->stub_address() + this->last_plt_size_ + this->branch_size_;
4133     if (to - loc + (1 << 25) < 2 << 25)
4134       return 4;
4135     if (size == 64 || !parameters->options().output_is_position_independent())
4136       return 16;
4137     return 32;
4138   }
4139
4140   // Write out stubs.
4141   void
4142   do_write(Output_file*);
4143
4144   // Plt call stub keys.
4145   class Plt_stub_ent
4146   {
4147   public:
4148     Plt_stub_ent(const Symbol* sym)
4149       : sym_(sym), object_(0), addend_(0), locsym_(0)
4150     { }
4151
4152     Plt_stub_ent(const Sized_relobj_file<size, big_endian>* object,
4153                  unsigned int locsym_index)
4154       : sym_(NULL), object_(object), addend_(0), locsym_(locsym_index)
4155     { }
4156
4157     Plt_stub_ent(const Sized_relobj_file<size, big_endian>* object,
4158                  const Symbol* sym,
4159                  unsigned int r_type,
4160                  Address addend)
4161       : sym_(sym), object_(0), addend_(0), locsym_(0)
4162     {
4163       if (size != 32)
4164         this->addend_ = addend;
4165       else if (parameters->options().output_is_position_independent()
4166                && r_type == elfcpp::R_PPC_PLTREL24)
4167         {
4168           this->addend_ = addend;
4169           if (this->addend_ >= 32768)
4170             this->object_ = object;
4171         }
4172     }
4173
4174     Plt_stub_ent(const Sized_relobj_file<size, big_endian>* object,
4175                  unsigned int locsym_index,
4176                  unsigned int r_type,
4177                  Address addend)
4178       : sym_(NULL), object_(object), addend_(0), locsym_(locsym_index)
4179     {
4180       if (size != 32)
4181         this->addend_ = addend;
4182       else if (parameters->options().output_is_position_independent()
4183                && r_type == elfcpp::R_PPC_PLTREL24)
4184         this->addend_ = addend;
4185     }
4186
4187     bool operator==(const Plt_stub_ent& that) const
4188     {
4189       return (this->sym_ == that.sym_
4190               && this->object_ == that.object_
4191               && this->addend_ == that.addend_
4192               && this->locsym_ == that.locsym_);
4193     }
4194
4195     const Symbol* sym_;
4196     const Sized_relobj_file<size, big_endian>* object_;
4197     typename elfcpp::Elf_types<size>::Elf_Addr addend_;
4198     unsigned int locsym_;
4199   };
4200
4201   class Plt_stub_ent_hash
4202   {
4203   public:
4204     size_t operator()(const Plt_stub_ent& ent) const
4205     {
4206       return (reinterpret_cast<uintptr_t>(ent.sym_)
4207               ^ reinterpret_cast<uintptr_t>(ent.object_)
4208               ^ ent.addend_
4209               ^ ent.locsym_);
4210     }
4211   };
4212
4213   // Long branch stub keys.
4214   class Branch_stub_ent
4215   {
4216   public:
4217     Branch_stub_ent(const Powerpc_relobj<size, big_endian>* obj,
4218                     Address to, bool save_res)
4219       : dest_(to), toc_base_off_(0), save_res_(save_res)
4220     {
4221       if (size == 64)
4222         toc_base_off_ = obj->toc_base_offset();
4223     }
4224
4225     bool operator==(const Branch_stub_ent& that) const
4226     {
4227       return (this->dest_ == that.dest_
4228               && (size == 32
4229                   || this->toc_base_off_ == that.toc_base_off_));
4230     }
4231
4232     Address dest_;
4233     unsigned int toc_base_off_;
4234     bool save_res_;
4235   };
4236
4237   class Branch_stub_ent_hash
4238   {
4239   public:
4240     size_t operator()(const Branch_stub_ent& ent) const
4241     { return ent.dest_ ^ ent.toc_base_off_; }
4242   };
4243
4244   // In a sane world this would be a global.
4245   Target_powerpc<size, big_endian>* targ_;
4246   // Map sym/object/addend to stub offset.
4247   Plt_stub_entries plt_call_stubs_;
4248   // Map destination address to stub offset.
4249   typedef Unordered_map<Branch_stub_ent, unsigned int,
4250                         Branch_stub_ent_hash> Branch_stub_entries;
4251   Branch_stub_entries long_branch_stubs_;
4252   // size of input section
4253   section_size_type orig_data_size_;
4254   // size of stubs
4255   section_size_type plt_size_, last_plt_size_, branch_size_, last_branch_size_;
4256   // Some rare cases cause (PR/20529) fluctuation in stub table
4257   // size, which leads to an endless relax loop. This is to be fixed
4258   // by, after the first few iterations, allowing only increase of
4259   // stub table size. This variable sets the minimal possible size of
4260   // a stub table, it is zero for the first few iterations, then
4261   // increases monotonically.
4262   Address min_size_threshold_;
4263   // Whether .eh_frame info has been created for this stub section.
4264   bool eh_frame_added_;
4265   // Set if this stub group needs a copy of out-of-line register
4266   // save/restore functions.
4267   bool need_save_res_;
4268 };
4269
4270 // Add a plt call stub, if we do not already have one for this
4271 // sym/object/addend combo.
4272
4273 template<int size, bool big_endian>
4274 bool
4275 Stub_table<size, big_endian>::add_plt_call_entry(
4276     Address from,
4277     const Sized_relobj_file<size, big_endian>* object,
4278     const Symbol* gsym,
4279     unsigned int r_type,
4280     Address addend)
4281 {
4282   Plt_stub_ent ent(object, gsym, r_type, addend);
4283   unsigned int off = this->plt_size_;
4284   std::pair<typename Plt_stub_entries::iterator, bool> p
4285     = this->plt_call_stubs_.insert(std::make_pair(ent, off));
4286   if (p.second)
4287     this->plt_size_ = off + this->plt_call_size(p.first);
4288   return this->can_reach_stub(from, off, r_type);
4289 }
4290
4291 template<int size, bool big_endian>
4292 bool
4293 Stub_table<size, big_endian>::add_plt_call_entry(
4294     Address from,
4295     const Sized_relobj_file<size, big_endian>* object,
4296     unsigned int locsym_index,
4297     unsigned int r_type,
4298     Address addend)
4299 {
4300   Plt_stub_ent ent(object, locsym_index, r_type, addend);
4301   unsigned int off = this->plt_size_;
4302   std::pair<typename Plt_stub_entries::iterator, bool> p
4303     = this->plt_call_stubs_.insert(std::make_pair(ent, off));
4304   if (p.second)
4305     this->plt_size_ = off + this->plt_call_size(p.first);
4306   return this->can_reach_stub(from, off, r_type);
4307 }
4308
4309 // Find a plt call stub.
4310
4311 template<int size, bool big_endian>
4312 typename Stub_table<size, big_endian>::Address
4313 Stub_table<size, big_endian>::find_plt_call_entry(
4314     const Sized_relobj_file<size, big_endian>* object,
4315     const Symbol* gsym,
4316     unsigned int r_type,
4317     Address addend) const
4318 {
4319   Plt_stub_ent ent(object, gsym, r_type, addend);
4320   typename Plt_stub_entries::const_iterator p = this->plt_call_stubs_.find(ent);
4321   return p == this->plt_call_stubs_.end() ? invalid_address : p->second;
4322 }
4323
4324 template<int size, bool big_endian>
4325 typename Stub_table<size, big_endian>::Address
4326 Stub_table<size, big_endian>::find_plt_call_entry(const Symbol* gsym) const
4327 {
4328   Plt_stub_ent ent(gsym);
4329   typename Plt_stub_entries::const_iterator p = this->plt_call_stubs_.find(ent);
4330   return p == this->plt_call_stubs_.end() ? invalid_address : p->second;
4331 }
4332
4333 template<int size, bool big_endian>
4334 typename Stub_table<size, big_endian>::Address
4335 Stub_table<size, big_endian>::find_plt_call_entry(
4336     const Sized_relobj_file<size, big_endian>* object,
4337     unsigned int locsym_index,
4338     unsigned int r_type,
4339     Address addend) const
4340 {
4341   Plt_stub_ent ent(object, locsym_index, r_type, addend);
4342   typename Plt_stub_entries::const_iterator p = this->plt_call_stubs_.find(ent);
4343   return p == this->plt_call_stubs_.end() ? invalid_address : p->second;
4344 }
4345
4346 template<int size, bool big_endian>
4347 typename Stub_table<size, big_endian>::Address
4348 Stub_table<size, big_endian>::find_plt_call_entry(
4349     const Sized_relobj_file<size, big_endian>* object,
4350     unsigned int locsym_index) const
4351 {
4352   Plt_stub_ent ent(object, locsym_index);
4353   typename Plt_stub_entries::const_iterator p = this->plt_call_stubs_.find(ent);
4354   return p == this->plt_call_stubs_.end() ? invalid_address : p->second;
4355 }
4356
4357 // Add a long branch stub if we don't already have one to given
4358 // destination.
4359
4360 template<int size, bool big_endian>
4361 bool
4362 Stub_table<size, big_endian>::add_long_branch_entry(
4363     const Powerpc_relobj<size, big_endian>* object,
4364     unsigned int r_type,
4365     Address from,
4366     Address to,
4367     bool save_res)
4368 {
4369   Branch_stub_ent ent(object, to, save_res);
4370   Address off = this->branch_size_;
4371   if (this->long_branch_stubs_.insert(std::make_pair(ent, off)).second)
4372     {
4373       if (save_res)
4374         this->need_save_res_ = true;
4375       else
4376         {
4377           unsigned int stub_size = this->branch_stub_size(to);
4378           this->branch_size_ = off + stub_size;
4379           if (size == 64 && stub_size != 4)
4380             this->targ_->add_branch_lookup_table(to);
4381         }
4382     }
4383   return this->can_reach_stub(from, off, r_type);
4384 }
4385
4386 // Find long branch stub offset.
4387
4388 template<int size, bool big_endian>
4389 typename Stub_table<size, big_endian>::Address
4390 Stub_table<size, big_endian>::find_long_branch_entry(
4391     const Powerpc_relobj<size, big_endian>* object,
4392     Address to) const
4393 {
4394   Branch_stub_ent ent(object, to, false);
4395   typename Branch_stub_entries::const_iterator p
4396     = this->long_branch_stubs_.find(ent);
4397   if (p == this->long_branch_stubs_.end())
4398     return invalid_address;
4399   if (p->first.save_res_)
4400     return to - this->targ_->savres_section()->address() + this->branch_size_;
4401   return p->second;
4402 }
4403
4404 // A class to handle .glink.
4405
4406 template<int size, bool big_endian>
4407 class Output_data_glink : public Output_section_data
4408 {
4409  public:
4410   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
4411   static const Address invalid_address = static_cast<Address>(0) - 1;
4412   static const int pltresolve_size = 16*4;
4413
4414   Output_data_glink(Target_powerpc<size, big_endian>* targ)
4415     : Output_section_data(16), targ_(targ), global_entry_stubs_(),
4416       end_branch_table_(), ge_size_(0)
4417   { }
4418
4419   void
4420   add_eh_frame(Layout* layout);
4421
4422   void
4423   add_global_entry(const Symbol*);
4424
4425   Address
4426   find_global_entry(const Symbol*) const;
4427
4428   Address
4429   global_entry_address() const
4430   {
4431     gold_assert(this->is_data_size_valid());
4432     unsigned int global_entry_off = (this->end_branch_table_ + 15) & -16;
4433     return this->address() + global_entry_off;
4434   }
4435
4436  protected:
4437   // Write to a map file.
4438   void
4439   do_print_to_mapfile(Mapfile* mapfile) const
4440   { mapfile->print_output_data(this, _("** glink")); }
4441
4442  private:
4443   void
4444   set_final_data_size();
4445
4446   // Write out .glink
4447   void
4448   do_write(Output_file*);
4449
4450   // Allows access to .got and .plt for do_write.
4451   Target_powerpc<size, big_endian>* targ_;
4452
4453   // Map sym to stub offset.
4454   typedef Unordered_map<const Symbol*, unsigned int> Global_entry_stub_entries;
4455   Global_entry_stub_entries global_entry_stubs_;
4456
4457   unsigned int end_branch_table_, ge_size_;
4458 };
4459
4460 template<int size, bool big_endian>
4461 void
4462 Output_data_glink<size, big_endian>::add_eh_frame(Layout* layout)
4463 {
4464   if (!parameters->options().ld_generated_unwind_info())
4465     return;
4466
4467   if (size == 64)
4468     {
4469       if (this->targ_->abiversion() < 2)
4470         layout->add_eh_frame_for_plt(this,
4471                                      Eh_cie<64>::eh_frame_cie,
4472                                      sizeof (Eh_cie<64>::eh_frame_cie),
4473                                      glink_eh_frame_fde_64v1,
4474                                      sizeof (glink_eh_frame_fde_64v1));
4475       else
4476         layout->add_eh_frame_for_plt(this,
4477                                      Eh_cie<64>::eh_frame_cie,
4478                                      sizeof (Eh_cie<64>::eh_frame_cie),
4479                                      glink_eh_frame_fde_64v2,
4480                                      sizeof (glink_eh_frame_fde_64v2));
4481     }
4482   else
4483     {
4484       // 32-bit .glink can use the default since the CIE return
4485       // address reg, LR, is valid.
4486       layout->add_eh_frame_for_plt(this,
4487                                    Eh_cie<32>::eh_frame_cie,
4488                                    sizeof (Eh_cie<32>::eh_frame_cie),
4489                                    default_fde,
4490                                    sizeof (default_fde));
4491       // Except where LR is used in a PIC __glink_PLTresolve.
4492       if (parameters->options().output_is_position_independent())
4493         layout->add_eh_frame_for_plt(this,
4494                                      Eh_cie<32>::eh_frame_cie,
4495                                      sizeof (Eh_cie<32>::eh_frame_cie),
4496                                      glink_eh_frame_fde_32,
4497                                      sizeof (glink_eh_frame_fde_32));
4498     }
4499 }
4500
4501 template<int size, bool big_endian>
4502 void
4503 Output_data_glink<size, big_endian>::add_global_entry(const Symbol* gsym)
4504 {
4505   std::pair<typename Global_entry_stub_entries::iterator, bool> p
4506     = this->global_entry_stubs_.insert(std::make_pair(gsym, this->ge_size_));
4507   if (p.second)
4508     this->ge_size_ += 16;
4509 }
4510
4511 template<int size, bool big_endian>
4512 typename Output_data_glink<size, big_endian>::Address
4513 Output_data_glink<size, big_endian>::find_global_entry(const Symbol* gsym) const
4514 {
4515   typename Global_entry_stub_entries::const_iterator p
4516     = this->global_entry_stubs_.find(gsym);
4517   return p == this->global_entry_stubs_.end() ? invalid_address : p->second;
4518 }
4519
4520 template<int size, bool big_endian>
4521 void
4522 Output_data_glink<size, big_endian>::set_final_data_size()
4523 {
4524   unsigned int count = this->targ_->plt_entry_count();
4525   section_size_type total = 0;
4526
4527   if (count != 0)
4528     {
4529       if (size == 32)
4530         {
4531           // space for branch table
4532           total += 4 * (count - 1);
4533
4534           total += -total & 15;
4535           total += this->pltresolve_size;
4536         }
4537       else
4538         {
4539           total += this->pltresolve_size;
4540
4541           // space for branch table
4542           total += 4 * count;
4543           if (this->targ_->abiversion() < 2)
4544             {
4545               total += 4 * count;
4546               if (count > 0x8000)
4547                 total += 4 * (count - 0x8000);
4548             }
4549         }
4550     }
4551   this->end_branch_table_ = total;
4552   total = (total + 15) & -16;
4553   total += this->ge_size_;
4554
4555   this->set_data_size(total);
4556 }
4557
4558 // Write out plt and long branch stub code.
4559
4560 template<int size, bool big_endian>
4561 void
4562 Stub_table<size, big_endian>::do_write(Output_file* of)
4563 {
4564   if (this->plt_call_stubs_.empty()
4565       && this->long_branch_stubs_.empty())
4566     return;
4567
4568   const section_size_type start_off = this->offset();
4569   const section_size_type off = this->stub_offset();
4570   const section_size_type oview_size =
4571     convert_to_section_size_type(this->data_size() - (off - start_off));
4572   unsigned char* const oview = of->get_output_view(off, oview_size);
4573   unsigned char* p;
4574
4575   if (size == 64)
4576     {
4577       const Output_data_got_powerpc<size, big_endian>* got
4578         = this->targ_->got_section();
4579       Address got_os_addr = got->output_section()->address();
4580
4581       if (!this->plt_call_stubs_.empty())
4582         {
4583           // The base address of the .plt section.
4584           Address plt_base = this->targ_->plt_section()->address();
4585           Address iplt_base = invalid_address;
4586
4587           // Write out plt call stubs.
4588           typename Plt_stub_entries::const_iterator cs;
4589           for (cs = this->plt_call_stubs_.begin();
4590                cs != this->plt_call_stubs_.end();
4591                ++cs)
4592             {
4593               bool is_iplt;
4594               Address pltoff = this->plt_off(cs, &is_iplt);
4595               Address plt_addr = pltoff;
4596               if (is_iplt)
4597                 {
4598                   if (iplt_base == invalid_address)
4599                     iplt_base = this->targ_->iplt_section()->address();
4600                   plt_addr += iplt_base;
4601                 }
4602               else
4603                 plt_addr += plt_base;
4604               const Powerpc_relobj<size, big_endian>* ppcobj = static_cast
4605                 <const Powerpc_relobj<size, big_endian>*>(cs->first.object_);
4606               Address got_addr = got_os_addr + ppcobj->toc_base_offset();
4607               Address off = plt_addr - got_addr;
4608
4609               if (off + 0x80008000 > 0xffffffff || (off & 7) != 0)
4610                 gold_error(_("%s: linkage table error against `%s'"),
4611                            cs->first.object_->name().c_str(),
4612                            cs->first.sym_->demangled_name().c_str());
4613
4614               bool plt_load_toc = this->targ_->abiversion() < 2;
4615               bool static_chain
4616                 = plt_load_toc && parameters->options().plt_static_chain();
4617               bool thread_safe
4618                 = plt_load_toc && this->targ_->plt_thread_safe();
4619               bool use_fake_dep = false;
4620               Address cmp_branch_off = 0;
4621               if (thread_safe)
4622                 {
4623                   unsigned int pltindex
4624                     = ((pltoff - this->targ_->first_plt_entry_offset())
4625                        / this->targ_->plt_entry_size());
4626                   Address glinkoff
4627                     = (this->targ_->glink_section()->pltresolve_size
4628                        + pltindex * 8);
4629                   if (pltindex > 32768)
4630                     glinkoff += (pltindex - 32768) * 4;
4631                   Address to
4632                     = this->targ_->glink_section()->address() + glinkoff;
4633                   Address from
4634                     = (this->stub_address() + cs->second + 24
4635                        + 4 * (ha(off) != 0)
4636                        + 4 * (ha(off + 8 + 8 * static_chain) != ha(off))
4637                        + 4 * static_chain);
4638                   cmp_branch_off = to - from;
4639                   use_fake_dep = cmp_branch_off + (1 << 25) >= (1 << 26);
4640                 }
4641
4642               p = oview + cs->second;
4643               if (ha(off) != 0)
4644                 {
4645                   write_insn<big_endian>(p, std_2_1 + this->targ_->stk_toc());
4646                   p += 4;
4647                   if (plt_load_toc)
4648                     {
4649                       write_insn<big_endian>(p, addis_11_2 + ha(off));
4650                       p += 4;
4651                       write_insn<big_endian>(p, ld_12_11 + l(off));
4652                       p += 4;
4653                     }
4654                   else
4655                     {
4656                       write_insn<big_endian>(p, addis_12_2 + ha(off));
4657                       p += 4;
4658                       write_insn<big_endian>(p, ld_12_12 + l(off));
4659                       p += 4;
4660                     }
4661                   if (plt_load_toc
4662                       && ha(off + 8 + 8 * static_chain) != ha(off))
4663                     {
4664                       write_insn<big_endian>(p, addi_11_11 + l(off));
4665                       p += 4;
4666                       off = 0;
4667                     }
4668                   write_insn<big_endian>(p, mtctr_12);
4669                   p += 4;
4670                   if (plt_load_toc)
4671                     {
4672                       if (use_fake_dep)
4673                         {
4674                           write_insn<big_endian>(p, xor_2_12_12);
4675                           p += 4;
4676                           write_insn<big_endian>(p, add_11_11_2);
4677                           p += 4;
4678                         }
4679                       write_insn<big_endian>(p, ld_2_11 + l(off + 8));
4680                       p += 4;
4681                       if (static_chain)
4682                         {
4683                           write_insn<big_endian>(p, ld_11_11 + l(off + 16));
4684                           p += 4;
4685                         }
4686                     }
4687                 }
4688               else
4689                 {
4690                   write_insn<big_endian>(p, std_2_1 + this->targ_->stk_toc());
4691                   p += 4;
4692                   write_insn<big_endian>(p, ld_12_2 + l(off));
4693                   p += 4;
4694                   if (plt_load_toc
4695                       && ha(off + 8 + 8 * static_chain) != ha(off))
4696                     {
4697                       write_insn<big_endian>(p, addi_2_2 + l(off));
4698                       p += 4;
4699                       off = 0;
4700                     }
4701                   write_insn<big_endian>(p, mtctr_12);
4702                   p += 4;
4703                   if (plt_load_toc)
4704                     {
4705                       if (use_fake_dep)
4706                         {
4707                           write_insn<big_endian>(p, xor_11_12_12);
4708                           p += 4;
4709                           write_insn<big_endian>(p, add_2_2_11);
4710                           p += 4;
4711                         }
4712                       if (static_chain)
4713                         {
4714                           write_insn<big_endian>(p, ld_11_2 + l(off + 16));
4715                           p += 4;
4716                         }
4717                       write_insn<big_endian>(p, ld_2_2 + l(off + 8));
4718                       p += 4;
4719                     }
4720                 }
4721               if (thread_safe && !use_fake_dep)
4722                 {
4723                   write_insn<big_endian>(p, cmpldi_2_0);
4724                   p += 4;
4725                   write_insn<big_endian>(p, bnectr_p4);
4726                   p += 4;
4727                   write_insn<big_endian>(p, b | (cmp_branch_off & 0x3fffffc));
4728                 }
4729               else
4730                 write_insn<big_endian>(p, bctr);
4731             }
4732         }
4733
4734       // Write out long branch stubs.
4735       typename Branch_stub_entries::const_iterator bs;
4736       for (bs = this->long_branch_stubs_.begin();
4737            bs != this->long_branch_stubs_.end();
4738            ++bs)
4739         {
4740           if (bs->first.save_res_)
4741             continue;
4742           p = oview + this->plt_size_ + bs->second;
4743           Address loc = this->stub_address() + this->plt_size_ + bs->second;
4744           Address delta = bs->first.dest_ - loc;
4745           if (delta + (1 << 25) < 2 << 25)
4746             write_insn<big_endian>(p, b | (delta & 0x3fffffc));
4747           else
4748             {
4749               Address brlt_addr
4750                 = this->targ_->find_branch_lookup_table(bs->first.dest_);
4751               gold_assert(brlt_addr != invalid_address);
4752               brlt_addr += this->targ_->brlt_section()->address();
4753               Address got_addr = got_os_addr + bs->first.toc_base_off_;
4754               Address brltoff = brlt_addr - got_addr;
4755               if (ha(brltoff) == 0)
4756                 {
4757                   write_insn<big_endian>(p, ld_12_2 + l(brltoff)),      p += 4;
4758                 }
4759               else
4760                 {
4761                   write_insn<big_endian>(p, addis_12_2 + ha(brltoff)),  p += 4;
4762                   write_insn<big_endian>(p, ld_12_12 + l(brltoff)),     p += 4;
4763                 }
4764               write_insn<big_endian>(p, mtctr_12),                      p += 4;
4765               write_insn<big_endian>(p, bctr);
4766             }
4767         }
4768     }
4769   else
4770     {
4771       if (!this->plt_call_stubs_.empty())
4772         {
4773           // The base address of the .plt section.
4774           Address plt_base = this->targ_->plt_section()->address();
4775           Address iplt_base = invalid_address;
4776           // The address of _GLOBAL_OFFSET_TABLE_.
4777           Address g_o_t = invalid_address;
4778
4779           // Write out plt call stubs.
4780           typename Plt_stub_entries::const_iterator cs;
4781           for (cs = this->plt_call_stubs_.begin();
4782                cs != this->plt_call_stubs_.end();
4783                ++cs)
4784             {
4785               bool is_iplt;
4786               Address plt_addr = this->plt_off(cs, &is_iplt);
4787               if (is_iplt)
4788                 {
4789                   if (iplt_base == invalid_address)
4790                     iplt_base = this->targ_->iplt_section()->address();
4791                   plt_addr += iplt_base;
4792                 }
4793               else
4794                 plt_addr += plt_base;
4795
4796               p = oview + cs->second;
4797               if (parameters->options().output_is_position_independent())
4798                 {
4799                   Address got_addr;
4800                   const Powerpc_relobj<size, big_endian>* ppcobj
4801                     = (static_cast<const Powerpc_relobj<size, big_endian>*>
4802                        (cs->first.object_));
4803                   if (ppcobj != NULL && cs->first.addend_ >= 32768)
4804                     {
4805                       unsigned int got2 = ppcobj->got2_shndx();
4806                       got_addr = ppcobj->get_output_section_offset(got2);
4807                       gold_assert(got_addr != invalid_address);
4808                       got_addr += (ppcobj->output_section(got2)->address()
4809                                    + cs->first.addend_);
4810                     }
4811                   else
4812                     {
4813                       if (g_o_t == invalid_address)
4814                         {
4815                           const Output_data_got_powerpc<size, big_endian>* got
4816                             = this->targ_->got_section();
4817                           g_o_t = got->address() + got->g_o_t();
4818                         }
4819                       got_addr = g_o_t;
4820                     }
4821
4822                   Address off = plt_addr - got_addr;
4823                   if (ha(off) == 0)
4824                     {
4825                       write_insn<big_endian>(p +  0, lwz_11_30 + l(off));
4826                       write_insn<big_endian>(p +  4, mtctr_11);
4827                       write_insn<big_endian>(p +  8, bctr);
4828                     }
4829                   else
4830                     {
4831                       write_insn<big_endian>(p +  0, addis_11_30 + ha(off));
4832                       write_insn<big_endian>(p +  4, lwz_11_11 + l(off));
4833                       write_insn<big_endian>(p +  8, mtctr_11);
4834                       write_insn<big_endian>(p + 12, bctr);
4835                     }
4836                 }
4837               else
4838                 {
4839                   write_insn<big_endian>(p +  0, lis_11 + ha(plt_addr));
4840                   write_insn<big_endian>(p +  4, lwz_11_11 + l(plt_addr));
4841                   write_insn<big_endian>(p +  8, mtctr_11);
4842                   write_insn<big_endian>(p + 12, bctr);
4843                 }
4844             }
4845         }
4846
4847       // Write out long branch stubs.
4848       typename Branch_stub_entries::const_iterator bs;
4849       for (bs = this->long_branch_stubs_.begin();
4850            bs != this->long_branch_stubs_.end();
4851            ++bs)
4852         {
4853           if (bs->first.save_res_)
4854             continue;
4855           p = oview + this->plt_size_ + bs->second;
4856           Address loc = this->stub_address() + this->plt_size_ + bs->second;
4857           Address delta = bs->first.dest_ - loc;
4858           if (delta + (1 << 25) < 2 << 25)
4859             write_insn<big_endian>(p, b | (delta & 0x3fffffc));
4860           else if (!parameters->options().output_is_position_independent())
4861             {
4862               write_insn<big_endian>(p +  0, lis_12 + ha(bs->first.dest_));
4863               write_insn<big_endian>(p +  4, addi_12_12 + l(bs->first.dest_));
4864               write_insn<big_endian>(p +  8, mtctr_12);
4865               write_insn<big_endian>(p + 12, bctr);
4866             }
4867           else
4868             {
4869               delta -= 8;
4870               write_insn<big_endian>(p +  0, mflr_0);
4871               write_insn<big_endian>(p +  4, bcl_20_31);
4872               write_insn<big_endian>(p +  8, mflr_12);
4873               write_insn<big_endian>(p + 12, addis_12_12 + ha(delta));
4874               write_insn<big_endian>(p + 16, addi_12_12 + l(delta));
4875               write_insn<big_endian>(p + 20, mtlr_0);
4876               write_insn<big_endian>(p + 24, mtctr_12);
4877               write_insn<big_endian>(p + 28, bctr);
4878             }
4879         }
4880     }
4881   if (this->need_save_res_)
4882     {
4883       p = oview + this->plt_size_ + this->branch_size_;
4884       memcpy (p, this->targ_->savres_section()->contents(),
4885               this->targ_->savres_section()->data_size());
4886     }
4887 }
4888
4889 // Write out .glink.
4890
4891 template<int size, bool big_endian>
4892 void
4893 Output_data_glink<size, big_endian>::do_write(Output_file* of)
4894 {
4895   const section_size_type off = this->offset();
4896   const section_size_type oview_size =
4897     convert_to_section_size_type(this->data_size());
4898   unsigned char* const oview = of->get_output_view(off, oview_size);
4899   unsigned char* p;
4900
4901   // The base address of the .plt section.
4902   typedef typename elfcpp::Elf_types<size>::Elf_Addr Address;
4903   Address plt_base = this->targ_->plt_section()->address();
4904
4905   if (size == 64)
4906     {
4907       if (this->end_branch_table_ != 0)
4908         {
4909           // Write pltresolve stub.
4910           p = oview;
4911           Address after_bcl = this->address() + 16;
4912           Address pltoff = plt_base - after_bcl;
4913
4914           elfcpp::Swap<64, big_endian>::writeval(p, pltoff),    p += 8;
4915
4916           if (this->targ_->abiversion() < 2)
4917             {
4918               write_insn<big_endian>(p, mflr_12),               p += 4;
4919               write_insn<big_endian>(p, bcl_20_31),             p += 4;
4920               write_insn<big_endian>(p, mflr_11),               p += 4;
4921               write_insn<big_endian>(p, ld_2_11 + l(-16)),      p += 4;
4922               write_insn<big_endian>(p, mtlr_12),               p += 4;
4923               write_insn<big_endian>(p, add_11_2_11),           p += 4;
4924               write_insn<big_endian>(p, ld_12_11 + 0),          p += 4;
4925               write_insn<big_endian>(p, ld_2_11 + 8),           p += 4;
4926               write_insn<big_endian>(p, mtctr_12),              p += 4;
4927               write_insn<big_endian>(p, ld_11_11 + 16),         p += 4;
4928             }
4929           else
4930             {
4931               write_insn<big_endian>(p, mflr_0),                p += 4;
4932               write_insn<big_endian>(p, bcl_20_31),             p += 4;
4933               write_insn<big_endian>(p, mflr_11),               p += 4;
4934               write_insn<big_endian>(p, ld_2_11 + l(-16)),      p += 4;
4935               write_insn<big_endian>(p, mtlr_0),                p += 4;
4936               write_insn<big_endian>(p, sub_12_12_11),          p += 4;
4937               write_insn<big_endian>(p, add_11_2_11),           p += 4;
4938               write_insn<big_endian>(p, addi_0_12 + l(-48)),    p += 4;
4939               write_insn<big_endian>(p, ld_12_11 + 0),          p += 4;
4940               write_insn<big_endian>(p, srdi_0_0_2),            p += 4;
4941               write_insn<big_endian>(p, mtctr_12),              p += 4;
4942               write_insn<big_endian>(p, ld_11_11 + 8),          p += 4;
4943             }
4944           write_insn<big_endian>(p, bctr),                      p += 4;
4945           while (p < oview + this->pltresolve_size)
4946             write_insn<big_endian>(p, nop), p += 4;
4947
4948           // Write lazy link call stubs.
4949           uint32_t indx = 0;
4950           while (p < oview + this->end_branch_table_)
4951             {
4952               if (this->targ_->abiversion() < 2)
4953                 {
4954                   if (indx < 0x8000)
4955                     {
4956                       write_insn<big_endian>(p, li_0_0 + indx),         p += 4;
4957                     }
4958                   else
4959                     {
4960                       write_insn<big_endian>(p, lis_0 + hi(indx)),      p += 4;
4961                       write_insn<big_endian>(p, ori_0_0_0 + l(indx)),   p += 4;
4962                     }
4963                 }
4964               uint32_t branch_off = 8 - (p - oview);
4965               write_insn<big_endian>(p, b + (branch_off & 0x3fffffc)),  p += 4;
4966               indx++;
4967             }
4968         }
4969
4970       Address plt_base = this->targ_->plt_section()->address();
4971       Address iplt_base = invalid_address;
4972       unsigned int global_entry_off = (this->end_branch_table_ + 15) & -16;
4973       Address global_entry_base = this->address() + global_entry_off;
4974       typename Global_entry_stub_entries::const_iterator ge;
4975       for (ge = this->global_entry_stubs_.begin();
4976            ge != this->global_entry_stubs_.end();
4977            ++ge)
4978         {
4979           p = oview + global_entry_off + ge->second;
4980           Address plt_addr = ge->first->plt_offset();
4981           if (ge->first->type() == elfcpp::STT_GNU_IFUNC
4982               && ge->first->can_use_relative_reloc(false))
4983             {
4984               if (iplt_base == invalid_address)
4985                 iplt_base = this->targ_->iplt_section()->address();
4986               plt_addr += iplt_base;
4987             }
4988           else
4989             plt_addr += plt_base;
4990           Address my_addr = global_entry_base + ge->second;
4991           Address off = plt_addr - my_addr;
4992
4993           if (off + 0x80008000 > 0xffffffff || (off & 3) != 0)
4994             gold_error(_("%s: linkage table error against `%s'"),
4995                        ge->first->object()->name().c_str(),
4996                        ge->first->demangled_name().c_str());
4997
4998           write_insn<big_endian>(p, addis_12_12 + ha(off)),     p += 4;
4999           write_insn<big_endian>(p, ld_12_12 + l(off)),         p += 4;
5000           write_insn<big_endian>(p, mtctr_12),                  p += 4;
5001           write_insn<big_endian>(p, bctr);
5002         }
5003     }
5004   else
5005     {
5006       const Output_data_got_powerpc<size, big_endian>* got
5007         = this->targ_->got_section();
5008       // The address of _GLOBAL_OFFSET_TABLE_.
5009       Address g_o_t = got->address() + got->g_o_t();
5010
5011       // Write out pltresolve branch table.
5012       p = oview;
5013       unsigned int the_end = oview_size - this->pltresolve_size;
5014       unsigned char* end_p = oview + the_end;
5015       while (p < end_p - 8 * 4)
5016         write_insn<big_endian>(p, b + end_p - p), p += 4;
5017       while (p < end_p)
5018         write_insn<big_endian>(p, nop), p += 4;
5019
5020       // Write out pltresolve call stub.
5021       if (parameters->options().output_is_position_independent())
5022         {
5023           Address res0_off = 0;
5024           Address after_bcl_off = the_end + 12;
5025           Address bcl_res0 = after_bcl_off - res0_off;
5026
5027           write_insn<big_endian>(p +  0, addis_11_11 + ha(bcl_res0));
5028           write_insn<big_endian>(p +  4, mflr_0);
5029           write_insn<big_endian>(p +  8, bcl_20_31);
5030           write_insn<big_endian>(p + 12, addi_11_11 + l(bcl_res0));
5031           write_insn<big_endian>(p + 16, mflr_12);
5032           write_insn<big_endian>(p + 20, mtlr_0);
5033           write_insn<big_endian>(p + 24, sub_11_11_12);
5034
5035           Address got_bcl = g_o_t + 4 - (after_bcl_off + this->address());
5036
5037           write_insn<big_endian>(p + 28, addis_12_12 + ha(got_bcl));
5038           if (ha(got_bcl) == ha(got_bcl + 4))
5039             {
5040               write_insn<big_endian>(p + 32, lwz_0_12 + l(got_bcl));
5041               write_insn<big_endian>(p + 36, lwz_12_12 + l(got_bcl + 4));
5042             }
5043           else
5044             {
5045               write_insn<big_endian>(p + 32, lwzu_0_12 + l(got_bcl));
5046               write_insn<big_endian>(p + 36, lwz_12_12 + 4);
5047             }
5048           write_insn<big_endian>(p + 40, mtctr_0);
5049           write_insn<big_endian>(p + 44, add_0_11_11);
5050           write_insn<big_endian>(p + 48, add_11_0_11);
5051           write_insn<big_endian>(p + 52, bctr);
5052           write_insn<big_endian>(p + 56, nop);
5053           write_insn<big_endian>(p + 60, nop);
5054         }
5055       else
5056         {
5057           Address res0 = this->address();
5058
5059           write_insn<big_endian>(p + 0, lis_12 + ha(g_o_t + 4));
5060           write_insn<big_endian>(p + 4, addis_11_11 + ha(-res0));
5061           if (ha(g_o_t + 4) == ha(g_o_t + 8))
5062             write_insn<big_endian>(p + 8, lwz_0_12 + l(g_o_t + 4));
5063           else
5064             write_insn<big_endian>(p + 8, lwzu_0_12 + l(g_o_t + 4));
5065           write_insn<big_endian>(p + 12, addi_11_11 + l(-res0));
5066           write_insn<big_endian>(p + 16, mtctr_0);
5067           write_insn<big_endian>(p + 20, add_0_11_11);
5068           if (ha(g_o_t + 4) == ha(g_o_t + 8))
5069             write_insn<big_endian>(p + 24, lwz_12_12 + l(g_o_t + 8));
5070           else
5071             write_insn<big_endian>(p + 24, lwz_12_12 + 4);
5072           write_insn<big_endian>(p + 28, add_11_0_11);
5073           write_insn<big_endian>(p + 32, bctr);
5074           write_insn<big_endian>(p + 36, nop);
5075           write_insn<big_endian>(p + 40, nop);
5076           write_insn<big_endian>(p + 44, nop);
5077           write_insn<big_endian>(p + 48, nop);
5078           write_insn<big_endian>(p + 52, nop);
5079           write_insn<big_endian>(p + 56, nop);
5080           write_insn<big_endian>(p + 60, nop);
5081         }
5082       p += 64;
5083     }
5084
5085   of->write_output_view(off, oview_size, oview);
5086 }
5087
5088
5089 // A class to handle linker generated save/restore functions.
5090
5091 template<int size, bool big_endian>
5092 class Output_data_save_res : public Output_section_data_build
5093 {
5094  public:
5095   Output_data_save_res(Symbol_table* symtab);
5096
5097   const unsigned char*
5098   contents() const
5099   {
5100     return contents_;
5101   }
5102
5103  protected:
5104   // Write to a map file.
5105   void
5106   do_print_to_mapfile(Mapfile* mapfile) const
5107   { mapfile->print_output_data(this, _("** save/restore")); }
5108
5109   void
5110   do_write(Output_file*);
5111
5112  private:
5113   // The maximum size of save/restore contents.
5114   static const unsigned int savres_max = 218*4;
5115
5116   void
5117   savres_define(Symbol_table* symtab,
5118                 const char *name,
5119                 unsigned int lo, unsigned int hi,
5120                 unsigned char* write_ent(unsigned char*, int),
5121                 unsigned char* write_tail(unsigned char*, int));
5122
5123   unsigned char *contents_;
5124 };
5125
5126 template<bool big_endian>
5127 static unsigned char*
5128 savegpr0(unsigned char* p, int r)
5129 {
5130   uint32_t insn = std_0_1 + (r << 21) + (1 << 16) - (32 - r) * 8;
5131   write_insn<big_endian>(p, insn);
5132   return p + 4;
5133 }
5134
5135 template<bool big_endian>
5136 static unsigned char*
5137 savegpr0_tail(unsigned char* p, int r)
5138 {
5139   p = savegpr0<big_endian>(p, r);
5140   uint32_t insn = std_0_1 + 16;
5141   write_insn<big_endian>(p, insn);
5142   p = p + 4;
5143   write_insn<big_endian>(p, blr);
5144   return p + 4;
5145 }
5146
5147 template<bool big_endian>
5148 static unsigned char*
5149 restgpr0(unsigned char* p, int r)
5150 {
5151   uint32_t insn = ld_0_1 + (r << 21) + (1 << 16) - (32 - r) * 8;
5152   write_insn<big_endian>(p, insn);
5153   return p + 4;
5154 }
5155
5156 template<bool big_endian>
5157 static unsigned char*
5158 restgpr0_tail(unsigned char* p, int r)
5159 {
5160   uint32_t insn = ld_0_1 + 16;
5161   write_insn<big_endian>(p, insn);
5162   p = p + 4;
5163   p = restgpr0<big_endian>(p, r);
5164   write_insn<big_endian>(p, mtlr_0);
5165   p = p + 4;
5166   if (r == 29)
5167     {
5168       p = restgpr0<big_endian>(p, 30);
5169       p = restgpr0<big_endian>(p, 31);
5170     }
5171   write_insn<big_endian>(p, blr);
5172   return p + 4;
5173 }
5174
5175 template<bool big_endian>
5176 static unsigned char*
5177 savegpr1(unsigned char* p, int r)
5178 {
5179   uint32_t insn = std_0_12 + (r << 21) + (1 << 16) - (32 - r) * 8;
5180   write_insn<big_endian>(p, insn);
5181   return p + 4;
5182 }
5183
5184 template<bool big_endian>
5185 static unsigned char*
5186 savegpr1_tail(unsigned char* p, int r)
5187 {
5188   p = savegpr1<big_endian>(p, r);
5189   write_insn<big_endian>(p, blr);
5190   return p + 4;
5191 }
5192
5193 template<bool big_endian>
5194 static unsigned char*
5195 restgpr1(unsigned char* p, int r)
5196 {
5197   uint32_t insn = ld_0_12 + (r << 21) + (1 << 16) - (32 - r) * 8;
5198   write_insn<big_endian>(p, insn);
5199   return p + 4;
5200 }
5201
5202 template<bool big_endian>
5203 static unsigned char*
5204 restgpr1_tail(unsigned char* p, int r)
5205 {
5206   p = restgpr1<big_endian>(p, r);
5207   write_insn<big_endian>(p, blr);
5208   return p + 4;
5209 }
5210
5211 template<bool big_endian>
5212 static unsigned char*
5213 savefpr(unsigned char* p, int r)
5214 {
5215   uint32_t insn = stfd_0_1 + (r << 21) + (1 << 16) - (32 - r) * 8;
5216   write_insn<big_endian>(p, insn);
5217   return p + 4;
5218 }
5219
5220 template<bool big_endian>
5221 static unsigned char*
5222 savefpr0_tail(unsigned char* p, int r)
5223 {
5224   p = savefpr<big_endian>(p, r);
5225   write_insn<big_endian>(p, std_0_1 + 16);
5226   p = p + 4;
5227   write_insn<big_endian>(p, blr);
5228   return p + 4;
5229 }
5230
5231 template<bool big_endian>
5232 static unsigned char*
5233 restfpr(unsigned char* p, int r)
5234 {
5235   uint32_t insn = lfd_0_1 + (r << 21) + (1 << 16) - (32 - r) * 8;
5236   write_insn<big_endian>(p, insn);
5237   return p + 4;
5238 }
5239
5240 template<bool big_endian>
5241 static unsigned char*
5242 restfpr0_tail(unsigned char* p, int r)
5243 {
5244   write_insn<big_endian>(p, ld_0_1 + 16);
5245   p = p + 4;
5246   p = restfpr<big_endian>(p, r);
5247   write_insn<big_endian>(p, mtlr_0);
5248   p = p + 4;
5249   if (r == 29)
5250     {
5251       p = restfpr<big_endian>(p, 30);
5252       p = restfpr<big_endian>(p, 31);
5253     }
5254   write_insn<big_endian>(p, blr);
5255   return p + 4;
5256 }
5257
5258 template<bool big_endian>
5259 static unsigned char*
5260 savefpr1_tail(unsigned char* p, int r)
5261 {
5262   p = savefpr<big_endian>(p, r);
5263   write_insn<big_endian>(p, blr);
5264   return p + 4;
5265 }
5266
5267 template<bool big_endian>
5268 static unsigned char*
5269 restfpr1_tail(unsigned char* p, int r)
5270 {
5271   p = restfpr<big_endian>(p, r);
5272   write_insn<big_endian>(p, blr);
5273   return p + 4;
5274 }
5275
5276 template<bool big_endian>
5277 static unsigned char*
5278 savevr(unsigned char* p, int r)
5279 {
5280   uint32_t insn = li_12_0 + (1 << 16) - (32 - r) * 16;
5281   write_insn<big_endian>(p, insn);
5282   p = p + 4;
5283   insn = stvx_0_12_0 + (r << 21);
5284   write_insn<big_endian>(p, insn);
5285   return p + 4;
5286 }
5287
5288 template<bool big_endian>
5289 static unsigned char*
5290 savevr_tail(unsigned char* p, int r)
5291 {
5292   p = savevr<big_endian>(p, r);
5293   write_insn<big_endian>(p, blr);
5294   return p + 4;
5295 }
5296
5297 template<bool big_endian>
5298 static unsigned char*
5299 restvr(unsigned char* p, int r)
5300 {
5301   uint32_t insn = li_12_0 + (1 << 16) - (32 - r) * 16;
5302   write_insn<big_endian>(p, insn);
5303   p = p + 4;
5304   insn = lvx_0_12_0 + (r << 21);
5305   write_insn<big_endian>(p, insn);
5306   return p + 4;
5307 }
5308
5309 template<bool big_endian>
5310 static unsigned char*
5311 restvr_tail(unsigned char* p, int r)
5312 {
5313   p = restvr<big_endian>(p, r);
5314   write_insn<big_endian>(p, blr);
5315   return p + 4;
5316 }
5317
5318
5319 template<int size, bool big_endian>
5320 Output_data_save_res<size, big_endian>::Output_data_save_res(
5321     Symbol_table* symtab)
5322   : Output_section_data_build(4),
5323     contents_(NULL)
5324 {
5325   this->savres_define(symtab,
5326                       "_savegpr0_", 14, 31,
5327                       savegpr0<big_endian>, savegpr0_tail<big_endian>);
5328   this->savres_define(symtab,
5329                       "_restgpr0_", 14, 29,
5330                       restgpr0<big_endian>, restgpr0_tail<big_endian>);
5331   this->savres_define(symtab,
5332                       "_restgpr0_", 30, 31,
5333                       restgpr0<big_endian>, restgpr0_tail<big_endian>);
5334   this->savres_define(symtab,
5335                       "_savegpr1_", 14, 31,
5336                       savegpr1<big_endian>, savegpr1_tail<big_endian>);
5337   this->savres_define(symtab,
5338                       "_restgpr1_", 14, 31,
5339                       restgpr1<big_endian>, restgpr1_tail<big_endian>);
5340   this->savres_define(symtab,
5341                       "_savefpr_", 14, 31,
5342                       savefpr<big_endian>, savefpr0_tail<big_endian>);
5343   this->savres_define(symtab,
5344                       "_restfpr_", 14, 29,
5345                       restfpr<big_endian>, restfpr0_tail<big_endian>);
5346   this->savres_define(symtab,
5347                       "_restfpr_", 30, 31,
5348                       restfpr<big_endian>, restfpr0_tail<big_endian>);
5349   this->savres_define(symtab,
5350                       "._savef", 14, 31,
5351                       savefpr<big_endian>, savefpr1_tail<big_endian>);
5352   this->savres_define(symtab,
5353                       "._restf", 14, 31,
5354                       restfpr<big_endian>, restfpr1_tail<big_endian>);
5355   this->savres_define(symtab,
5356                       "_savevr_", 20, 31,
5357                       savevr<big_endian>, savevr_tail<big_endian>);
5358   this->savres_define(symtab,
5359                       "_restvr_", 20, 31,
5360                       restvr<big_endian>, restvr_tail<big_endian>);
5361 }
5362
5363 template<int size, bool big_endian>
5364 void
5365 Output_data_save_res<size, big_endian>::savres_define(
5366     Symbol_table* symtab,
5367     const char *name,
5368     unsigned int lo, unsigned int hi,
5369     unsigned char* write_ent(unsigned char*, int),
5370     unsigned char* write_tail(unsigned char*, int))
5371 {
5372   size_t len = strlen(name);
5373   bool writing = false;
5374   char sym[16];
5375
5376   memcpy(sym, name, len);
5377   sym[len + 2] = 0;
5378
5379   for (unsigned int i = lo; i <= hi; i++)
5380     {
5381       sym[len + 0] = i / 10 + '0';
5382       sym[len + 1] = i % 10 + '0';
5383       Symbol* gsym = symtab->lookup(sym);
5384       bool refd = gsym != NULL && gsym->is_undefined();
5385       writing = writing || refd;
5386       if (writing)
5387         {
5388           if (this->contents_ == NULL)
5389             this->contents_ = new unsigned char[this->savres_max];
5390
5391           section_size_type value = this->current_data_size();
5392           unsigned char* p = this->contents_ + value;
5393           if (i != hi)
5394             p = write_ent(p, i);
5395           else
5396             p = write_tail(p, i);
5397           section_size_type cur_size = p - this->contents_;
5398           this->set_current_data_size(cur_size);
5399           if (refd)
5400             symtab->define_in_output_data(sym, NULL, Symbol_table::PREDEFINED,
5401                                           this, value, cur_size - value,
5402                                           elfcpp::STT_FUNC, elfcpp::STB_GLOBAL,
5403                                           elfcpp::STV_HIDDEN, 0, false, false);
5404         }
5405     }
5406 }
5407
5408 // Write out save/restore.
5409
5410 template<int size, bool big_endian>
5411 void
5412 Output_data_save_res<size, big_endian>::do_write(Output_file* of)
5413 {
5414   const section_size_type off = this->offset();
5415   const section_size_type oview_size =
5416     convert_to_section_size_type(this->data_size());
5417   unsigned char* const oview = of->get_output_view(off, oview_size);
5418   memcpy(oview, this->contents_, oview_size);
5419   of->write_output_view(off, oview_size, oview);
5420 }
5421
5422
5423 // Create the glink section.
5424
5425 template<int size, bool big_endian>
5426 void
5427 Target_powerpc<size, big_endian>::make_glink_section(Layout* layout)
5428 {
5429   if (this->glink_ == NULL)
5430     {
5431       this->glink_ = new Output_data_glink<size, big_endian>(this);
5432       this->glink_->add_eh_frame(layout);
5433       layout->add_output_section_data(".text", elfcpp::SHT_PROGBITS,
5434                                       elfcpp::SHF_ALLOC | elfcpp::SHF_EXECINSTR,
5435                                       this->glink_, ORDER_TEXT, false);
5436     }
5437 }
5438
5439 // Create a PLT entry for a global symbol.
5440
5441 template<int size, bool big_endian>
5442 void
5443 Target_powerpc<size, big_endian>::make_plt_entry(Symbol_table* symtab,
5444                                                  Layout* layout,
5445                                                  Symbol* gsym)
5446 {
5447   if (gsym->type() == elfcpp::STT_GNU_IFUNC
5448       && gsym->can_use_relative_reloc(false))
5449     {
5450       if (this->iplt_ == NULL)
5451         this->make_iplt_section(symtab, layout);
5452       this->iplt_->add_ifunc_entry(gsym);
5453     }
5454   else
5455     {
5456       if (this->plt_ == NULL)
5457         this->make_plt_section(symtab, layout);
5458       this->plt_->add_entry(gsym);
5459     }
5460 }
5461
5462 // Make a PLT entry for a local STT_GNU_IFUNC symbol.
5463
5464 template<int size, bool big_endian>
5465 void
5466 Target_powerpc<size, big_endian>::make_local_ifunc_plt_entry(
5467     Symbol_table* symtab,
5468     Layout* layout,
5469     Sized_relobj_file<size, big_endian>* relobj,
5470     unsigned int r_sym)
5471 {
5472   if (this->iplt_ == NULL)
5473     this->make_iplt_section(symtab, layout);
5474   this->iplt_->add_local_ifunc_entry(relobj, r_sym);
5475 }
5476
5477 // Return the number of entries in the PLT.
5478
5479 template<int size, bool big_endian>
5480 unsigned int
5481 Target_powerpc<size, big_endian>::plt_entry_count() const
5482 {
5483   if (this->plt_ == NULL)
5484     return 0;
5485   return this->plt_->entry_count();
5486 }
5487
5488 // Create a GOT entry for local dynamic __tls_get_addr calls.
5489
5490 template<int size, bool big_endian>
5491 unsigned int
5492 Target_powerpc<size, big_endian>::tlsld_got_offset(
5493     Symbol_table* symtab,
5494     Layout* layout,
5495     Sized_relobj_file<size, big_endian>* object)
5496 {
5497   if (this->tlsld_got_offset_ == -1U)
5498     {
5499       gold_assert(symtab != NULL && layout != NULL && object != NULL);
5500       Reloc_section* rela_dyn = this->rela_dyn_section(layout);
5501       Output_data_got_powerpc<size, big_endian>* got
5502         = this->got_section(symtab, layout);
5503       unsigned int got_offset = got->add_constant_pair(0, 0);
5504       rela_dyn->add_local(object, 0, elfcpp::R_POWERPC_DTPMOD, got,
5505                           got_offset, 0);
5506       this->tlsld_got_offset_ = got_offset;
5507     }
5508   return this->tlsld_got_offset_;
5509 }
5510
5511 // Get the Reference_flags for a particular relocation.
5512
5513 template<int size, bool big_endian>
5514 int
5515 Target_powerpc<size, big_endian>::Scan::get_reference_flags(
5516     unsigned int r_type,
5517     const Target_powerpc* target)
5518 {
5519   int ref = 0;
5520
5521   switch (r_type)
5522     {
5523     case elfcpp::R_POWERPC_NONE:
5524     case elfcpp::R_POWERPC_GNU_VTINHERIT:
5525     case elfcpp::R_POWERPC_GNU_VTENTRY:
5526     case elfcpp::R_PPC64_TOC:
5527       // No symbol reference.
5528       break;
5529
5530     case elfcpp::R_PPC64_ADDR64:
5531     case elfcpp::R_PPC64_UADDR64:
5532     case elfcpp::R_POWERPC_ADDR32:
5533     case elfcpp::R_POWERPC_UADDR32:
5534     case elfcpp::R_POWERPC_ADDR16:
5535     case elfcpp::R_POWERPC_UADDR16:
5536     case elfcpp::R_POWERPC_ADDR16_LO:
5537     case elfcpp::R_POWERPC_ADDR16_HI:
5538     case elfcpp::R_POWERPC_ADDR16_HA:
5539       ref = Symbol::ABSOLUTE_REF;
5540       break;
5541
5542     case elfcpp::R_POWERPC_ADDR24:
5543     case elfcpp::R_POWERPC_ADDR14:
5544     case elfcpp::R_POWERPC_ADDR14_BRTAKEN:
5545     case elfcpp::R_POWERPC_ADDR14_BRNTAKEN:
5546       ref = Symbol::FUNCTION_CALL | Symbol::ABSOLUTE_REF;
5547       break;
5548
5549     case elfcpp::R_PPC64_REL64:
5550     case elfcpp::R_POWERPC_REL32:
5551     case elfcpp::R_PPC_LOCAL24PC:
5552     case elfcpp::R_POWERPC_REL16:
5553     case elfcpp::R_POWERPC_REL16_LO:
5554     case elfcpp::R_POWERPC_REL16_HI:
5555     case elfcpp::R_POWERPC_REL16_HA:
5556       ref = Symbol::RELATIVE_REF;
5557       break;
5558
5559     case elfcpp::R_POWERPC_REL24:
5560     case elfcpp::R_PPC_PLTREL24:
5561     case elfcpp::R_POWERPC_REL14:
5562     case elfcpp::R_POWERPC_REL14_BRTAKEN:
5563     case elfcpp::R_POWERPC_REL14_BRNTAKEN:
5564       ref = Symbol::FUNCTION_CALL | Symbol::RELATIVE_REF;
5565       break;
5566
5567     case elfcpp::R_POWERPC_GOT16:
5568     case elfcpp::R_POWERPC_GOT16_LO:
5569     case elfcpp::R_POWERPC_GOT16_HI:
5570     case elfcpp::R_POWERPC_GOT16_HA:
5571     case elfcpp::R_PPC64_GOT16_DS:
5572     case elfcpp::R_PPC64_GOT16_LO_DS:
5573     case elfcpp::R_PPC64_TOC16:
5574     case elfcpp::R_PPC64_TOC16_LO:
5575     case elfcpp::R_PPC64_TOC16_HI:
5576     case elfcpp::R_PPC64_TOC16_HA:
5577     case elfcpp::R_PPC64_TOC16_DS:
5578     case elfcpp::R_PPC64_TOC16_LO_DS:
5579       ref = Symbol::RELATIVE_REF;
5580       break;
5581
5582     case elfcpp::R_POWERPC_GOT_TPREL16:
5583     case elfcpp::R_POWERPC_TLS:
5584       ref = Symbol::TLS_REF;
5585       break;
5586
5587     case elfcpp::R_POWERPC_COPY:
5588     case elfcpp::R_POWERPC_GLOB_DAT:
5589     case elfcpp::R_POWERPC_JMP_SLOT:
5590     case elfcpp::R_POWERPC_RELATIVE:
5591     case elfcpp::R_POWERPC_DTPMOD:
5592     default:
5593       // Not expected.  We will give an error later.
5594       break;
5595     }
5596
5597   if (size == 64 && target->abiversion() < 2)
5598     ref |= Symbol::FUNC_DESC_ABI;
5599   return ref;
5600 }
5601
5602 // Report an unsupported relocation against a local symbol.
5603
5604 template<int size, bool big_endian>
5605 void
5606 Target_powerpc<size, big_endian>::Scan::unsupported_reloc_local(
5607     Sized_relobj_file<size, big_endian>* object,
5608     unsigned int r_type)
5609 {
5610   gold_error(_("%s: unsupported reloc %u against local symbol"),
5611              object->name().c_str(), r_type);
5612 }
5613
5614 // We are about to emit a dynamic relocation of type R_TYPE.  If the
5615 // dynamic linker does not support it, issue an error.
5616
5617 template<int size, bool big_endian>
5618 void
5619 Target_powerpc<size, big_endian>::Scan::check_non_pic(Relobj* object,
5620                                                       unsigned int r_type)
5621 {
5622   gold_assert(r_type != elfcpp::R_POWERPC_NONE);
5623
5624   // These are the relocation types supported by glibc for both 32-bit
5625   // and 64-bit powerpc.
5626   switch (r_type)
5627     {
5628     case elfcpp::R_POWERPC_NONE:
5629     case elfcpp::R_POWERPC_RELATIVE:
5630     case elfcpp::R_POWERPC_GLOB_DAT:
5631     case elfcpp::R_POWERPC_DTPMOD:
5632     case elfcpp::R_POWERPC_DTPREL:
5633     case elfcpp::R_POWERPC_TPREL:
5634     case elfcpp::R_POWERPC_JMP_SLOT:
5635     case elfcpp::R_POWERPC_COPY:
5636     case elfcpp::R_POWERPC_IRELATIVE:
5637     case elfcpp::R_POWERPC_ADDR32:
5638     case elfcpp::R_POWERPC_UADDR32:
5639     case elfcpp::R_POWERPC_ADDR24:
5640     case elfcpp::R_POWERPC_ADDR16:
5641     case elfcpp::R_POWERPC_UADDR16:
5642     case elfcpp::R_POWERPC_ADDR16_LO:
5643     case elfcpp::R_POWERPC_ADDR16_HI:
5644     case elfcpp::R_POWERPC_ADDR16_HA:
5645     case elfcpp::R_POWERPC_ADDR14:
5646     case elfcpp::R_POWERPC_ADDR14_BRTAKEN:
5647     case elfcpp::R_POWERPC_ADDR14_BRNTAKEN:
5648     case elfcpp::R_POWERPC_REL32:
5649     case elfcpp::R_POWERPC_REL24:
5650     case elfcpp::R_POWERPC_TPREL16:
5651     case elfcpp::R_POWERPC_TPREL16_LO:
5652     case elfcpp::R_POWERPC_TPREL16_HI:
5653     case elfcpp::R_POWERPC_TPREL16_HA:
5654       return;
5655
5656     default:
5657       break;
5658     }
5659
5660   if (size == 64)
5661     {
5662       switch (r_type)
5663         {
5664           // These are the relocation types supported only on 64-bit.
5665         case elfcpp::R_PPC64_ADDR64:
5666         case elfcpp::R_PPC64_UADDR64:
5667         case elfcpp::R_PPC64_JMP_IREL:
5668         case elfcpp::R_PPC64_ADDR16_DS:
5669         case elfcpp::R_PPC64_ADDR16_LO_DS:
5670         case elfcpp::R_PPC64_ADDR16_HIGH:
5671         case elfcpp::R_PPC64_ADDR16_HIGHA:
5672         case elfcpp::R_PPC64_ADDR16_HIGHER:
5673         case elfcpp::R_PPC64_ADDR16_HIGHEST:
5674         case elfcpp::R_PPC64_ADDR16_HIGHERA:
5675         case elfcpp::R_PPC64_ADDR16_HIGHESTA:
5676         case elfcpp::R_PPC64_REL64:
5677         case elfcpp::R_POWERPC_ADDR30:
5678         case elfcpp::R_PPC64_TPREL16_DS:
5679         case elfcpp::R_PPC64_TPREL16_LO_DS:
5680         case elfcpp::R_PPC64_TPREL16_HIGH:
5681         case elfcpp::R_PPC64_TPREL16_HIGHA:
5682         case elfcpp::R_PPC64_TPREL16_HIGHER:
5683         case elfcpp::R_PPC64_TPREL16_HIGHEST:
5684         case elfcpp::R_PPC64_TPREL16_HIGHERA:
5685         case elfcpp::R_PPC64_TPREL16_HIGHESTA:
5686           return;
5687
5688         default:
5689           break;
5690         }
5691     }
5692   else
5693     {
5694       switch (r_type)
5695         {
5696           // These are the relocation types supported only on 32-bit.
5697           // ??? glibc ld.so doesn't need to support these.
5698         case elfcpp::R_POWERPC_DTPREL16:
5699         case elfcpp::R_POWERPC_DTPREL16_LO:
5700         case elfcpp::R_POWERPC_DTPREL16_HI:
5701         case elfcpp::R_POWERPC_DTPREL16_HA:
5702           return;
5703
5704         default:
5705           break;
5706         }
5707     }
5708
5709   // This prevents us from issuing more than one error per reloc
5710   // section.  But we can still wind up issuing more than one
5711   // error per object file.
5712   if (this->issued_non_pic_error_)
5713     return;
5714   gold_assert(parameters->options().output_is_position_independent());
5715   object->error(_("requires unsupported dynamic reloc; "
5716                   "recompile with -fPIC"));
5717   this->issued_non_pic_error_ = true;
5718   return;
5719 }
5720
5721 // Return whether we need to make a PLT entry for a relocation of the
5722 // given type against a STT_GNU_IFUNC symbol.
5723
5724 template<int size, bool big_endian>
5725 bool
5726 Target_powerpc<size, big_endian>::Scan::reloc_needs_plt_for_ifunc(
5727      Target_powerpc<size, big_endian>* target,
5728      Sized_relobj_file<size, big_endian>* object,
5729      unsigned int r_type,
5730      bool report_err)
5731 {
5732   // In non-pic code any reference will resolve to the plt call stub
5733   // for the ifunc symbol.
5734   if ((size == 32 || target->abiversion() >= 2)
5735       && !parameters->options().output_is_position_independent())
5736     return true;
5737
5738   switch (r_type)
5739     {
5740     // Word size refs from data sections are OK, but don't need a PLT entry.
5741     case elfcpp::R_POWERPC_ADDR32:
5742     case elfcpp::R_POWERPC_UADDR32:
5743       if (size == 32)
5744         return false;
5745       break;
5746
5747     case elfcpp::R_PPC64_ADDR64:
5748     case elfcpp::R_PPC64_UADDR64:
5749       if (size == 64)
5750         return false;
5751       break;
5752
5753     // GOT refs are good, but also don't need a PLT entry.
5754     case elfcpp::R_POWERPC_GOT16:
5755     case elfcpp::R_POWERPC_GOT16_LO:
5756     case elfcpp::R_POWERPC_GOT16_HI:
5757     case elfcpp::R_POWERPC_GOT16_HA:
5758     case elfcpp::R_PPC64_GOT16_DS:
5759     case elfcpp::R_PPC64_GOT16_LO_DS:
5760       return false;
5761
5762     // Function calls are good, and these do need a PLT entry.
5763     case elfcpp::R_POWERPC_ADDR24:
5764     case elfcpp::R_POWERPC_ADDR14:
5765     case elfcpp::R_POWERPC_ADDR14_BRTAKEN:
5766     case elfcpp::R_POWERPC_ADDR14_BRNTAKEN:
5767     case elfcpp::R_POWERPC_REL24:
5768     case elfcpp::R_PPC_PLTREL24:
5769     case elfcpp::R_POWERPC_REL14:
5770     case elfcpp::R_POWERPC_REL14_BRTAKEN:
5771     case elfcpp::R_POWERPC_REL14_BRNTAKEN:
5772       return true;
5773
5774     default:
5775       break;
5776     }
5777
5778   // Anything else is a problem.
5779   // If we are building a static executable, the libc startup function
5780   // responsible for applying indirect function relocations is going
5781   // to complain about the reloc type.
5782   // If we are building a dynamic executable, we will have a text
5783   // relocation.  The dynamic loader will set the text segment
5784   // writable and non-executable to apply text relocations.  So we'll
5785   // segfault when trying to run the indirection function to resolve
5786   // the reloc.
5787   if (report_err)
5788     gold_error(_("%s: unsupported reloc %u for IFUNC symbol"),
5789                object->name().c_str(), r_type);
5790   return false;
5791 }
5792
5793 // Return TRUE iff INSN is one we expect on a _LO variety toc/got
5794 // reloc.
5795
5796 static bool
5797 ok_lo_toc_insn(uint32_t insn, unsigned int r_type)
5798 {
5799   return ((insn & (0x3f << 26)) == 12u << 26 /* addic */
5800           || (insn & (0x3f << 26)) == 14u << 26 /* addi */
5801           || (insn & (0x3f << 26)) == 32u << 26 /* lwz */
5802           || (insn & (0x3f << 26)) == 34u << 26 /* lbz */
5803           || (insn & (0x3f << 26)) == 36u << 26 /* stw */
5804           || (insn & (0x3f << 26)) == 38u << 26 /* stb */
5805           || (insn & (0x3f << 26)) == 40u << 26 /* lhz */
5806           || (insn & (0x3f << 26)) == 42u << 26 /* lha */
5807           || (insn & (0x3f << 26)) == 44u << 26 /* sth */
5808           || (insn & (0x3f << 26)) == 46u << 26 /* lmw */
5809           || (insn & (0x3f << 26)) == 47u << 26 /* stmw */
5810           || (insn & (0x3f << 26)) == 48u << 26 /* lfs */
5811           || (insn & (0x3f << 26)) == 50u << 26 /* lfd */
5812           || (insn & (0x3f << 26)) == 52u << 26 /* stfs */
5813           || (insn & (0x3f << 26)) == 54u << 26 /* stfd */
5814           || (insn & (0x3f << 26)) == 56u << 26 /* lq,lfq */
5815           || ((insn & (0x3f << 26)) == 57u << 26 /* lxsd,lxssp,lfdp */
5816               /* Exclude lfqu by testing reloc.  If relocs are ever
5817                  defined for the reduced D field in psq_lu then those
5818                  will need testing too.  */
5819               && r_type != elfcpp::R_PPC64_TOC16_LO
5820               && r_type != elfcpp::R_POWERPC_GOT16_LO)
5821           || ((insn & (0x3f << 26)) == 58u << 26 /* ld,lwa */
5822               && (insn & 1) == 0)
5823           || (insn & (0x3f << 26)) == 60u << 26 /* stfq */
5824           || ((insn & (0x3f << 26)) == 61u << 26 /* lxv,stx{v,sd,ssp},stfdp */
5825               /* Exclude stfqu.  psq_stu as above for psq_lu.  */
5826               && r_type != elfcpp::R_PPC64_TOC16_LO
5827               && r_type != elfcpp::R_POWERPC_GOT16_LO)
5828           || ((insn & (0x3f << 26)) == 62u << 26 /* std,stq */
5829               && (insn & 1) == 0));
5830 }
5831
5832 // Scan a relocation for a local symbol.
5833
5834 template<int size, bool big_endian>
5835 inline void
5836 Target_powerpc<size, big_endian>::Scan::local(
5837     Symbol_table* symtab,
5838     Layout* layout,
5839     Target_powerpc<size, big_endian>* target,
5840     Sized_relobj_file<size, big_endian>* object,
5841     unsigned int data_shndx,
5842     Output_section* output_section,
5843     const elfcpp::Rela<size, big_endian>& reloc,
5844     unsigned int r_type,
5845     const elfcpp::Sym<size, big_endian>& lsym,
5846     bool is_discarded)
5847 {
5848   this->maybe_skip_tls_get_addr_call(r_type, NULL);
5849
5850   if ((size == 64 && r_type == elfcpp::R_PPC64_TLSGD)
5851       || (size == 32 && r_type == elfcpp::R_PPC_TLSGD))
5852     {
5853       this->expect_tls_get_addr_call();
5854       const tls::Tls_optimization tls_type = target->optimize_tls_gd(true);
5855       if (tls_type != tls::TLSOPT_NONE)
5856         this->skip_next_tls_get_addr_call();
5857     }
5858   else if ((size == 64 && r_type == elfcpp::R_PPC64_TLSLD)
5859            || (size == 32 && r_type == elfcpp::R_PPC_TLSLD))
5860     {
5861       this->expect_tls_get_addr_call();
5862       const tls::Tls_optimization tls_type = target->optimize_tls_ld();
5863       if (tls_type != tls::TLSOPT_NONE)
5864         this->skip_next_tls_get_addr_call();
5865     }
5866
5867   Powerpc_relobj<size, big_endian>* ppc_object
5868     = static_cast<Powerpc_relobj<size, big_endian>*>(object);
5869
5870   if (is_discarded)
5871     {
5872       if (size == 64
5873           && data_shndx == ppc_object->opd_shndx()
5874           && r_type == elfcpp::R_PPC64_ADDR64)
5875         ppc_object->set_opd_discard(reloc.get_r_offset());
5876       return;
5877     }
5878
5879   // A local STT_GNU_IFUNC symbol may require a PLT entry.
5880   bool is_ifunc = lsym.get_st_type() == elfcpp::STT_GNU_IFUNC;
5881   if (is_ifunc && this->reloc_needs_plt_for_ifunc(target, object, r_type, true))
5882     {
5883       unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
5884       target->push_branch(ppc_object, data_shndx, reloc.get_r_offset(),
5885                           r_type, r_sym, reloc.get_r_addend());
5886       target->make_local_ifunc_plt_entry(symtab, layout, object, r_sym);
5887     }
5888
5889   switch (r_type)
5890     {
5891     case elfcpp::R_POWERPC_NONE:
5892     case elfcpp::R_POWERPC_GNU_VTINHERIT:
5893     case elfcpp::R_POWERPC_GNU_VTENTRY:
5894     case elfcpp::R_PPC64_TOCSAVE:
5895     case elfcpp::R_POWERPC_TLS:
5896     case elfcpp::R_PPC64_ENTRY:
5897       break;
5898
5899     case elfcpp::R_PPC64_TOC:
5900       {
5901         Output_data_got_powerpc<size, big_endian>* got
5902           = target->got_section(symtab, layout);
5903         if (parameters->options().output_is_position_independent())
5904           {
5905             Address off = reloc.get_r_offset();
5906             if (size == 64
5907                 && target->abiversion() < 2
5908                 && data_shndx == ppc_object->opd_shndx()
5909                 && ppc_object->get_opd_discard(off - 8))
5910               break;
5911
5912             Reloc_section* rela_dyn = target->rela_dyn_section(layout);
5913             Powerpc_relobj<size, big_endian>* symobj = ppc_object;
5914             rela_dyn->add_output_section_relative(got->output_section(),
5915                                                   elfcpp::R_POWERPC_RELATIVE,
5916                                                   output_section,
5917                                                   object, data_shndx, off,
5918                                                   symobj->toc_base_offset());
5919           }
5920       }
5921       break;
5922
5923     case elfcpp::R_PPC64_ADDR64:
5924     case elfcpp::R_PPC64_UADDR64:
5925     case elfcpp::R_POWERPC_ADDR32:
5926     case elfcpp::R_POWERPC_UADDR32:
5927     case elfcpp::R_POWERPC_ADDR24:
5928     case elfcpp::R_POWERPC_ADDR16:
5929     case elfcpp::R_POWERPC_ADDR16_LO:
5930     case elfcpp::R_POWERPC_ADDR16_HI:
5931     case elfcpp::R_POWERPC_ADDR16_HA:
5932     case elfcpp::R_POWERPC_UADDR16:
5933     case elfcpp::R_PPC64_ADDR16_HIGH:
5934     case elfcpp::R_PPC64_ADDR16_HIGHA:
5935     case elfcpp::R_PPC64_ADDR16_HIGHER:
5936     case elfcpp::R_PPC64_ADDR16_HIGHERA:
5937     case elfcpp::R_PPC64_ADDR16_HIGHEST:
5938     case elfcpp::R_PPC64_ADDR16_HIGHESTA:
5939     case elfcpp::R_PPC64_ADDR16_DS:
5940     case elfcpp::R_PPC64_ADDR16_LO_DS:
5941     case elfcpp::R_POWERPC_ADDR14:
5942     case elfcpp::R_POWERPC_ADDR14_BRTAKEN:
5943     case elfcpp::R_POWERPC_ADDR14_BRNTAKEN:
5944       // If building a shared library (or a position-independent
5945       // executable), we need to create a dynamic relocation for
5946       // this location.
5947       if (parameters->options().output_is_position_independent()
5948           || (size == 64 && is_ifunc && target->abiversion() < 2))
5949         {
5950           Reloc_section* rela_dyn = target->rela_dyn_section(symtab, layout,
5951                                                              is_ifunc);
5952           unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
5953           if ((size == 32 && r_type == elfcpp::R_POWERPC_ADDR32)
5954               || (size == 64 && r_type == elfcpp::R_PPC64_ADDR64))
5955             {
5956               unsigned int dynrel = (is_ifunc ? elfcpp::R_POWERPC_IRELATIVE
5957                                      : elfcpp::R_POWERPC_RELATIVE);
5958               rela_dyn->add_local_relative(object, r_sym, dynrel,
5959                                            output_section, data_shndx,
5960                                            reloc.get_r_offset(),
5961                                            reloc.get_r_addend(), false);
5962             }
5963           else if (lsym.get_st_type() != elfcpp::STT_SECTION)
5964             {
5965               check_non_pic(object, r_type);
5966               rela_dyn->add_local(object, r_sym, r_type, output_section,
5967                                   data_shndx, reloc.get_r_offset(),
5968                                   reloc.get_r_addend());
5969             }
5970           else
5971             {
5972               gold_assert(lsym.get_st_value() == 0);
5973               unsigned int shndx = lsym.get_st_shndx();
5974               bool is_ordinary;
5975               shndx = object->adjust_sym_shndx(r_sym, shndx,
5976                                                &is_ordinary);
5977               if (!is_ordinary)
5978                 object->error(_("section symbol %u has bad shndx %u"),
5979                               r_sym, shndx);
5980               else
5981                 rela_dyn->add_local_section(object, shndx, r_type,
5982                                             output_section, data_shndx,
5983                                             reloc.get_r_offset());
5984             }
5985         }
5986       break;
5987
5988     case elfcpp::R_POWERPC_REL24:
5989     case elfcpp::R_PPC_PLTREL24:
5990     case elfcpp::R_PPC_LOCAL24PC:
5991     case elfcpp::R_POWERPC_REL14:
5992     case elfcpp::R_POWERPC_REL14_BRTAKEN:
5993     case elfcpp::R_POWERPC_REL14_BRNTAKEN:
5994       if (!is_ifunc)
5995         {
5996           unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
5997           target->push_branch(ppc_object, data_shndx, reloc.get_r_offset(),
5998                               r_type, r_sym, reloc.get_r_addend());
5999         }
6000       break;
6001
6002     case elfcpp::R_PPC64_REL64:
6003     case elfcpp::R_POWERPC_REL32:
6004     case elfcpp::R_POWERPC_REL16:
6005     case elfcpp::R_POWERPC_REL16_LO:
6006     case elfcpp::R_POWERPC_REL16_HI:
6007     case elfcpp::R_POWERPC_REL16_HA:
6008     case elfcpp::R_POWERPC_REL16DX_HA:
6009     case elfcpp::R_POWERPC_SECTOFF:
6010     case elfcpp::R_POWERPC_SECTOFF_LO:
6011     case elfcpp::R_POWERPC_SECTOFF_HI:
6012     case elfcpp::R_POWERPC_SECTOFF_HA:
6013     case elfcpp::R_PPC64_SECTOFF_DS:
6014     case elfcpp::R_PPC64_SECTOFF_LO_DS:
6015     case elfcpp::R_POWERPC_TPREL16:
6016     case elfcpp::R_POWERPC_TPREL16_LO:
6017     case elfcpp::R_POWERPC_TPREL16_HI:
6018     case elfcpp::R_POWERPC_TPREL16_HA:
6019     case elfcpp::R_PPC64_TPREL16_DS:
6020     case elfcpp::R_PPC64_TPREL16_LO_DS:
6021     case elfcpp::R_PPC64_TPREL16_HIGH:
6022     case elfcpp::R_PPC64_TPREL16_HIGHA:
6023     case elfcpp::R_PPC64_TPREL16_HIGHER:
6024     case elfcpp::R_PPC64_TPREL16_HIGHERA:
6025     case elfcpp::R_PPC64_TPREL16_HIGHEST:
6026     case elfcpp::R_PPC64_TPREL16_HIGHESTA:
6027     case elfcpp::R_POWERPC_DTPREL16:
6028     case elfcpp::R_POWERPC_DTPREL16_LO:
6029     case elfcpp::R_POWERPC_DTPREL16_HI:
6030     case elfcpp::R_POWERPC_DTPREL16_HA:
6031     case elfcpp::R_PPC64_DTPREL16_DS:
6032     case elfcpp::R_PPC64_DTPREL16_LO_DS:
6033     case elfcpp::R_PPC64_DTPREL16_HIGH:
6034     case elfcpp::R_PPC64_DTPREL16_HIGHA:
6035     case elfcpp::R_PPC64_DTPREL16_HIGHER:
6036     case elfcpp::R_PPC64_DTPREL16_HIGHERA:
6037     case elfcpp::R_PPC64_DTPREL16_HIGHEST:
6038     case elfcpp::R_PPC64_DTPREL16_HIGHESTA:
6039     case elfcpp::R_PPC64_TLSGD:
6040     case elfcpp::R_PPC64_TLSLD:
6041     case elfcpp::R_PPC64_ADDR64_LOCAL:
6042       break;
6043
6044     case elfcpp::R_POWERPC_GOT16:
6045     case elfcpp::R_POWERPC_GOT16_LO:
6046     case elfcpp::R_POWERPC_GOT16_HI:
6047     case elfcpp::R_POWERPC_GOT16_HA:
6048     case elfcpp::R_PPC64_GOT16_DS:
6049     case elfcpp::R_PPC64_GOT16_LO_DS:
6050       {
6051         // The symbol requires a GOT entry.
6052         Output_data_got_powerpc<size, big_endian>* got
6053           = target->got_section(symtab, layout);
6054         unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
6055
6056         if (!parameters->options().output_is_position_independent())
6057           {
6058             if (is_ifunc
6059                 && (size == 32 || target->abiversion() >= 2))
6060               got->add_local_plt(object, r_sym, GOT_TYPE_STANDARD);
6061             else
6062               got->add_local(object, r_sym, GOT_TYPE_STANDARD);
6063           }
6064         else if (!object->local_has_got_offset(r_sym, GOT_TYPE_STANDARD))
6065           {
6066             // If we are generating a shared object or a pie, this
6067             // symbol's GOT entry will be set by a dynamic relocation.
6068             unsigned int off;
6069             off = got->add_constant(0);
6070             object->set_local_got_offset(r_sym, GOT_TYPE_STANDARD, off);
6071
6072             Reloc_section* rela_dyn = target->rela_dyn_section(symtab, layout,
6073                                                                is_ifunc);
6074             unsigned int dynrel = (is_ifunc ? elfcpp::R_POWERPC_IRELATIVE
6075                                    : elfcpp::R_POWERPC_RELATIVE);
6076             rela_dyn->add_local_relative(object, r_sym, dynrel,
6077                                          got, off, 0, false);
6078           }
6079       }
6080       break;
6081
6082     case elfcpp::R_PPC64_TOC16:
6083     case elfcpp::R_PPC64_TOC16_LO:
6084     case elfcpp::R_PPC64_TOC16_HI:
6085     case elfcpp::R_PPC64_TOC16_HA:
6086     case elfcpp::R_PPC64_TOC16_DS:
6087     case elfcpp::R_PPC64_TOC16_LO_DS:
6088       // We need a GOT section.
6089       target->got_section(symtab, layout);
6090       break;
6091
6092     case elfcpp::R_POWERPC_GOT_TLSGD16:
6093     case elfcpp::R_POWERPC_GOT_TLSGD16_LO:
6094     case elfcpp::R_POWERPC_GOT_TLSGD16_HI:
6095     case elfcpp::R_POWERPC_GOT_TLSGD16_HA:
6096       {
6097         const tls::Tls_optimization tls_type = target->optimize_tls_gd(true);
6098         if (tls_type == tls::TLSOPT_NONE)
6099           {
6100             Output_data_got_powerpc<size, big_endian>* got
6101               = target->got_section(symtab, layout);
6102             unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
6103             Reloc_section* rela_dyn = target->rela_dyn_section(layout);
6104             got->add_local_tls_pair(object, r_sym, GOT_TYPE_TLSGD,
6105                                     rela_dyn, elfcpp::R_POWERPC_DTPMOD);
6106           }
6107         else if (tls_type == tls::TLSOPT_TO_LE)
6108           {
6109             // no GOT relocs needed for Local Exec.
6110           }
6111         else
6112           gold_unreachable();
6113       }
6114       break;
6115
6116     case elfcpp::R_POWERPC_GOT_TLSLD16:
6117     case elfcpp::R_POWERPC_GOT_TLSLD16_LO:
6118     case elfcpp::R_POWERPC_GOT_TLSLD16_HI:
6119     case elfcpp::R_POWERPC_GOT_TLSLD16_HA:
6120       {
6121         const tls::Tls_optimization tls_type = target->optimize_tls_ld();
6122         if (tls_type == tls::TLSOPT_NONE)
6123           target->tlsld_got_offset(symtab, layout, object);
6124         else if (tls_type == tls::TLSOPT_TO_LE)
6125           {
6126             // no GOT relocs needed for Local Exec.
6127             if (parameters->options().emit_relocs())
6128               {
6129                 Output_section* os = layout->tls_segment()->first_section();
6130                 gold_assert(os != NULL);
6131                 os->set_needs_symtab_index();
6132               }
6133           }
6134         else
6135           gold_unreachable();
6136       }
6137       break;
6138
6139     case elfcpp::R_POWERPC_GOT_DTPREL16:
6140     case elfcpp::R_POWERPC_GOT_DTPREL16_LO:
6141     case elfcpp::R_POWERPC_GOT_DTPREL16_HI:
6142     case elfcpp::R_POWERPC_GOT_DTPREL16_HA:
6143       {
6144         Output_data_got_powerpc<size, big_endian>* got
6145           = target->got_section(symtab, layout);
6146         unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
6147         got->add_local_tls(object, r_sym, GOT_TYPE_DTPREL);
6148       }
6149       break;
6150
6151     case elfcpp::R_POWERPC_GOT_TPREL16:
6152     case elfcpp::R_POWERPC_GOT_TPREL16_LO:
6153     case elfcpp::R_POWERPC_GOT_TPREL16_HI:
6154     case elfcpp::R_POWERPC_GOT_TPREL16_HA:
6155       {
6156         const tls::Tls_optimization tls_type = target->optimize_tls_ie(true);
6157         if (tls_type == tls::TLSOPT_NONE)
6158           {
6159             unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
6160             if (!object->local_has_got_offset(r_sym, GOT_TYPE_TPREL))
6161               {
6162                 Output_data_got_powerpc<size, big_endian>* got
6163                   = target->got_section(symtab, layout);
6164                 unsigned int off = got->add_constant(0);
6165                 object->set_local_got_offset(r_sym, GOT_TYPE_TPREL, off);
6166
6167                 Reloc_section* rela_dyn = target->rela_dyn_section(layout);
6168                 rela_dyn->add_symbolless_local_addend(object, r_sym,
6169                                                       elfcpp::R_POWERPC_TPREL,
6170                                                       got, off, 0);
6171               }
6172           }
6173         else if (tls_type == tls::TLSOPT_TO_LE)
6174           {
6175             // no GOT relocs needed for Local Exec.
6176           }
6177         else
6178           gold_unreachable();
6179       }
6180       break;
6181
6182     default:
6183       unsupported_reloc_local(object, r_type);
6184       break;
6185     }
6186
6187   if (size == 64
6188       && parameters->options().toc_optimize())
6189     {
6190       if (data_shndx == ppc_object->toc_shndx())
6191         {
6192           bool ok = true;
6193           if (r_type != elfcpp::R_PPC64_ADDR64
6194               || (is_ifunc && target->abiversion() < 2))
6195             ok = false;
6196           else if (parameters->options().output_is_position_independent())
6197             {
6198               if (is_ifunc)
6199                 ok = false;
6200               else
6201                 {
6202                   unsigned int shndx = lsym.get_st_shndx();
6203                   if (shndx >= elfcpp::SHN_LORESERVE
6204                       && shndx != elfcpp::SHN_XINDEX)
6205                     ok = false;
6206                 }
6207             }
6208           if (!ok)
6209             ppc_object->set_no_toc_opt(reloc.get_r_offset());
6210         }
6211
6212       enum {no_check, check_lo, check_ha} insn_check;
6213       switch (r_type)
6214         {
6215         default:
6216           insn_check = no_check;
6217           break;
6218
6219         case elfcpp::R_POWERPC_GOT_TLSLD16_HA:
6220         case elfcpp::R_POWERPC_GOT_TLSGD16_HA:
6221         case elfcpp::R_POWERPC_GOT_TPREL16_HA:
6222         case elfcpp::R_POWERPC_GOT_DTPREL16_HA:
6223         case elfcpp::R_POWERPC_GOT16_HA:
6224         case elfcpp::R_PPC64_TOC16_HA:
6225           insn_check = check_ha;
6226           break;
6227
6228         case elfcpp::R_POWERPC_GOT_TLSLD16_LO:
6229         case elfcpp::R_POWERPC_GOT_TLSGD16_LO:
6230         case elfcpp::R_POWERPC_GOT_TPREL16_LO:
6231         case elfcpp::R_POWERPC_GOT_DTPREL16_LO:
6232         case elfcpp::R_POWERPC_GOT16_LO:
6233         case elfcpp::R_PPC64_GOT16_LO_DS:
6234         case elfcpp::R_PPC64_TOC16_LO:
6235         case elfcpp::R_PPC64_TOC16_LO_DS:
6236           insn_check = check_lo;
6237           break;
6238         }
6239
6240       section_size_type slen;
6241       const unsigned char* view = NULL;
6242       if (insn_check != no_check)
6243         {
6244           view = ppc_object->section_contents(data_shndx, &slen, false);
6245           section_size_type off =
6246             convert_to_section_size_type(reloc.get_r_offset()) & -4;
6247           if (off < slen)
6248             {
6249               uint32_t insn = elfcpp::Swap<32, big_endian>::readval(view + off);
6250               if (insn_check == check_lo
6251                   ? !ok_lo_toc_insn(insn, r_type)
6252                   : ((insn & ((0x3f << 26) | 0x1f << 16))
6253                      != ((15u << 26) | (2 << 16)) /* addis rt,2,imm */))
6254                 {
6255                   ppc_object->set_no_toc_opt();
6256                   gold_warning(_("%s: toc optimization is not supported "
6257                                  "for %#08x instruction"),
6258                                ppc_object->name().c_str(), insn);
6259                 }
6260             }
6261         }
6262
6263       switch (r_type)
6264         {
6265         default:
6266           break;
6267         case elfcpp::R_PPC64_TOC16:
6268         case elfcpp::R_PPC64_TOC16_LO:
6269         case elfcpp::R_PPC64_TOC16_HI:
6270         case elfcpp::R_PPC64_TOC16_HA:
6271         case elfcpp::R_PPC64_TOC16_DS:
6272         case elfcpp::R_PPC64_TOC16_LO_DS:
6273           unsigned int shndx = lsym.get_st_shndx();
6274           unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
6275           bool is_ordinary;
6276           shndx = ppc_object->adjust_sym_shndx(r_sym, shndx, &is_ordinary);
6277           if (is_ordinary && shndx == ppc_object->toc_shndx())
6278             {
6279               Address dst_off = lsym.get_st_value() + reloc.get_r_offset();
6280               if (dst_off < ppc_object->section_size(shndx))
6281                 {
6282                   bool ok = false;
6283                   if (r_type == elfcpp::R_PPC64_TOC16_HA)
6284                     ok = true;
6285                   else if (r_type == elfcpp::R_PPC64_TOC16_LO_DS)
6286                     {
6287                       // Need to check that the insn is a ld
6288                       if (!view)
6289                         view = ppc_object->section_contents(data_shndx,
6290                                                             &slen,
6291                                                             false);
6292                       section_size_type off =
6293                         (convert_to_section_size_type(reloc.get_r_offset())
6294                          + (big_endian ? -2 : 3));
6295                       if (off < slen
6296                           && (view[off] & (0x3f << 2)) == 58u << 2)
6297                         ok = true;
6298                     }
6299                   if (!ok)
6300                     ppc_object->set_no_toc_opt(dst_off);
6301                 }
6302             }
6303           break;
6304         }
6305     }
6306
6307   if (size == 32)
6308     {
6309       switch (r_type)
6310         {
6311         case elfcpp::R_POWERPC_REL32:
6312           if (ppc_object->got2_shndx() != 0
6313               && parameters->options().output_is_position_independent())
6314             {
6315               unsigned int shndx = lsym.get_st_shndx();
6316               unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
6317               bool is_ordinary;
6318               shndx = ppc_object->adjust_sym_shndx(r_sym, shndx, &is_ordinary);
6319               if (is_ordinary && shndx == ppc_object->got2_shndx()
6320                   && (ppc_object->section_flags(data_shndx)
6321                       & elfcpp::SHF_EXECINSTR) != 0)
6322                 gold_error(_("%s: unsupported -mbss-plt code"),
6323                            ppc_object->name().c_str());
6324             }
6325           break;
6326         default:
6327           break;
6328         }
6329     }
6330
6331   switch (r_type)
6332     {
6333     case elfcpp::R_POWERPC_GOT_TLSLD16:
6334     case elfcpp::R_POWERPC_GOT_TLSGD16:
6335     case elfcpp::R_POWERPC_GOT_TPREL16:
6336     case elfcpp::R_POWERPC_GOT_DTPREL16:
6337     case elfcpp::R_POWERPC_GOT16:
6338     case elfcpp::R_PPC64_GOT16_DS:
6339     case elfcpp::R_PPC64_TOC16:
6340     case elfcpp::R_PPC64_TOC16_DS:
6341       ppc_object->set_has_small_toc_reloc();
6342     default:
6343       break;
6344     }
6345 }
6346
6347 // Report an unsupported relocation against a global symbol.
6348
6349 template<int size, bool big_endian>
6350 void
6351 Target_powerpc<size, big_endian>::Scan::unsupported_reloc_global(
6352     Sized_relobj_file<size, big_endian>* object,
6353     unsigned int r_type,
6354     Symbol* gsym)
6355 {
6356   gold_error(_("%s: unsupported reloc %u against global symbol %s"),
6357              object->name().c_str(), r_type, gsym->demangled_name().c_str());
6358 }
6359
6360 // Scan a relocation for a global symbol.
6361
6362 template<int size, bool big_endian>
6363 inline void
6364 Target_powerpc<size, big_endian>::Scan::global(
6365     Symbol_table* symtab,
6366     Layout* layout,
6367     Target_powerpc<size, big_endian>* target,
6368     Sized_relobj_file<size, big_endian>* object,
6369     unsigned int data_shndx,
6370     Output_section* output_section,
6371     const elfcpp::Rela<size, big_endian>& reloc,
6372     unsigned int r_type,
6373     Symbol* gsym)
6374 {
6375   if (this->maybe_skip_tls_get_addr_call(r_type, gsym) == Track_tls::SKIP)
6376     return;
6377
6378   if ((size == 64 && r_type == elfcpp::R_PPC64_TLSGD)
6379       || (size == 32 && r_type == elfcpp::R_PPC_TLSGD))
6380     {
6381       this->expect_tls_get_addr_call();
6382       const bool final = gsym->final_value_is_known();
6383       const tls::Tls_optimization tls_type = target->optimize_tls_gd(final);
6384       if (tls_type != tls::TLSOPT_NONE)
6385         this->skip_next_tls_get_addr_call();
6386     }
6387   else if ((size == 64 && r_type == elfcpp::R_PPC64_TLSLD)
6388            || (size == 32 && r_type == elfcpp::R_PPC_TLSLD))
6389     {
6390       this->expect_tls_get_addr_call();
6391       const tls::Tls_optimization tls_type = target->optimize_tls_ld();
6392       if (tls_type != tls::TLSOPT_NONE)
6393         this->skip_next_tls_get_addr_call();
6394     }
6395
6396   Powerpc_relobj<size, big_endian>* ppc_object
6397     = static_cast<Powerpc_relobj<size, big_endian>*>(object);
6398
6399   // A STT_GNU_IFUNC symbol may require a PLT entry.
6400   bool is_ifunc = gsym->type() == elfcpp::STT_GNU_IFUNC;
6401   bool pushed_ifunc = false;
6402   if (is_ifunc && this->reloc_needs_plt_for_ifunc(target, object, r_type, true))
6403     {
6404       unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
6405       target->push_branch(ppc_object, data_shndx, reloc.get_r_offset(),
6406                           r_type, r_sym, reloc.get_r_addend());
6407       target->make_plt_entry(symtab, layout, gsym);
6408       pushed_ifunc = true;
6409     }
6410
6411   switch (r_type)
6412     {
6413     case elfcpp::R_POWERPC_NONE:
6414     case elfcpp::R_POWERPC_GNU_VTINHERIT:
6415     case elfcpp::R_POWERPC_GNU_VTENTRY:
6416     case elfcpp::R_PPC_LOCAL24PC:
6417     case elfcpp::R_POWERPC_TLS:
6418     case elfcpp::R_PPC64_ENTRY:
6419       break;
6420
6421     case elfcpp::R_PPC64_TOC:
6422       {
6423         Output_data_got_powerpc<size, big_endian>* got
6424           = target->got_section(symtab, layout);
6425         if (parameters->options().output_is_position_independent())
6426           {
6427             Address off = reloc.get_r_offset();
6428             if (size == 64
6429                 && data_shndx == ppc_object->opd_shndx()
6430                 && ppc_object->get_opd_discard(off - 8))
6431               break;
6432
6433             Reloc_section* rela_dyn = target->rela_dyn_section(layout);
6434             Powerpc_relobj<size, big_endian>* symobj = ppc_object;
6435             if (data_shndx != ppc_object->opd_shndx())
6436               symobj = static_cast
6437                 <Powerpc_relobj<size, big_endian>*>(gsym->object());
6438             rela_dyn->add_output_section_relative(got->output_section(),
6439                                                   elfcpp::R_POWERPC_RELATIVE,
6440                                                   output_section,
6441                                                   object, data_shndx, off,
6442                                                   symobj->toc_base_offset());
6443           }
6444       }
6445       break;
6446
6447     case elfcpp::R_PPC64_ADDR64:
6448       if (size == 64
6449           && target->abiversion() < 2
6450           && data_shndx == ppc_object->opd_shndx()
6451           && (gsym->is_defined_in_discarded_section()
6452               || gsym->object() != object))
6453         {
6454           ppc_object->set_opd_discard(reloc.get_r_offset());
6455           break;
6456         }
6457       // Fall through.
6458     case elfcpp::R_PPC64_UADDR64:
6459     case elfcpp::R_POWERPC_ADDR32:
6460     case elfcpp::R_POWERPC_UADDR32:
6461     case elfcpp::R_POWERPC_ADDR24:
6462     case elfcpp::R_POWERPC_ADDR16:
6463     case elfcpp::R_POWERPC_ADDR16_LO:
6464     case elfcpp::R_POWERPC_ADDR16_HI:
6465     case elfcpp::R_POWERPC_ADDR16_HA:
6466     case elfcpp::R_POWERPC_UADDR16:
6467     case elfcpp::R_PPC64_ADDR16_HIGH:
6468     case elfcpp::R_PPC64_ADDR16_HIGHA:
6469     case elfcpp::R_PPC64_ADDR16_HIGHER:
6470     case elfcpp::R_PPC64_ADDR16_HIGHERA:
6471     case elfcpp::R_PPC64_ADDR16_HIGHEST:
6472     case elfcpp::R_PPC64_ADDR16_HIGHESTA:
6473     case elfcpp::R_PPC64_ADDR16_DS:
6474     case elfcpp::R_PPC64_ADDR16_LO_DS:
6475     case elfcpp::R_POWERPC_ADDR14:
6476     case elfcpp::R_POWERPC_ADDR14_BRTAKEN:
6477     case elfcpp::R_POWERPC_ADDR14_BRNTAKEN:
6478       {
6479         // Make a PLT entry if necessary.
6480         if (gsym->needs_plt_entry())
6481           {
6482             // Since this is not a PC-relative relocation, we may be
6483             // taking the address of a function. In that case we need to
6484             // set the entry in the dynamic symbol table to the address of
6485             // the PLT call stub.
6486             bool need_ifunc_plt = false;
6487             if ((size == 32 || target->abiversion() >= 2)
6488                 && gsym->is_from_dynobj()
6489                 && !parameters->options().output_is_position_independent())
6490               {
6491                 gsym->set_needs_dynsym_value();
6492                 need_ifunc_plt = true;
6493               }
6494             if (!is_ifunc || (!pushed_ifunc && need_ifunc_plt))
6495               {
6496                 unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
6497                 target->push_branch(ppc_object, data_shndx,
6498                                     reloc.get_r_offset(), r_type, r_sym,
6499                                     reloc.get_r_addend());
6500                 target->make_plt_entry(symtab, layout, gsym);
6501               }
6502           }
6503         // Make a dynamic relocation if necessary.
6504         if (gsym->needs_dynamic_reloc(Scan::get_reference_flags(r_type, target))
6505             || (size == 64 && is_ifunc && target->abiversion() < 2))
6506           {
6507             if (!parameters->options().output_is_position_independent()
6508                 && gsym->may_need_copy_reloc())
6509               {
6510                 target->copy_reloc(symtab, layout, object,
6511                                    data_shndx, output_section, gsym, reloc);
6512               }
6513             else if ((((size == 32
6514                         && r_type == elfcpp::R_POWERPC_ADDR32)
6515                        || (size == 64
6516                            && r_type == elfcpp::R_PPC64_ADDR64
6517                            && target->abiversion() >= 2))
6518                       && gsym->can_use_relative_reloc(false)
6519                       && !(gsym->visibility() == elfcpp::STV_PROTECTED
6520                            && parameters->options().shared()))
6521                      || (size == 64
6522                          && r_type == elfcpp::R_PPC64_ADDR64
6523                          && target->abiversion() < 2
6524                          && (gsym->can_use_relative_reloc(false)
6525                              || data_shndx == ppc_object->opd_shndx())))
6526               {
6527                 Reloc_section* rela_dyn
6528                   = target->rela_dyn_section(symtab, layout, is_ifunc);
6529                 unsigned int dynrel = (is_ifunc ? elfcpp::R_POWERPC_IRELATIVE
6530                                        : elfcpp::R_POWERPC_RELATIVE);
6531                 rela_dyn->add_symbolless_global_addend(
6532                     gsym, dynrel, output_section, object, data_shndx,
6533                     reloc.get_r_offset(), reloc.get_r_addend());
6534               }
6535             else
6536               {
6537                 Reloc_section* rela_dyn
6538                   = target->rela_dyn_section(symtab, layout, is_ifunc);
6539                 check_non_pic(object, r_type);
6540                 rela_dyn->add_global(gsym, r_type, output_section,
6541                                      object, data_shndx,
6542                                      reloc.get_r_offset(),
6543                                      reloc.get_r_addend());
6544
6545                 if (size == 64
6546                     && parameters->options().toc_optimize()
6547                     && data_shndx == ppc_object->toc_shndx())
6548                   ppc_object->set_no_toc_opt(reloc.get_r_offset());
6549               }
6550           }
6551       }
6552       break;
6553
6554     case elfcpp::R_PPC_PLTREL24:
6555     case elfcpp::R_POWERPC_REL24:
6556       if (!is_ifunc)
6557         {
6558           unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
6559           target->push_branch(ppc_object, data_shndx, reloc.get_r_offset(),
6560                               r_type, r_sym, reloc.get_r_addend());
6561           if (gsym->needs_plt_entry()
6562               || (!gsym->final_value_is_known()
6563                   && (gsym->is_undefined()
6564                       || gsym->is_from_dynobj()
6565                       || gsym->is_preemptible())))
6566             target->make_plt_entry(symtab, layout, gsym);
6567         }
6568       // Fall through.
6569
6570     case elfcpp::R_PPC64_REL64:
6571     case elfcpp::R_POWERPC_REL32:
6572       // Make a dynamic relocation if necessary.
6573       if (gsym->needs_dynamic_reloc(Scan::get_reference_flags(r_type, target)))
6574         {
6575           if (!parameters->options().output_is_position_independent()
6576               && gsym->may_need_copy_reloc())
6577             {
6578               target->copy_reloc(symtab, layout, object,
6579                                  data_shndx, output_section, gsym,
6580                                  reloc);
6581             }
6582           else
6583             {
6584               Reloc_section* rela_dyn
6585                 = target->rela_dyn_section(symtab, layout, is_ifunc);
6586               check_non_pic(object, r_type);
6587               rela_dyn->add_global(gsym, r_type, output_section, object,
6588                                    data_shndx, reloc.get_r_offset(),
6589                                    reloc.get_r_addend());
6590             }
6591         }
6592       break;
6593
6594     case elfcpp::R_POWERPC_REL14:
6595     case elfcpp::R_POWERPC_REL14_BRTAKEN:
6596     case elfcpp::R_POWERPC_REL14_BRNTAKEN:
6597       if (!is_ifunc)
6598         {
6599           unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
6600           target->push_branch(ppc_object, data_shndx, reloc.get_r_offset(),
6601                               r_type, r_sym, reloc.get_r_addend());
6602         }
6603       break;
6604
6605     case elfcpp::R_POWERPC_REL16:
6606     case elfcpp::R_POWERPC_REL16_LO:
6607     case elfcpp::R_POWERPC_REL16_HI:
6608     case elfcpp::R_POWERPC_REL16_HA:
6609     case elfcpp::R_POWERPC_REL16DX_HA:
6610     case elfcpp::R_POWERPC_SECTOFF:
6611     case elfcpp::R_POWERPC_SECTOFF_LO:
6612     case elfcpp::R_POWERPC_SECTOFF_HI:
6613     case elfcpp::R_POWERPC_SECTOFF_HA:
6614     case elfcpp::R_PPC64_SECTOFF_DS:
6615     case elfcpp::R_PPC64_SECTOFF_LO_DS:
6616     case elfcpp::R_POWERPC_TPREL16:
6617     case elfcpp::R_POWERPC_TPREL16_LO:
6618     case elfcpp::R_POWERPC_TPREL16_HI:
6619     case elfcpp::R_POWERPC_TPREL16_HA:
6620     case elfcpp::R_PPC64_TPREL16_DS:
6621     case elfcpp::R_PPC64_TPREL16_LO_DS:
6622     case elfcpp::R_PPC64_TPREL16_HIGH:
6623     case elfcpp::R_PPC64_TPREL16_HIGHA:
6624     case elfcpp::R_PPC64_TPREL16_HIGHER:
6625     case elfcpp::R_PPC64_TPREL16_HIGHERA:
6626     case elfcpp::R_PPC64_TPREL16_HIGHEST:
6627     case elfcpp::R_PPC64_TPREL16_HIGHESTA:
6628     case elfcpp::R_POWERPC_DTPREL16:
6629     case elfcpp::R_POWERPC_DTPREL16_LO:
6630     case elfcpp::R_POWERPC_DTPREL16_HI:
6631     case elfcpp::R_POWERPC_DTPREL16_HA:
6632     case elfcpp::R_PPC64_DTPREL16_DS:
6633     case elfcpp::R_PPC64_DTPREL16_LO_DS:
6634     case elfcpp::R_PPC64_DTPREL16_HIGH:
6635     case elfcpp::R_PPC64_DTPREL16_HIGHA:
6636     case elfcpp::R_PPC64_DTPREL16_HIGHER:
6637     case elfcpp::R_PPC64_DTPREL16_HIGHERA:
6638     case elfcpp::R_PPC64_DTPREL16_HIGHEST:
6639     case elfcpp::R_PPC64_DTPREL16_HIGHESTA:
6640     case elfcpp::R_PPC64_TLSGD:
6641     case elfcpp::R_PPC64_TLSLD:
6642     case elfcpp::R_PPC64_ADDR64_LOCAL:
6643       break;
6644
6645     case elfcpp::R_POWERPC_GOT16:
6646     case elfcpp::R_POWERPC_GOT16_LO:
6647     case elfcpp::R_POWERPC_GOT16_HI:
6648     case elfcpp::R_POWERPC_GOT16_HA:
6649     case elfcpp::R_PPC64_GOT16_DS:
6650     case elfcpp::R_PPC64_GOT16_LO_DS:
6651       {
6652         // The symbol requires a GOT entry.
6653         Output_data_got_powerpc<size, big_endian>* got;
6654
6655         got = target->got_section(symtab, layout);
6656         if (gsym->final_value_is_known())
6657           {
6658             if (is_ifunc
6659                 && (size == 32 || target->abiversion() >= 2))
6660               got->add_global_plt(gsym, GOT_TYPE_STANDARD);
6661             else
6662               got->add_global(gsym, GOT_TYPE_STANDARD);
6663           }
6664         else if (!gsym->has_got_offset(GOT_TYPE_STANDARD))
6665           {
6666             // If we are generating a shared object or a pie, this
6667             // symbol's GOT entry will be set by a dynamic relocation.
6668             unsigned int off = got->add_constant(0);
6669             gsym->set_got_offset(GOT_TYPE_STANDARD, off);
6670
6671             Reloc_section* rela_dyn
6672               = target->rela_dyn_section(symtab, layout, is_ifunc);
6673
6674             if (gsym->can_use_relative_reloc(false)
6675                 && !((size == 32
6676                       || target->abiversion() >= 2)
6677                      && gsym->visibility() == elfcpp::STV_PROTECTED
6678                      && parameters->options().shared()))
6679               {
6680                 unsigned int dynrel = (is_ifunc ? elfcpp::R_POWERPC_IRELATIVE
6681                                        : elfcpp::R_POWERPC_RELATIVE);
6682                 rela_dyn->add_global_relative(gsym, dynrel, got, off, 0, false);
6683               }
6684             else
6685               {
6686                 unsigned int dynrel = elfcpp::R_POWERPC_GLOB_DAT;
6687                 rela_dyn->add_global(gsym, dynrel, got, off, 0);
6688               }
6689           }
6690       }
6691       break;
6692
6693     case elfcpp::R_PPC64_TOC16:
6694     case elfcpp::R_PPC64_TOC16_LO:
6695     case elfcpp::R_PPC64_TOC16_HI:
6696     case elfcpp::R_PPC64_TOC16_HA:
6697     case elfcpp::R_PPC64_TOC16_DS:
6698     case elfcpp::R_PPC64_TOC16_LO_DS:
6699       // We need a GOT section.
6700       target->got_section(symtab, layout);
6701       break;
6702
6703     case elfcpp::R_POWERPC_GOT_TLSGD16:
6704     case elfcpp::R_POWERPC_GOT_TLSGD16_LO:
6705     case elfcpp::R_POWERPC_GOT_TLSGD16_HI:
6706     case elfcpp::R_POWERPC_GOT_TLSGD16_HA:
6707       {
6708         const bool final = gsym->final_value_is_known();
6709         const tls::Tls_optimization tls_type = target->optimize_tls_gd(final);
6710         if (tls_type == tls::TLSOPT_NONE)
6711           {
6712             Output_data_got_powerpc<size, big_endian>* got
6713               = target->got_section(symtab, layout);
6714             Reloc_section* rela_dyn = target->rela_dyn_section(layout);
6715             got->add_global_pair_with_rel(gsym, GOT_TYPE_TLSGD, rela_dyn,
6716                                           elfcpp::R_POWERPC_DTPMOD,
6717                                           elfcpp::R_POWERPC_DTPREL);
6718           }
6719         else if (tls_type == tls::TLSOPT_TO_IE)
6720           {
6721             if (!gsym->has_got_offset(GOT_TYPE_TPREL))
6722               {
6723                 Output_data_got_powerpc<size, big_endian>* got
6724                   = target->got_section(symtab, layout);
6725                 Reloc_section* rela_dyn = target->rela_dyn_section(layout);
6726                 if (gsym->is_undefined()
6727                     || gsym->is_from_dynobj())
6728                   {
6729                     got->add_global_with_rel(gsym, GOT_TYPE_TPREL, rela_dyn,
6730                                              elfcpp::R_POWERPC_TPREL);
6731                   }
6732                 else
6733                   {
6734                     unsigned int off = got->add_constant(0);
6735                     gsym->set_got_offset(GOT_TYPE_TPREL, off);
6736                     unsigned int dynrel = elfcpp::R_POWERPC_TPREL;
6737                     rela_dyn->add_symbolless_global_addend(gsym, dynrel,
6738                                                            got, off, 0);
6739                   }
6740               }
6741           }
6742         else if (tls_type == tls::TLSOPT_TO_LE)
6743           {
6744             // no GOT relocs needed for Local Exec.
6745           }
6746         else
6747           gold_unreachable();
6748       }
6749       break;
6750
6751     case elfcpp::R_POWERPC_GOT_TLSLD16:
6752     case elfcpp::R_POWERPC_GOT_TLSLD16_LO:
6753     case elfcpp::R_POWERPC_GOT_TLSLD16_HI:
6754     case elfcpp::R_POWERPC_GOT_TLSLD16_HA:
6755       {
6756         const tls::Tls_optimization tls_type = target->optimize_tls_ld();
6757         if (tls_type == tls::TLSOPT_NONE)
6758           target->tlsld_got_offset(symtab, layout, object);
6759         else if (tls_type == tls::TLSOPT_TO_LE)
6760           {
6761             // no GOT relocs needed for Local Exec.
6762             if (parameters->options().emit_relocs())
6763               {
6764                 Output_section* os = layout->tls_segment()->first_section();
6765                 gold_assert(os != NULL);
6766                 os->set_needs_symtab_index();
6767               }
6768           }
6769         else
6770           gold_unreachable();
6771       }
6772       break;
6773
6774     case elfcpp::R_POWERPC_GOT_DTPREL16:
6775     case elfcpp::R_POWERPC_GOT_DTPREL16_LO:
6776     case elfcpp::R_POWERPC_GOT_DTPREL16_HI:
6777     case elfcpp::R_POWERPC_GOT_DTPREL16_HA:
6778       {
6779         Output_data_got_powerpc<size, big_endian>* got
6780           = target->got_section(symtab, layout);
6781         if (!gsym->final_value_is_known()
6782             && (gsym->is_from_dynobj()
6783                 || gsym->is_undefined()
6784                 || gsym->is_preemptible()))
6785           got->add_global_with_rel(gsym, GOT_TYPE_DTPREL,
6786                                    target->rela_dyn_section(layout),
6787                                    elfcpp::R_POWERPC_DTPREL);
6788         else
6789           got->add_global_tls(gsym, GOT_TYPE_DTPREL);
6790       }
6791       break;
6792
6793     case elfcpp::R_POWERPC_GOT_TPREL16:
6794     case elfcpp::R_POWERPC_GOT_TPREL16_LO:
6795     case elfcpp::R_POWERPC_GOT_TPREL16_HI:
6796     case elfcpp::R_POWERPC_GOT_TPREL16_HA:
6797       {
6798         const bool final = gsym->final_value_is_known();
6799         const tls::Tls_optimization tls_type = target->optimize_tls_ie(final);
6800         if (tls_type == tls::TLSOPT_NONE)
6801           {
6802             if (!gsym->has_got_offset(GOT_TYPE_TPREL))
6803               {
6804                 Output_data_got_powerpc<size, big_endian>* got
6805                   = target->got_section(symtab, layout);
6806                 Reloc_section* rela_dyn = target->rela_dyn_section(layout);
6807                 if (gsym->is_undefined()
6808                     || gsym->is_from_dynobj())
6809                   {
6810                     got->add_global_with_rel(gsym, GOT_TYPE_TPREL, rela_dyn,
6811                                              elfcpp::R_POWERPC_TPREL);
6812                   }
6813                 else
6814                   {
6815                     unsigned int off = got->add_constant(0);
6816                     gsym->set_got_offset(GOT_TYPE_TPREL, off);
6817                     unsigned int dynrel = elfcpp::R_POWERPC_TPREL;
6818                     rela_dyn->add_symbolless_global_addend(gsym, dynrel,
6819                                                            got, off, 0);
6820                   }
6821               }
6822           }
6823         else if (tls_type == tls::TLSOPT_TO_LE)
6824           {
6825             // no GOT relocs needed for Local Exec.
6826           }
6827         else
6828           gold_unreachable();
6829       }
6830       break;
6831
6832     default:
6833       unsupported_reloc_global(object, r_type, gsym);
6834       break;
6835     }
6836
6837   if (size == 64
6838       && parameters->options().toc_optimize())
6839     {
6840       if (data_shndx == ppc_object->toc_shndx())
6841         {
6842           bool ok = true;
6843           if (r_type != elfcpp::R_PPC64_ADDR64
6844               || (is_ifunc && target->abiversion() < 2))
6845             ok = false;
6846           else if (parameters->options().output_is_position_independent()
6847                    && (is_ifunc || gsym->is_absolute() || gsym->is_undefined()))
6848             ok = false;
6849           if (!ok)
6850             ppc_object->set_no_toc_opt(reloc.get_r_offset());
6851         }
6852
6853       enum {no_check, check_lo, check_ha} insn_check;
6854       switch (r_type)
6855         {
6856         default:
6857           insn_check = no_check;
6858           break;
6859
6860         case elfcpp::R_POWERPC_GOT_TLSLD16_HA:
6861         case elfcpp::R_POWERPC_GOT_TLSGD16_HA:
6862         case elfcpp::R_POWERPC_GOT_TPREL16_HA:
6863         case elfcpp::R_POWERPC_GOT_DTPREL16_HA:
6864         case elfcpp::R_POWERPC_GOT16_HA:
6865         case elfcpp::R_PPC64_TOC16_HA:
6866           insn_check = check_ha;
6867           break;
6868
6869         case elfcpp::R_POWERPC_GOT_TLSLD16_LO:
6870         case elfcpp::R_POWERPC_GOT_TLSGD16_LO:
6871         case elfcpp::R_POWERPC_GOT_TPREL16_LO:
6872         case elfcpp::R_POWERPC_GOT_DTPREL16_LO:
6873         case elfcpp::R_POWERPC_GOT16_LO:
6874         case elfcpp::R_PPC64_GOT16_LO_DS:
6875         case elfcpp::R_PPC64_TOC16_LO:
6876         case elfcpp::R_PPC64_TOC16_LO_DS:
6877           insn_check = check_lo;
6878           break;
6879         }
6880
6881       section_size_type slen;
6882       const unsigned char* view = NULL;
6883       if (insn_check != no_check)
6884         {
6885           view = ppc_object->section_contents(data_shndx, &slen, false);
6886           section_size_type off =
6887             convert_to_section_size_type(reloc.get_r_offset()) & -4;
6888           if (off < slen)
6889             {
6890               uint32_t insn = elfcpp::Swap<32, big_endian>::readval(view + off);
6891               if (insn_check == check_lo
6892                   ? !ok_lo_toc_insn(insn, r_type)
6893                   : ((insn & ((0x3f << 26) | 0x1f << 16))
6894                      != ((15u << 26) | (2 << 16)) /* addis rt,2,imm */))
6895                 {
6896                   ppc_object->set_no_toc_opt();
6897                   gold_warning(_("%s: toc optimization is not supported "
6898                                  "for %#08x instruction"),
6899                                ppc_object->name().c_str(), insn);
6900                 }
6901             }
6902         }
6903
6904       switch (r_type)
6905         {
6906         default:
6907           break;
6908         case elfcpp::R_PPC64_TOC16:
6909         case elfcpp::R_PPC64_TOC16_LO:
6910         case elfcpp::R_PPC64_TOC16_HI:
6911         case elfcpp::R_PPC64_TOC16_HA:
6912         case elfcpp::R_PPC64_TOC16_DS:
6913         case elfcpp::R_PPC64_TOC16_LO_DS:
6914           if (gsym->source() == Symbol::FROM_OBJECT
6915               && !gsym->object()->is_dynamic())
6916             {
6917               Powerpc_relobj<size, big_endian>* sym_object
6918                 = static_cast<Powerpc_relobj<size, big_endian>*>(gsym->object());
6919               bool is_ordinary;
6920               unsigned int shndx = gsym->shndx(&is_ordinary);
6921               if (shndx == sym_object->toc_shndx())
6922                 {
6923                   Sized_symbol<size>* sym = symtab->get_sized_symbol<size>(gsym);
6924                   Address dst_off = sym->value() + reloc.get_r_offset();
6925                   if (dst_off < sym_object->section_size(shndx))
6926                     {
6927                       bool ok = false;
6928                       if (r_type == elfcpp::R_PPC64_TOC16_HA)
6929                         ok = true;
6930                       else if (r_type == elfcpp::R_PPC64_TOC16_LO_DS)
6931                         {
6932                           // Need to check that the insn is a ld
6933                           if (!view)
6934                             view = ppc_object->section_contents(data_shndx,
6935                                                                 &slen,
6936                                                                 false);
6937                           section_size_type off =
6938                             (convert_to_section_size_type(reloc.get_r_offset())
6939                              + (big_endian ? -2 : 3));
6940                           if (off < slen
6941                               && (view[off] & (0x3f << 2)) == (58u << 2))
6942                             ok = true;
6943                         }
6944                       if (!ok)
6945                         sym_object->set_no_toc_opt(dst_off);
6946                     }
6947                 }
6948             }
6949           break;
6950         }
6951     }
6952
6953   if (size == 32)
6954     {
6955       switch (r_type)
6956         {
6957         case elfcpp::R_PPC_LOCAL24PC:
6958           if (strcmp(gsym->name(), "_GLOBAL_OFFSET_TABLE_") == 0)
6959             gold_error(_("%s: unsupported -mbss-plt code"),
6960                        ppc_object->name().c_str());
6961           break;
6962         default:
6963           break;
6964         }
6965     }
6966
6967   switch (r_type)
6968     {
6969     case elfcpp::R_POWERPC_GOT_TLSLD16:
6970     case elfcpp::R_POWERPC_GOT_TLSGD16:
6971     case elfcpp::R_POWERPC_GOT_TPREL16:
6972     case elfcpp::R_POWERPC_GOT_DTPREL16:
6973     case elfcpp::R_POWERPC_GOT16:
6974     case elfcpp::R_PPC64_GOT16_DS:
6975     case elfcpp::R_PPC64_TOC16:
6976     case elfcpp::R_PPC64_TOC16_DS:
6977       ppc_object->set_has_small_toc_reloc();
6978     default:
6979       break;
6980     }
6981 }
6982
6983 // Process relocations for gc.
6984
6985 template<int size, bool big_endian>
6986 void
6987 Target_powerpc<size, big_endian>::gc_process_relocs(
6988     Symbol_table* symtab,
6989     Layout* layout,
6990     Sized_relobj_file<size, big_endian>* object,
6991     unsigned int data_shndx,
6992     unsigned int,
6993     const unsigned char* prelocs,
6994     size_t reloc_count,
6995     Output_section* output_section,
6996     bool needs_special_offset_handling,
6997     size_t local_symbol_count,
6998     const unsigned char* plocal_symbols)
6999 {
7000   typedef Target_powerpc<size, big_endian> Powerpc;
7001   typedef gold::Default_classify_reloc<elfcpp::SHT_RELA, size, big_endian>
7002       Classify_reloc;
7003
7004   Powerpc_relobj<size, big_endian>* ppc_object
7005     = static_cast<Powerpc_relobj<size, big_endian>*>(object);
7006   if (size == 64)
7007     ppc_object->set_opd_valid();
7008   if (size == 64 && data_shndx == ppc_object->opd_shndx())
7009     {
7010       typename Powerpc_relobj<size, big_endian>::Access_from::iterator p;
7011       for (p = ppc_object->access_from_map()->begin();
7012            p != ppc_object->access_from_map()->end();
7013            ++p)
7014         {
7015           Address dst_off = p->first;
7016           unsigned int dst_indx = ppc_object->get_opd_ent(dst_off);
7017           typename Powerpc_relobj<size, big_endian>::Section_refs::iterator s;
7018           for (s = p->second.begin(); s != p->second.end(); ++s)
7019             {
7020               Relobj* src_obj = s->first;
7021               unsigned int src_indx = s->second;
7022               symtab->gc()->add_reference(src_obj, src_indx,
7023                                           ppc_object, dst_indx);
7024             }
7025           p->second.clear();
7026         }
7027       ppc_object->access_from_map()->clear();
7028       ppc_object->process_gc_mark(symtab);
7029       // Don't look at .opd relocs as .opd will reference everything.
7030       return;
7031     }
7032
7033   gold::gc_process_relocs<size, big_endian, Powerpc, Scan, Classify_reloc>(
7034     symtab,
7035     layout,
7036     this,
7037     object,
7038     data_shndx,
7039     prelocs,
7040     reloc_count,
7041     output_section,
7042     needs_special_offset_handling,
7043     local_symbol_count,
7044     plocal_symbols);
7045 }
7046
7047 // Handle target specific gc actions when adding a gc reference from
7048 // SRC_OBJ, SRC_SHNDX to a location specified by DST_OBJ, DST_SHNDX
7049 // and DST_OFF.  For powerpc64, this adds a referenc to the code
7050 // section of a function descriptor.
7051
7052 template<int size, bool big_endian>
7053 void
7054 Target_powerpc<size, big_endian>::do_gc_add_reference(
7055     Symbol_table* symtab,
7056     Relobj* src_obj,
7057     unsigned int src_shndx,
7058     Relobj* dst_obj,
7059     unsigned int dst_shndx,
7060     Address dst_off) const
7061 {
7062   if (size != 64 || dst_obj->is_dynamic())
7063     return;
7064
7065   Powerpc_relobj<size, big_endian>* ppc_object
7066     = static_cast<Powerpc_relobj<size, big_endian>*>(dst_obj);
7067   if (dst_shndx != 0 && dst_shndx == ppc_object->opd_shndx())
7068     {
7069       if (ppc_object->opd_valid())
7070         {
7071           dst_shndx = ppc_object->get_opd_ent(dst_off);
7072           symtab->gc()->add_reference(src_obj, src_shndx, dst_obj, dst_shndx);
7073         }
7074       else
7075         {
7076           // If we haven't run scan_opd_relocs, we must delay
7077           // processing this function descriptor reference.
7078           ppc_object->add_reference(src_obj, src_shndx, dst_off);
7079         }
7080     }
7081 }
7082
7083 // Add any special sections for this symbol to the gc work list.
7084 // For powerpc64, this adds the code section of a function
7085 // descriptor.
7086
7087 template<int size, bool big_endian>
7088 void
7089 Target_powerpc<size, big_endian>::do_gc_mark_symbol(
7090     Symbol_table* symtab,
7091     Symbol* sym) const
7092 {
7093   if (size == 64)
7094     {
7095       Powerpc_relobj<size, big_endian>* ppc_object
7096         = static_cast<Powerpc_relobj<size, big_endian>*>(sym->object());
7097       bool is_ordinary;
7098       unsigned int shndx = sym->shndx(&is_ordinary);
7099       if (is_ordinary && shndx != 0 && shndx == ppc_object->opd_shndx())
7100         {
7101           Sized_symbol<size>* gsym = symtab->get_sized_symbol<size>(sym);
7102           Address dst_off = gsym->value();
7103           if (ppc_object->opd_valid())
7104             {
7105               unsigned int dst_indx = ppc_object->get_opd_ent(dst_off);
7106               symtab->gc()->worklist().push_back(Section_id(ppc_object,
7107                                                             dst_indx));
7108             }
7109           else
7110             ppc_object->add_gc_mark(dst_off);
7111         }
7112     }
7113 }
7114
7115 // For a symbol location in .opd, set LOC to the location of the
7116 // function entry.
7117
7118 template<int size, bool big_endian>
7119 void
7120 Target_powerpc<size, big_endian>::do_function_location(
7121     Symbol_location* loc) const
7122 {
7123   if (size == 64 && loc->shndx != 0)
7124     {
7125       if (loc->object->is_dynamic())
7126         {
7127           Powerpc_dynobj<size, big_endian>* ppc_object
7128             = static_cast<Powerpc_dynobj<size, big_endian>*>(loc->object);
7129           if (loc->shndx == ppc_object->opd_shndx())
7130             {
7131               Address dest_off;
7132               Address off = loc->offset - ppc_object->opd_address();
7133               loc->shndx = ppc_object->get_opd_ent(off, &dest_off);
7134               loc->offset = dest_off;
7135             }
7136         }
7137       else
7138         {
7139           const Powerpc_relobj<size, big_endian>* ppc_object
7140             = static_cast<const Powerpc_relobj<size, big_endian>*>(loc->object);
7141           if (loc->shndx == ppc_object->opd_shndx())
7142             {
7143               Address dest_off;
7144               loc->shndx = ppc_object->get_opd_ent(loc->offset, &dest_off);
7145               loc->offset = dest_off;
7146             }
7147         }
7148     }
7149 }
7150
7151 // FNOFFSET in section SHNDX in OBJECT is the start of a function
7152 // compiled with -fsplit-stack.  The function calls non-split-stack
7153 // code.  Change the function to ensure it has enough stack space to
7154 // call some random function.
7155
7156 template<int size, bool big_endian>
7157 void
7158 Target_powerpc<size, big_endian>::do_calls_non_split(
7159     Relobj* object,
7160     unsigned int shndx,
7161     section_offset_type fnoffset,
7162     section_size_type fnsize,
7163     const unsigned char* prelocs,
7164     size_t reloc_count,
7165     unsigned char* view,
7166     section_size_type view_size,
7167     std::string* from,
7168     std::string* to) const
7169 {
7170   // 32-bit not supported.
7171   if (size == 32)
7172     {
7173       // warn
7174       Target::do_calls_non_split(object, shndx, fnoffset, fnsize,
7175                                  prelocs, reloc_count, view, view_size,
7176                                  from, to);
7177       return;
7178     }
7179
7180   // The function always starts with
7181   //    ld %r0,-0x7000-64(%r13)  # tcbhead_t.__private_ss
7182   //    addis %r12,%r1,-allocate@ha
7183   //    addi %r12,%r12,-allocate@l
7184   //    cmpld %r12,%r0
7185   // but note that the addis or addi may be replaced with a nop
7186
7187   unsigned char *entry = view + fnoffset;
7188   uint32_t insn = elfcpp::Swap<32, big_endian>::readval(entry);
7189
7190   if ((insn & 0xffff0000) == addis_2_12)
7191     {
7192       /* Skip ELFv2 global entry code.  */
7193       entry += 8;
7194       insn = elfcpp::Swap<32, big_endian>::readval(entry);
7195     }
7196
7197   unsigned char *pinsn = entry;
7198   bool ok = false;
7199   const uint32_t ld_private_ss = 0xe80d8fc0;
7200   if (insn == ld_private_ss)
7201     {
7202       int32_t allocate = 0;
7203       while (1)
7204         {
7205           pinsn += 4;
7206           insn = elfcpp::Swap<32, big_endian>::readval(pinsn);
7207           if ((insn & 0xffff0000) == addis_12_1)
7208             allocate += (insn & 0xffff) << 16;
7209           else if ((insn & 0xffff0000) == addi_12_1
7210                    || (insn & 0xffff0000) == addi_12_12)
7211             allocate += ((insn & 0xffff) ^ 0x8000) - 0x8000;
7212           else if (insn != nop)
7213             break;
7214         }
7215       if (insn == cmpld_7_12_0 && pinsn == entry + 12)
7216         {
7217           int extra = parameters->options().split_stack_adjust_size();
7218           allocate -= extra;
7219           if (allocate >= 0 || extra < 0)
7220             {
7221               object->error(_("split-stack stack size overflow at "
7222                               "section %u offset %0zx"),
7223                             shndx, static_cast<size_t>(fnoffset));
7224               return;
7225             }
7226           pinsn = entry + 4;
7227           insn = addis_12_1 | (((allocate + 0x8000) >> 16) & 0xffff);
7228           if (insn != addis_12_1)
7229             {
7230               elfcpp::Swap<32, big_endian>::writeval(pinsn, insn);
7231               pinsn += 4;
7232               insn = addi_12_12 | (allocate & 0xffff);
7233               if (insn != addi_12_12)
7234                 {
7235                   elfcpp::Swap<32, big_endian>::writeval(pinsn, insn);
7236                   pinsn += 4;
7237                 }
7238             }
7239           else
7240             {
7241               insn = addi_12_1 | (allocate & 0xffff);
7242               elfcpp::Swap<32, big_endian>::writeval(pinsn, insn);
7243               pinsn += 4;
7244             }
7245           if (pinsn != entry + 12)
7246             elfcpp::Swap<32, big_endian>::writeval(pinsn, nop);
7247
7248           ok = true;
7249         }
7250     }
7251
7252   if (!ok)
7253     {
7254       if (!object->has_no_split_stack())
7255         object->error(_("failed to match split-stack sequence at "
7256                         "section %u offset %0zx"),
7257                       shndx, static_cast<size_t>(fnoffset));
7258     }
7259 }
7260
7261 // Scan relocations for a section.
7262
7263 template<int size, bool big_endian>
7264 void
7265 Target_powerpc<size, big_endian>::scan_relocs(
7266     Symbol_table* symtab,
7267     Layout* layout,
7268     Sized_relobj_file<size, big_endian>* object,
7269     unsigned int data_shndx,
7270     unsigned int sh_type,
7271     const unsigned char* prelocs,
7272     size_t reloc_count,
7273     Output_section* output_section,
7274     bool needs_special_offset_handling,
7275     size_t local_symbol_count,
7276     const unsigned char* plocal_symbols)
7277 {
7278   typedef Target_powerpc<size, big_endian> Powerpc;
7279   typedef gold::Default_classify_reloc<elfcpp::SHT_RELA, size, big_endian>
7280       Classify_reloc;
7281
7282   if (sh_type == elfcpp::SHT_REL)
7283     {
7284       gold_error(_("%s: unsupported REL reloc section"),
7285                  object->name().c_str());
7286       return;
7287     }
7288
7289   gold::scan_relocs<size, big_endian, Powerpc, Scan, Classify_reloc>(
7290     symtab,
7291     layout,
7292     this,
7293     object,
7294     data_shndx,
7295     prelocs,
7296     reloc_count,
7297     output_section,
7298     needs_special_offset_handling,
7299     local_symbol_count,
7300     plocal_symbols);
7301 }
7302
7303 // Functor class for processing the global symbol table.
7304 // Removes symbols defined on discarded opd entries.
7305
7306 template<bool big_endian>
7307 class Global_symbol_visitor_opd
7308 {
7309  public:
7310   Global_symbol_visitor_opd()
7311   { }
7312
7313   void
7314   operator()(Sized_symbol<64>* sym)
7315   {
7316     if (sym->has_symtab_index()
7317         || sym->source() != Symbol::FROM_OBJECT
7318         || !sym->in_real_elf())
7319       return;
7320
7321     if (sym->object()->is_dynamic())
7322       return;
7323
7324     Powerpc_relobj<64, big_endian>* symobj
7325       = static_cast<Powerpc_relobj<64, big_endian>*>(sym->object());
7326     if (symobj->opd_shndx() == 0)
7327       return;
7328
7329     bool is_ordinary;
7330     unsigned int shndx = sym->shndx(&is_ordinary);
7331     if (shndx == symobj->opd_shndx()
7332         && symobj->get_opd_discard(sym->value()))
7333       {
7334         sym->set_undefined();
7335         sym->set_visibility(elfcpp::STV_DEFAULT);
7336         sym->set_is_defined_in_discarded_section();
7337         sym->set_symtab_index(-1U);
7338       }
7339   }
7340 };
7341
7342 template<int size, bool big_endian>
7343 void
7344 Target_powerpc<size, big_endian>::define_save_restore_funcs(
7345     Layout* layout,
7346     Symbol_table* symtab)
7347 {
7348   if (size == 64)
7349     {
7350       Output_data_save_res<size, big_endian>* savres
7351         = new Output_data_save_res<size, big_endian>(symtab);
7352       this->savres_section_ = savres;
7353       layout->add_output_section_data(".text", elfcpp::SHT_PROGBITS,
7354                                       elfcpp::SHF_ALLOC | elfcpp::SHF_EXECINSTR,
7355                                       savres, ORDER_TEXT, false);
7356     }
7357 }
7358
7359 // Sort linker created .got section first (for the header), then input
7360 // sections belonging to files using small model code.
7361
7362 template<bool big_endian>
7363 class Sort_toc_sections
7364 {
7365  public:
7366   bool
7367   operator()(const Output_section::Input_section& is1,
7368              const Output_section::Input_section& is2) const
7369   {
7370     if (!is1.is_input_section() && is2.is_input_section())
7371       return true;
7372     bool small1
7373       = (is1.is_input_section()
7374          && (static_cast<const Powerpc_relobj<64, big_endian>*>(is1.relobj())
7375              ->has_small_toc_reloc()));
7376     bool small2
7377       = (is2.is_input_section()
7378          && (static_cast<const Powerpc_relobj<64, big_endian>*>(is2.relobj())
7379              ->has_small_toc_reloc()));
7380     return small1 && !small2;
7381   }
7382 };
7383
7384 // Finalize the sections.
7385
7386 template<int size, bool big_endian>
7387 void
7388 Target_powerpc<size, big_endian>::do_finalize_sections(
7389     Layout* layout,
7390     const Input_objects*,
7391     Symbol_table* symtab)
7392 {
7393   if (parameters->doing_static_link())
7394     {
7395       // At least some versions of glibc elf-init.o have a strong
7396       // reference to __rela_iplt marker syms.  A weak ref would be
7397       // better..
7398       if (this->iplt_ != NULL)
7399         {
7400           Reloc_section* rel = this->iplt_->rel_plt();
7401           symtab->define_in_output_data("__rela_iplt_start", NULL,
7402                                         Symbol_table::PREDEFINED, rel, 0, 0,
7403                                         elfcpp::STT_NOTYPE, elfcpp::STB_GLOBAL,
7404                                         elfcpp::STV_HIDDEN, 0, false, true);
7405           symtab->define_in_output_data("__rela_iplt_end", NULL,
7406                                         Symbol_table::PREDEFINED, rel, 0, 0,
7407                                         elfcpp::STT_NOTYPE, elfcpp::STB_GLOBAL,
7408                                         elfcpp::STV_HIDDEN, 0, true, true);
7409         }
7410       else
7411         {
7412           symtab->define_as_constant("__rela_iplt_start", NULL,
7413                                      Symbol_table::PREDEFINED, 0, 0,
7414                                      elfcpp::STT_NOTYPE, elfcpp::STB_GLOBAL,
7415                                      elfcpp::STV_HIDDEN, 0, true, false);
7416           symtab->define_as_constant("__rela_iplt_end", NULL,
7417                                      Symbol_table::PREDEFINED, 0, 0,
7418                                      elfcpp::STT_NOTYPE, elfcpp::STB_GLOBAL,
7419                                      elfcpp::STV_HIDDEN, 0, true, false);
7420         }
7421     }
7422
7423   if (size == 64)
7424     {
7425       typedef Global_symbol_visitor_opd<big_endian> Symbol_visitor;
7426       symtab->for_all_symbols<64, Symbol_visitor>(Symbol_visitor());
7427
7428       if (!parameters->options().relocatable())
7429         {
7430           this->define_save_restore_funcs(layout, symtab);
7431
7432           // Annoyingly, we need to make these sections now whether or
7433           // not we need them.  If we delay until do_relax then we
7434           // need to mess with the relaxation machinery checkpointing.
7435           this->got_section(symtab, layout);
7436           this->make_brlt_section(layout);
7437
7438           if (parameters->options().toc_sort())
7439             {
7440               Output_section* os = this->got_->output_section();
7441               if (os != NULL && os->input_sections().size() > 1)
7442                 std::stable_sort(os->input_sections().begin(),
7443                                  os->input_sections().end(),
7444                                  Sort_toc_sections<big_endian>());
7445             }
7446         }
7447     }
7448
7449   // Fill in some more dynamic tags.
7450   Output_data_dynamic* odyn = layout->dynamic_data();
7451   if (odyn != NULL)
7452     {
7453       const Reloc_section* rel_plt = (this->plt_ == NULL
7454                                       ? NULL
7455                                       : this->plt_->rel_plt());
7456       layout->add_target_dynamic_tags(false, this->plt_, rel_plt,
7457                                       this->rela_dyn_, true, size == 32);
7458
7459       if (size == 32)
7460         {
7461           if (this->got_ != NULL)
7462             {
7463               this->got_->finalize_data_size();
7464               odyn->add_section_plus_offset(elfcpp::DT_PPC_GOT,
7465                                             this->got_, this->got_->g_o_t());
7466             }
7467         }
7468       else
7469         {
7470           if (this->glink_ != NULL)
7471             {
7472               this->glink_->finalize_data_size();
7473               odyn->add_section_plus_offset(elfcpp::DT_PPC64_GLINK,
7474                                             this->glink_,
7475                                             (this->glink_->pltresolve_size
7476                                              - 32));
7477             }
7478         }
7479     }
7480
7481   // Emit any relocs we saved in an attempt to avoid generating COPY
7482   // relocs.
7483   if (this->copy_relocs_.any_saved_relocs())
7484     this->copy_relocs_.emit(this->rela_dyn_section(layout));
7485 }
7486
7487 // Emit any saved relocs, and mark toc entries using any of these
7488 // relocs as not optimizable.
7489
7490 template<int sh_type, int size, bool big_endian>
7491 void
7492 Powerpc_copy_relocs<sh_type, size, big_endian>::emit(
7493     Output_data_reloc<sh_type, true, size, big_endian>* reloc_section)
7494 {
7495   if (size == 64
7496       && parameters->options().toc_optimize())
7497     {
7498       for (typename Copy_relocs<sh_type, size, big_endian>::
7499              Copy_reloc_entries::iterator p = this->entries_.begin();
7500            p != this->entries_.end();
7501            ++p)
7502         {
7503           typename Copy_relocs<sh_type, size, big_endian>::Copy_reloc_entry&
7504             entry = *p;
7505
7506           // If the symbol is no longer defined in a dynamic object,
7507           // then we emitted a COPY relocation.  If it is still
7508           // dynamic then we'll need dynamic relocations and thus
7509           // can't optimize toc entries.
7510           if (entry.sym_->is_from_dynobj())
7511             {
7512               Powerpc_relobj<size, big_endian>* ppc_object
7513                 = static_cast<Powerpc_relobj<size, big_endian>*>(entry.relobj_);
7514               if (entry.shndx_ == ppc_object->toc_shndx())
7515                 ppc_object->set_no_toc_opt(entry.address_);
7516             }
7517         }
7518     }
7519
7520   Copy_relocs<sh_type, size, big_endian>::emit(reloc_section);
7521 }
7522
7523 // Return the value to use for a branch relocation.
7524
7525 template<int size, bool big_endian>
7526 bool
7527 Target_powerpc<size, big_endian>::symval_for_branch(
7528     const Symbol_table* symtab,
7529     const Sized_symbol<size>* gsym,
7530     Powerpc_relobj<size, big_endian>* object,
7531     Address *value,
7532     unsigned int *dest_shndx)
7533 {
7534   if (size == 32 || this->abiversion() >= 2)
7535     gold_unreachable();
7536   *dest_shndx = 0;
7537
7538   // If the symbol is defined in an opd section, ie. is a function
7539   // descriptor, use the function descriptor code entry address
7540   Powerpc_relobj<size, big_endian>* symobj = object;
7541   if (gsym != NULL
7542       && (gsym->source() != Symbol::FROM_OBJECT
7543           || gsym->object()->is_dynamic()))
7544     return true;
7545   if (gsym != NULL)
7546     symobj = static_cast<Powerpc_relobj<size, big_endian>*>(gsym->object());
7547   unsigned int shndx = symobj->opd_shndx();
7548   if (shndx == 0)
7549     return true;
7550   Address opd_addr = symobj->get_output_section_offset(shndx);
7551   if (opd_addr == invalid_address)
7552     return true;
7553   opd_addr += symobj->output_section_address(shndx);
7554   if (*value >= opd_addr && *value < opd_addr + symobj->section_size(shndx))
7555     {
7556       Address sec_off;
7557       *dest_shndx = symobj->get_opd_ent(*value - opd_addr, &sec_off);
7558       if (symtab->is_section_folded(symobj, *dest_shndx))
7559         {
7560           Section_id folded
7561             = symtab->icf()->get_folded_section(symobj, *dest_shndx);
7562           symobj = static_cast<Powerpc_relobj<size, big_endian>*>(folded.first);
7563           *dest_shndx = folded.second;
7564         }
7565       Address sec_addr = symobj->get_output_section_offset(*dest_shndx);
7566       if (sec_addr == invalid_address)
7567         return false;
7568
7569       sec_addr += symobj->output_section(*dest_shndx)->address();
7570       *value = sec_addr + sec_off;
7571     }
7572   return true;
7573 }
7574
7575 // Perform a relocation.
7576
7577 template<int size, bool big_endian>
7578 inline bool
7579 Target_powerpc<size, big_endian>::Relocate::relocate(
7580     const Relocate_info<size, big_endian>* relinfo,
7581     unsigned int,
7582     Target_powerpc* target,
7583     Output_section* os,
7584     size_t relnum,
7585     const unsigned char* preloc,
7586     const Sized_symbol<size>* gsym,
7587     const Symbol_value<size>* psymval,
7588     unsigned char* view,
7589     Address address,
7590     section_size_type view_size)
7591 {
7592   if (view == NULL)
7593     return true;
7594
7595   const elfcpp::Rela<size, big_endian> rela(preloc);
7596   unsigned int r_type = elfcpp::elf_r_type<size>(rela.get_r_info());
7597   switch (this->maybe_skip_tls_get_addr_call(r_type, gsym))
7598     {
7599     case Track_tls::NOT_EXPECTED:
7600       gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
7601                              _("__tls_get_addr call lacks marker reloc"));
7602       break;
7603     case Track_tls::EXPECTED:
7604       // We have already complained.
7605       break;
7606     case Track_tls::SKIP:
7607       return true;
7608     case Track_tls::NORMAL:
7609       break;
7610     }
7611
7612   typedef Powerpc_relocate_functions<size, big_endian> Reloc;
7613   typedef typename elfcpp::Swap<32, big_endian>::Valtype Insn;
7614   typedef typename elfcpp::Rela<size, big_endian> Reltype;
7615   // Offset from start of insn to d-field reloc.
7616   const int d_offset = big_endian ? 2 : 0;
7617
7618   Powerpc_relobj<size, big_endian>* const object
7619     = static_cast<Powerpc_relobj<size, big_endian>*>(relinfo->object);
7620   Address value = 0;
7621   bool has_stub_value = false;
7622   unsigned int r_sym = elfcpp::elf_r_sym<size>(rela.get_r_info());
7623   if ((gsym != NULL
7624        ? gsym->use_plt_offset(Scan::get_reference_flags(r_type, target))
7625        : object->local_has_plt_offset(r_sym))
7626       && (!psymval->is_ifunc_symbol()
7627           || Scan::reloc_needs_plt_for_ifunc(target, object, r_type, false)))
7628     {
7629       if (size == 64
7630           && gsym != NULL
7631           && target->abiversion() >= 2
7632           && !parameters->options().output_is_position_independent()
7633           && !is_branch_reloc(r_type))
7634         {
7635           Address off = target->glink_section()->find_global_entry(gsym);
7636           if (off != invalid_address)
7637             {
7638               value = target->glink_section()->global_entry_address() + off;
7639               has_stub_value = true;
7640             }
7641         }
7642       else
7643         {
7644           Stub_table<size, big_endian>* stub_table
7645             = object->stub_table(relinfo->data_shndx);
7646           if (stub_table == NULL)
7647             {
7648               // This is a ref from a data section to an ifunc symbol.
7649               if (target->stub_tables().size() != 0)
7650                 stub_table = target->stub_tables()[0];
7651             }
7652           if (stub_table != NULL)
7653             {
7654               Address off;
7655               if (gsym != NULL)
7656                 off = stub_table->find_plt_call_entry(object, gsym, r_type,
7657                                                       rela.get_r_addend());
7658               else
7659                 off = stub_table->find_plt_call_entry(object, r_sym, r_type,
7660                                                       rela.get_r_addend());
7661               if (off != invalid_address)
7662                 {
7663                   value = stub_table->stub_address() + off;
7664                   has_stub_value = true;
7665                 }
7666             }
7667         }
7668       // We don't care too much about bogus debug references to
7669       // non-local functions, but otherwise there had better be a plt
7670       // call stub or global entry stub as appropriate.
7671       gold_assert(has_stub_value || !(os->flags() & elfcpp::SHF_ALLOC));
7672     }
7673
7674   if (r_type == elfcpp::R_POWERPC_GOT16
7675       || r_type == elfcpp::R_POWERPC_GOT16_LO
7676       || r_type == elfcpp::R_POWERPC_GOT16_HI
7677       || r_type == elfcpp::R_POWERPC_GOT16_HA
7678       || r_type == elfcpp::R_PPC64_GOT16_DS
7679       || r_type == elfcpp::R_PPC64_GOT16_LO_DS)
7680     {
7681       if (gsym != NULL)
7682         {
7683           gold_assert(gsym->has_got_offset(GOT_TYPE_STANDARD));
7684           value = gsym->got_offset(GOT_TYPE_STANDARD);
7685         }
7686       else
7687         {
7688           gold_assert(object->local_has_got_offset(r_sym, GOT_TYPE_STANDARD));
7689           value = object->local_got_offset(r_sym, GOT_TYPE_STANDARD);
7690         }
7691       value -= target->got_section()->got_base_offset(object);
7692     }
7693   else if (r_type == elfcpp::R_PPC64_TOC)
7694     {
7695       value = (target->got_section()->output_section()->address()
7696                + object->toc_base_offset());
7697     }
7698   else if (gsym != NULL
7699            && (r_type == elfcpp::R_POWERPC_REL24
7700                || r_type == elfcpp::R_PPC_PLTREL24)
7701            && has_stub_value)
7702     {
7703       if (size == 64)
7704         {
7705           typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
7706           Valtype* wv = reinterpret_cast<Valtype*>(view);
7707           bool can_plt_call = false;
7708           if (rela.get_r_offset() + 8 <= view_size)
7709             {
7710               Valtype insn = elfcpp::Swap<32, big_endian>::readval(wv);
7711               Valtype insn2 = elfcpp::Swap<32, big_endian>::readval(wv + 1);
7712               if ((insn & 1) != 0
7713                   && (insn2 == nop
7714                       || insn2 == cror_15_15_15 || insn2 == cror_31_31_31))
7715                 {
7716                   elfcpp::Swap<32, big_endian>::
7717                     writeval(wv + 1, ld_2_1 + target->stk_toc());
7718                   can_plt_call = true;
7719                 }
7720             }
7721           if (!can_plt_call)
7722             {
7723               // If we don't have a branch and link followed by a nop,
7724               // we can't go via the plt because there is no place to
7725               // put a toc restoring instruction.
7726               // Unless we know we won't be returning.
7727               if (strcmp(gsym->name(), "__libc_start_main") == 0)
7728                 can_plt_call = true;
7729             }
7730           if (!can_plt_call)
7731             {
7732               // g++ as of 20130507 emits self-calls without a
7733               // following nop.  This is arguably wrong since we have
7734               // conflicting information.  On the one hand a global
7735               // symbol and on the other a local call sequence, but
7736               // don't error for this special case.
7737               // It isn't possible to cheaply verify we have exactly
7738               // such a call.  Allow all calls to the same section.
7739               bool ok = false;
7740               Address code = value;
7741               if (gsym->source() == Symbol::FROM_OBJECT
7742                   && gsym->object() == object)
7743                 {
7744                   unsigned int dest_shndx = 0;
7745                   if (target->abiversion() < 2)
7746                     {
7747                       Address addend = rela.get_r_addend();
7748                       code = psymval->value(object, addend);
7749                       target->symval_for_branch(relinfo->symtab, gsym, object,
7750                                                 &code, &dest_shndx);
7751                     }
7752                   bool is_ordinary;
7753                   if (dest_shndx == 0)
7754                     dest_shndx = gsym->shndx(&is_ordinary);
7755                   ok = dest_shndx == relinfo->data_shndx;
7756                 }
7757               if (!ok)
7758                 {
7759                   gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
7760                                          _("call lacks nop, can't restore toc; "
7761                                            "recompile with -fPIC"));
7762                   value = code;
7763                 }
7764             }
7765         }
7766     }
7767   else if (r_type == elfcpp::R_POWERPC_GOT_TLSGD16
7768            || r_type == elfcpp::R_POWERPC_GOT_TLSGD16_LO
7769            || r_type == elfcpp::R_POWERPC_GOT_TLSGD16_HI
7770            || r_type == elfcpp::R_POWERPC_GOT_TLSGD16_HA)
7771     {
7772       // First instruction of a global dynamic sequence, arg setup insn.
7773       const bool final = gsym == NULL || gsym->final_value_is_known();
7774       const tls::Tls_optimization tls_type = target->optimize_tls_gd(final);
7775       enum Got_type got_type = GOT_TYPE_STANDARD;
7776       if (tls_type == tls::TLSOPT_NONE)
7777         got_type = GOT_TYPE_TLSGD;
7778       else if (tls_type == tls::TLSOPT_TO_IE)
7779         got_type = GOT_TYPE_TPREL;
7780       if (got_type != GOT_TYPE_STANDARD)
7781         {
7782           if (gsym != NULL)
7783             {
7784               gold_assert(gsym->has_got_offset(got_type));
7785               value = gsym->got_offset(got_type);
7786             }
7787           else
7788             {
7789               gold_assert(object->local_has_got_offset(r_sym, got_type));
7790               value = object->local_got_offset(r_sym, got_type);
7791             }
7792           value -= target->got_section()->got_base_offset(object);
7793         }
7794       if (tls_type == tls::TLSOPT_TO_IE)
7795         {
7796           if (r_type == elfcpp::R_POWERPC_GOT_TLSGD16
7797               || r_type == elfcpp::R_POWERPC_GOT_TLSGD16_LO)
7798             {
7799               Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
7800               Insn insn = elfcpp::Swap<32, big_endian>::readval(iview);
7801               insn &= (1 << 26) - (1 << 16); // extract rt,ra from addi
7802               if (size == 32)
7803                 insn |= 32 << 26; // lwz
7804               else
7805                 insn |= 58 << 26; // ld
7806               elfcpp::Swap<32, big_endian>::writeval(iview, insn);
7807             }
7808           r_type += (elfcpp::R_POWERPC_GOT_TPREL16
7809                      - elfcpp::R_POWERPC_GOT_TLSGD16);
7810         }
7811       else if (tls_type == tls::TLSOPT_TO_LE)
7812         {
7813           if (r_type == elfcpp::R_POWERPC_GOT_TLSGD16
7814               || r_type == elfcpp::R_POWERPC_GOT_TLSGD16_LO)
7815             {
7816               Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
7817               Insn insn = elfcpp::Swap<32, big_endian>::readval(iview);
7818               insn &= (1 << 26) - (1 << 21); // extract rt
7819               if (size == 32)
7820                 insn |= addis_0_2;
7821               else
7822                 insn |= addis_0_13;
7823               elfcpp::Swap<32, big_endian>::writeval(iview, insn);
7824               r_type = elfcpp::R_POWERPC_TPREL16_HA;
7825               value = psymval->value(object, rela.get_r_addend());
7826             }
7827           else
7828             {
7829               Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
7830               Insn insn = nop;
7831               elfcpp::Swap<32, big_endian>::writeval(iview, insn);
7832               r_type = elfcpp::R_POWERPC_NONE;
7833             }
7834         }
7835     }
7836   else if (r_type == elfcpp::R_POWERPC_GOT_TLSLD16
7837            || r_type == elfcpp::R_POWERPC_GOT_TLSLD16_LO
7838            || r_type == elfcpp::R_POWERPC_GOT_TLSLD16_HI
7839            || r_type == elfcpp::R_POWERPC_GOT_TLSLD16_HA)
7840     {
7841       // First instruction of a local dynamic sequence, arg setup insn.
7842       const tls::Tls_optimization tls_type = target->optimize_tls_ld();
7843       if (tls_type == tls::TLSOPT_NONE)
7844         {
7845           value = target->tlsld_got_offset();
7846           value -= target->got_section()->got_base_offset(object);
7847         }
7848       else
7849         {
7850           gold_assert(tls_type == tls::TLSOPT_TO_LE);
7851           if (r_type == elfcpp::R_POWERPC_GOT_TLSLD16
7852               || r_type == elfcpp::R_POWERPC_GOT_TLSLD16_LO)
7853             {
7854               Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
7855               Insn insn = elfcpp::Swap<32, big_endian>::readval(iview);
7856               insn &= (1 << 26) - (1 << 21); // extract rt
7857               if (size == 32)
7858                 insn |= addis_0_2;
7859               else
7860                 insn |= addis_0_13;
7861               elfcpp::Swap<32, big_endian>::writeval(iview, insn);
7862               r_type = elfcpp::R_POWERPC_TPREL16_HA;
7863               value = dtp_offset;
7864             }
7865           else
7866             {
7867               Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
7868               Insn insn = nop;
7869               elfcpp::Swap<32, big_endian>::writeval(iview, insn);
7870               r_type = elfcpp::R_POWERPC_NONE;
7871             }
7872         }
7873     }
7874   else if (r_type == elfcpp::R_POWERPC_GOT_DTPREL16
7875            || r_type == elfcpp::R_POWERPC_GOT_DTPREL16_LO
7876            || r_type == elfcpp::R_POWERPC_GOT_DTPREL16_HI
7877            || r_type == elfcpp::R_POWERPC_GOT_DTPREL16_HA)
7878     {
7879       // Accesses relative to a local dynamic sequence address,
7880       // no optimisation here.
7881       if (gsym != NULL)
7882         {
7883           gold_assert(gsym->has_got_offset(GOT_TYPE_DTPREL));
7884           value = gsym->got_offset(GOT_TYPE_DTPREL);
7885         }
7886       else
7887         {
7888           gold_assert(object->local_has_got_offset(r_sym, GOT_TYPE_DTPREL));
7889           value = object->local_got_offset(r_sym, GOT_TYPE_DTPREL);
7890         }
7891       value -= target->got_section()->got_base_offset(object);
7892     }
7893   else if (r_type == elfcpp::R_POWERPC_GOT_TPREL16
7894            || r_type == elfcpp::R_POWERPC_GOT_TPREL16_LO
7895            || r_type == elfcpp::R_POWERPC_GOT_TPREL16_HI
7896            || r_type == elfcpp::R_POWERPC_GOT_TPREL16_HA)
7897     {
7898       // First instruction of initial exec sequence.
7899       const bool final = gsym == NULL || gsym->final_value_is_known();
7900       const tls::Tls_optimization tls_type = target->optimize_tls_ie(final);
7901       if (tls_type == tls::TLSOPT_NONE)
7902         {
7903           if (gsym != NULL)
7904             {
7905               gold_assert(gsym->has_got_offset(GOT_TYPE_TPREL));
7906               value = gsym->got_offset(GOT_TYPE_TPREL);
7907             }
7908           else
7909             {
7910               gold_assert(object->local_has_got_offset(r_sym, GOT_TYPE_TPREL));
7911               value = object->local_got_offset(r_sym, GOT_TYPE_TPREL);
7912             }
7913           value -= target->got_section()->got_base_offset(object);
7914         }
7915       else
7916         {
7917           gold_assert(tls_type == tls::TLSOPT_TO_LE);
7918           if (r_type == elfcpp::R_POWERPC_GOT_TPREL16
7919               || r_type == elfcpp::R_POWERPC_GOT_TPREL16_LO)
7920             {
7921               Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
7922               Insn insn = elfcpp::Swap<32, big_endian>::readval(iview);
7923               insn &= (1 << 26) - (1 << 21); // extract rt from ld
7924               if (size == 32)
7925                 insn |= addis_0_2;
7926               else
7927                 insn |= addis_0_13;
7928               elfcpp::Swap<32, big_endian>::writeval(iview, insn);
7929               r_type = elfcpp::R_POWERPC_TPREL16_HA;
7930               value = psymval->value(object, rela.get_r_addend());
7931             }
7932           else
7933             {
7934               Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
7935               Insn insn = nop;
7936               elfcpp::Swap<32, big_endian>::writeval(iview, insn);
7937               r_type = elfcpp::R_POWERPC_NONE;
7938             }
7939         }
7940     }
7941   else if ((size == 64 && r_type == elfcpp::R_PPC64_TLSGD)
7942            || (size == 32 && r_type == elfcpp::R_PPC_TLSGD))
7943     {
7944       // Second instruction of a global dynamic sequence,
7945       // the __tls_get_addr call
7946       this->expect_tls_get_addr_call(relinfo, relnum, rela.get_r_offset());
7947       const bool final = gsym == NULL || gsym->final_value_is_known();
7948       const tls::Tls_optimization tls_type = target->optimize_tls_gd(final);
7949       if (tls_type != tls::TLSOPT_NONE)
7950         {
7951           if (tls_type == tls::TLSOPT_TO_IE)
7952             {
7953               Insn* iview = reinterpret_cast<Insn*>(view);
7954               Insn insn = add_3_3_13;
7955               if (size == 32)
7956                 insn = add_3_3_2;
7957               elfcpp::Swap<32, big_endian>::writeval(iview, insn);
7958               r_type = elfcpp::R_POWERPC_NONE;
7959             }
7960           else
7961             {
7962               Insn* iview = reinterpret_cast<Insn*>(view);
7963               Insn insn = addi_3_3;
7964               elfcpp::Swap<32, big_endian>::writeval(iview, insn);
7965               r_type = elfcpp::R_POWERPC_TPREL16_LO;
7966               view += d_offset;
7967               value = psymval->value(object, rela.get_r_addend());
7968             }
7969           this->skip_next_tls_get_addr_call();
7970         }
7971     }
7972   else if ((size == 64 && r_type == elfcpp::R_PPC64_TLSLD)
7973            || (size == 32 && r_type == elfcpp::R_PPC_TLSLD))
7974     {
7975       // Second instruction of a local dynamic sequence,
7976       // the __tls_get_addr call
7977       this->expect_tls_get_addr_call(relinfo, relnum, rela.get_r_offset());
7978       const tls::Tls_optimization tls_type = target->optimize_tls_ld();
7979       if (tls_type == tls::TLSOPT_TO_LE)
7980         {
7981           Insn* iview = reinterpret_cast<Insn*>(view);
7982           Insn insn = addi_3_3;
7983           elfcpp::Swap<32, big_endian>::writeval(iview, insn);
7984           this->skip_next_tls_get_addr_call();
7985           r_type = elfcpp::R_POWERPC_TPREL16_LO;
7986           view += d_offset;
7987           value = dtp_offset;
7988         }
7989     }
7990   else if (r_type == elfcpp::R_POWERPC_TLS)
7991     {
7992       // Second instruction of an initial exec sequence
7993       const bool final = gsym == NULL || gsym->final_value_is_known();
7994       const tls::Tls_optimization tls_type = target->optimize_tls_ie(final);
7995       if (tls_type == tls::TLSOPT_TO_LE)
7996         {
7997           Insn* iview = reinterpret_cast<Insn*>(view);
7998           Insn insn = elfcpp::Swap<32, big_endian>::readval(iview);
7999           unsigned int reg = size == 32 ? 2 : 13;
8000           insn = at_tls_transform(insn, reg);
8001           gold_assert(insn != 0);
8002           elfcpp::Swap<32, big_endian>::writeval(iview, insn);
8003           r_type = elfcpp::R_POWERPC_TPREL16_LO;
8004           view += d_offset;
8005           value = psymval->value(object, rela.get_r_addend());
8006         }
8007     }
8008   else if (!has_stub_value)
8009     {
8010       Address addend = 0;
8011       if (!(size == 32 && r_type == elfcpp::R_PPC_PLTREL24))
8012         addend = rela.get_r_addend();
8013       value = psymval->value(object, addend);
8014       if (size == 64 && is_branch_reloc(r_type))
8015         {
8016           if (target->abiversion() >= 2)
8017             {
8018               if (gsym != NULL)
8019                 value += object->ppc64_local_entry_offset(gsym);
8020               else
8021                 value += object->ppc64_local_entry_offset(r_sym);
8022             }
8023           else
8024             {
8025               unsigned int dest_shndx;
8026               target->symval_for_branch(relinfo->symtab, gsym, object,
8027                                         &value, &dest_shndx);
8028             }
8029         }
8030       Address max_branch_offset = max_branch_delta(r_type);
8031       if (max_branch_offset != 0
8032           && value - address + max_branch_offset >= 2 * max_branch_offset)
8033         {
8034           Stub_table<size, big_endian>* stub_table
8035             = object->stub_table(relinfo->data_shndx);
8036           if (stub_table != NULL)
8037             {
8038               Address off = stub_table->find_long_branch_entry(object, value);
8039               if (off != invalid_address)
8040                 {
8041                   value = (stub_table->stub_address() + stub_table->plt_size()
8042                            + off);
8043                   has_stub_value = true;
8044                 }
8045             }
8046         }
8047     }
8048
8049   switch (r_type)
8050     {
8051     case elfcpp::R_PPC64_REL64:
8052     case elfcpp::R_POWERPC_REL32:
8053     case elfcpp::R_POWERPC_REL24:
8054     case elfcpp::R_PPC_PLTREL24:
8055     case elfcpp::R_PPC_LOCAL24PC:
8056     case elfcpp::R_POWERPC_REL16:
8057     case elfcpp::R_POWERPC_REL16_LO:
8058     case elfcpp::R_POWERPC_REL16_HI:
8059     case elfcpp::R_POWERPC_REL16_HA:
8060     case elfcpp::R_POWERPC_REL16DX_HA:
8061     case elfcpp::R_POWERPC_REL14:
8062     case elfcpp::R_POWERPC_REL14_BRTAKEN:
8063     case elfcpp::R_POWERPC_REL14_BRNTAKEN:
8064       value -= address;
8065       break;
8066
8067     case elfcpp::R_PPC64_TOC16:
8068     case elfcpp::R_PPC64_TOC16_LO:
8069     case elfcpp::R_PPC64_TOC16_HI:
8070     case elfcpp::R_PPC64_TOC16_HA:
8071     case elfcpp::R_PPC64_TOC16_DS:
8072     case elfcpp::R_PPC64_TOC16_LO_DS:
8073       // Subtract the TOC base address.
8074       value -= (target->got_section()->output_section()->address()
8075                 + object->toc_base_offset());
8076       break;
8077
8078     case elfcpp::R_POWERPC_SECTOFF:
8079     case elfcpp::R_POWERPC_SECTOFF_LO:
8080     case elfcpp::R_POWERPC_SECTOFF_HI:
8081     case elfcpp::R_POWERPC_SECTOFF_HA:
8082     case elfcpp::R_PPC64_SECTOFF_DS:
8083     case elfcpp::R_PPC64_SECTOFF_LO_DS:
8084       if (os != NULL)
8085         value -= os->address();
8086       break;
8087
8088     case elfcpp::R_PPC64_TPREL16_DS:
8089     case elfcpp::R_PPC64_TPREL16_LO_DS:
8090     case elfcpp::R_PPC64_TPREL16_HIGH:
8091     case elfcpp::R_PPC64_TPREL16_HIGHA:
8092       if (size != 64)
8093         // R_PPC_TLSGD, R_PPC_TLSLD, R_PPC_EMB_RELST_LO, R_PPC_EMB_RELST_HI
8094         break;
8095       // Fall through.
8096     case elfcpp::R_POWERPC_TPREL16:
8097     case elfcpp::R_POWERPC_TPREL16_LO:
8098     case elfcpp::R_POWERPC_TPREL16_HI:
8099     case elfcpp::R_POWERPC_TPREL16_HA:
8100     case elfcpp::R_POWERPC_TPREL:
8101     case elfcpp::R_PPC64_TPREL16_HIGHER:
8102     case elfcpp::R_PPC64_TPREL16_HIGHERA:
8103     case elfcpp::R_PPC64_TPREL16_HIGHEST:
8104     case elfcpp::R_PPC64_TPREL16_HIGHESTA:
8105       // tls symbol values are relative to tls_segment()->vaddr()
8106       value -= tp_offset;
8107       break;
8108
8109     case elfcpp::R_PPC64_DTPREL16_DS:
8110     case elfcpp::R_PPC64_DTPREL16_LO_DS:
8111     case elfcpp::R_PPC64_DTPREL16_HIGHER:
8112     case elfcpp::R_PPC64_DTPREL16_HIGHERA:
8113     case elfcpp::R_PPC64_DTPREL16_HIGHEST:
8114     case elfcpp::R_PPC64_DTPREL16_HIGHESTA:
8115       if (size != 64)
8116         // R_PPC_EMB_NADDR32, R_PPC_EMB_NADDR16, R_PPC_EMB_NADDR16_LO
8117         // R_PPC_EMB_NADDR16_HI, R_PPC_EMB_NADDR16_HA, R_PPC_EMB_SDAI16
8118         break;
8119       // Fall through.
8120     case elfcpp::R_POWERPC_DTPREL16:
8121     case elfcpp::R_POWERPC_DTPREL16_LO:
8122     case elfcpp::R_POWERPC_DTPREL16_HI:
8123     case elfcpp::R_POWERPC_DTPREL16_HA:
8124     case elfcpp::R_POWERPC_DTPREL:
8125     case elfcpp::R_PPC64_DTPREL16_HIGH:
8126     case elfcpp::R_PPC64_DTPREL16_HIGHA:
8127       // tls symbol values are relative to tls_segment()->vaddr()
8128       value -= dtp_offset;
8129       break;
8130
8131     case elfcpp::R_PPC64_ADDR64_LOCAL:
8132       if (gsym != NULL)
8133         value += object->ppc64_local_entry_offset(gsym);
8134       else
8135         value += object->ppc64_local_entry_offset(r_sym);
8136       break;
8137
8138     default:
8139       break;
8140     }
8141
8142   Insn branch_bit = 0;
8143   switch (r_type)
8144     {
8145     case elfcpp::R_POWERPC_ADDR14_BRTAKEN:
8146     case elfcpp::R_POWERPC_REL14_BRTAKEN:
8147       branch_bit = 1 << 21;
8148       // Fall through.
8149     case elfcpp::R_POWERPC_ADDR14_BRNTAKEN:
8150     case elfcpp::R_POWERPC_REL14_BRNTAKEN:
8151       {
8152         Insn* iview = reinterpret_cast<Insn*>(view);
8153         Insn insn = elfcpp::Swap<32, big_endian>::readval(iview);
8154         insn &= ~(1 << 21);
8155         insn |= branch_bit;
8156         if (this->is_isa_v2)
8157           {
8158             // Set 'a' bit.  This is 0b00010 in BO field for branch
8159             // on CR(BI) insns (BO == 001at or 011at), and 0b01000
8160             // for branch on CTR insns (BO == 1a00t or 1a01t).
8161             if ((insn & (0x14 << 21)) == (0x04 << 21))
8162               insn |= 0x02 << 21;
8163             else if ((insn & (0x14 << 21)) == (0x10 << 21))
8164               insn |= 0x08 << 21;
8165             else
8166               break;
8167           }
8168         else
8169           {
8170             // Invert 'y' bit if not the default.
8171             if (static_cast<Signed_address>(value) < 0)
8172               insn ^= 1 << 21;
8173           }
8174         elfcpp::Swap<32, big_endian>::writeval(iview, insn);
8175       }
8176       break;
8177
8178     default:
8179       break;
8180     }
8181
8182   if (size == 64)
8183     {
8184       switch (r_type)
8185         {
8186         default:
8187           break;
8188
8189           // Multi-instruction sequences that access the GOT/TOC can
8190           // be optimized, eg.
8191           //     addis ra,r2,x@got@ha; ld rb,x@got@l(ra);
8192           // to  addis ra,r2,x@toc@ha; addi rb,ra,x@toc@l;
8193           // and
8194           //     addis ra,r2,0; addi rb,ra,x@toc@l;
8195           // to  nop;           addi rb,r2,x@toc;
8196           // FIXME: the @got sequence shown above is not yet
8197           // optimized.  Note that gcc as of 2017-01-07 doesn't use
8198           // the ELF @got relocs except for TLS, instead using the
8199           // PowerOpen variant of a compiler managed GOT (called TOC).
8200           // The PowerOpen TOC sequence equivalent to the first
8201           // example is optimized.
8202         case elfcpp::R_POWERPC_GOT_TLSLD16_HA:
8203         case elfcpp::R_POWERPC_GOT_TLSGD16_HA:
8204         case elfcpp::R_POWERPC_GOT_TPREL16_HA:
8205         case elfcpp::R_POWERPC_GOT_DTPREL16_HA:
8206         case elfcpp::R_POWERPC_GOT16_HA:
8207         case elfcpp::R_PPC64_TOC16_HA:
8208           if (parameters->options().toc_optimize())
8209             {
8210               Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
8211               Insn insn = elfcpp::Swap<32, big_endian>::readval(iview);
8212               if (r_type == elfcpp::R_PPC64_TOC16_HA
8213                   && object->make_toc_relative(target, &value))
8214                 {
8215                   gold_assert((insn & ((0x3f << 26) | 0x1f << 16))
8216                               == ((15u << 26) | (2 << 16)));
8217                 }
8218               if (((insn & ((0x3f << 26) | 0x1f << 16))
8219                    == ((15u << 26) | (2 << 16)) /* addis rt,2,imm */)
8220                   && value + 0x8000 < 0x10000)
8221                 {
8222                   elfcpp::Swap<32, big_endian>::writeval(iview, nop);
8223                   return true;
8224                 }
8225             }
8226           break;
8227
8228         case elfcpp::R_POWERPC_GOT_TLSLD16_LO:
8229         case elfcpp::R_POWERPC_GOT_TLSGD16_LO:
8230         case elfcpp::R_POWERPC_GOT_TPREL16_LO:
8231         case elfcpp::R_POWERPC_GOT_DTPREL16_LO:
8232         case elfcpp::R_POWERPC_GOT16_LO:
8233         case elfcpp::R_PPC64_GOT16_LO_DS:
8234         case elfcpp::R_PPC64_TOC16_LO:
8235         case elfcpp::R_PPC64_TOC16_LO_DS:
8236           if (parameters->options().toc_optimize())
8237             {
8238               Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
8239               Insn insn = elfcpp::Swap<32, big_endian>::readval(iview);
8240               bool changed = false;
8241               if (r_type == elfcpp::R_PPC64_TOC16_LO_DS
8242                   && object->make_toc_relative(target, &value))
8243                 {
8244                   gold_assert ((insn & (0x3f << 26)) == 58u << 26 /* ld */);
8245                   insn ^= (14u << 26) ^ (58u << 26);
8246                   r_type = elfcpp::R_PPC64_TOC16_LO;
8247                   changed = true;
8248                 }
8249               if (ok_lo_toc_insn(insn, r_type)
8250                   && value + 0x8000 < 0x10000)
8251                 {
8252                   if ((insn & (0x3f << 26)) == 12u << 26 /* addic */)
8253                     {
8254                       // Transform addic to addi when we change reg.
8255                       insn &= ~((0x3f << 26) | (0x1f << 16));
8256                       insn |= (14u << 26) | (2 << 16);
8257                     }
8258                   else
8259                     {
8260                       insn &= ~(0x1f << 16);
8261                       insn |= 2 << 16;
8262                     }
8263                   changed = true;
8264                 }
8265               if (changed)
8266                 elfcpp::Swap<32, big_endian>::writeval(iview, insn);
8267             }
8268           break;
8269
8270         case elfcpp::R_PPC64_ENTRY:
8271           value = (target->got_section()->output_section()->address()
8272                    + object->toc_base_offset());
8273           if (value + 0x80008000 <= 0xffffffff
8274               && !parameters->options().output_is_position_independent())
8275             {
8276               Insn* iview = reinterpret_cast<Insn*>(view);
8277               Insn insn1 = elfcpp::Swap<32, big_endian>::readval(iview);
8278               Insn insn2 = elfcpp::Swap<32, big_endian>::readval(iview + 1);
8279
8280               if ((insn1 & ~0xfffc) == ld_2_12
8281                   && insn2 == add_2_2_12)
8282                 {
8283                   insn1 = lis_2 + ha(value);
8284                   elfcpp::Swap<32, big_endian>::writeval(iview, insn1);
8285                   insn2 = addi_2_2 + l(value);
8286                   elfcpp::Swap<32, big_endian>::writeval(iview + 1, insn2);
8287                   return true;
8288                 }
8289             }
8290           else
8291             {
8292               value -= address;
8293               if (value + 0x80008000 <= 0xffffffff)
8294                 {
8295                   Insn* iview = reinterpret_cast<Insn*>(view);
8296                   Insn insn1 = elfcpp::Swap<32, big_endian>::readval(iview);
8297                   Insn insn2 = elfcpp::Swap<32, big_endian>::readval(iview + 1);
8298
8299                   if ((insn1 & ~0xfffc) == ld_2_12
8300                       && insn2 == add_2_2_12)
8301                     {
8302                       insn1 = addis_2_12 + ha(value);
8303                       elfcpp::Swap<32, big_endian>::writeval(iview, insn1);
8304                       insn2 = addi_2_2 + l(value);
8305                       elfcpp::Swap<32, big_endian>::writeval(iview + 1, insn2);
8306                       return true;
8307                     }
8308                 }
8309             }
8310           break;
8311
8312         case elfcpp::R_POWERPC_REL16_LO:
8313           // If we are generating a non-PIC executable, edit
8314           //    0:      addis 2,12,.TOC.-0b@ha
8315           //            addi 2,2,.TOC.-0b@l
8316           // used by ELFv2 global entry points to set up r2, to
8317           //            lis 2,.TOC.@ha
8318           //            addi 2,2,.TOC.@l
8319           // if .TOC. is in range.  */
8320           if (value + address - 4 + 0x80008000 <= 0xffffffff
8321               && relnum != 0
8322               && preloc != NULL
8323               && target->abiversion() >= 2
8324               && !parameters->options().output_is_position_independent()
8325               && rela.get_r_addend() == d_offset + 4
8326               && gsym != NULL
8327               && strcmp(gsym->name(), ".TOC.") == 0)
8328             {
8329               const int reloc_size = elfcpp::Elf_sizes<size>::rela_size;
8330               Reltype prev_rela(preloc - reloc_size);
8331               if ((prev_rela.get_r_info()
8332                    == elfcpp::elf_r_info<size>(r_sym,
8333                                                elfcpp::R_POWERPC_REL16_HA))
8334                   && prev_rela.get_r_offset() + 4 == rela.get_r_offset()
8335                   && prev_rela.get_r_addend() + 4 == rela.get_r_addend())
8336                 {
8337                   Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
8338                   Insn insn1 = elfcpp::Swap<32, big_endian>::readval(iview - 1);
8339                   Insn insn2 = elfcpp::Swap<32, big_endian>::readval(iview);
8340
8341                   if ((insn1 & 0xffff0000) == addis_2_12
8342                       && (insn2 & 0xffff0000) == addi_2_2)
8343                     {
8344                       insn1 = lis_2 + ha(value + address - 4);
8345                       elfcpp::Swap<32, big_endian>::writeval(iview - 1, insn1);
8346                       insn2 = addi_2_2 + l(value + address - 4);
8347                       elfcpp::Swap<32, big_endian>::writeval(iview, insn2);
8348                       if (relinfo->rr)
8349                         {
8350                           relinfo->rr->set_strategy(relnum - 1,
8351                                                     Relocatable_relocs::RELOC_SPECIAL);
8352                           relinfo->rr->set_strategy(relnum,
8353                                                     Relocatable_relocs::RELOC_SPECIAL);
8354                         }
8355                       return true;
8356                     }
8357                 }
8358             }
8359           break;
8360         }
8361     }
8362
8363   typename Reloc::Overflow_check overflow = Reloc::CHECK_NONE;
8364   elfcpp::Shdr<size, big_endian> shdr(relinfo->data_shdr);
8365   switch (r_type)
8366     {
8367     case elfcpp::R_POWERPC_ADDR32:
8368     case elfcpp::R_POWERPC_UADDR32:
8369       if (size == 64)
8370         overflow = Reloc::CHECK_BITFIELD;
8371       break;
8372
8373     case elfcpp::R_POWERPC_REL32:
8374     case elfcpp::R_POWERPC_REL16DX_HA:
8375       if (size == 64)
8376         overflow = Reloc::CHECK_SIGNED;
8377       break;
8378
8379     case elfcpp::R_POWERPC_UADDR16:
8380       overflow = Reloc::CHECK_BITFIELD;
8381       break;
8382
8383     case elfcpp::R_POWERPC_ADDR16:
8384       // We really should have three separate relocations,
8385       // one for 16-bit data, one for insns with 16-bit signed fields,
8386       // and one for insns with 16-bit unsigned fields.
8387       overflow = Reloc::CHECK_BITFIELD;
8388       if ((shdr.get_sh_flags() & elfcpp::SHF_EXECINSTR) != 0)
8389         overflow = Reloc::CHECK_LOW_INSN;
8390       break;
8391
8392     case elfcpp::R_POWERPC_ADDR16_HI:
8393     case elfcpp::R_POWERPC_ADDR16_HA:
8394     case elfcpp::R_POWERPC_GOT16_HI:
8395     case elfcpp::R_POWERPC_GOT16_HA:
8396     case elfcpp::R_POWERPC_PLT16_HI:
8397     case elfcpp::R_POWERPC_PLT16_HA:
8398     case elfcpp::R_POWERPC_SECTOFF_HI:
8399     case elfcpp::R_POWERPC_SECTOFF_HA:
8400     case elfcpp::R_PPC64_TOC16_HI:
8401     case elfcpp::R_PPC64_TOC16_HA:
8402     case elfcpp::R_PPC64_PLTGOT16_HI:
8403     case elfcpp::R_PPC64_PLTGOT16_HA:
8404     case elfcpp::R_POWERPC_TPREL16_HI:
8405     case elfcpp::R_POWERPC_TPREL16_HA:
8406     case elfcpp::R_POWERPC_DTPREL16_HI:
8407     case elfcpp::R_POWERPC_DTPREL16_HA:
8408     case elfcpp::R_POWERPC_GOT_TLSGD16_HI:
8409     case elfcpp::R_POWERPC_GOT_TLSGD16_HA:
8410     case elfcpp::R_POWERPC_GOT_TLSLD16_HI:
8411     case elfcpp::R_POWERPC_GOT_TLSLD16_HA:
8412     case elfcpp::R_POWERPC_GOT_TPREL16_HI:
8413     case elfcpp::R_POWERPC_GOT_TPREL16_HA:
8414     case elfcpp::R_POWERPC_GOT_DTPREL16_HI:
8415     case elfcpp::R_POWERPC_GOT_DTPREL16_HA:
8416     case elfcpp::R_POWERPC_REL16_HI:
8417     case elfcpp::R_POWERPC_REL16_HA:
8418       if (size != 32)
8419         overflow = Reloc::CHECK_HIGH_INSN;
8420       break;
8421
8422     case elfcpp::R_POWERPC_REL16:
8423     case elfcpp::R_PPC64_TOC16:
8424     case elfcpp::R_POWERPC_GOT16:
8425     case elfcpp::R_POWERPC_SECTOFF:
8426     case elfcpp::R_POWERPC_TPREL16:
8427     case elfcpp::R_POWERPC_DTPREL16:
8428     case elfcpp::R_POWERPC_GOT_TLSGD16:
8429     case elfcpp::R_POWERPC_GOT_TLSLD16:
8430     case elfcpp::R_POWERPC_GOT_TPREL16:
8431     case elfcpp::R_POWERPC_GOT_DTPREL16:
8432       overflow = Reloc::CHECK_LOW_INSN;
8433       break;
8434
8435     case elfcpp::R_POWERPC_ADDR24:
8436     case elfcpp::R_POWERPC_ADDR14:
8437     case elfcpp::R_POWERPC_ADDR14_BRTAKEN:
8438     case elfcpp::R_POWERPC_ADDR14_BRNTAKEN:
8439     case elfcpp::R_PPC64_ADDR16_DS:
8440     case elfcpp::R_POWERPC_REL24:
8441     case elfcpp::R_PPC_PLTREL24:
8442     case elfcpp::R_PPC_LOCAL24PC:
8443     case elfcpp::R_PPC64_TPREL16_DS:
8444     case elfcpp::R_PPC64_DTPREL16_DS:
8445     case elfcpp::R_PPC64_TOC16_DS:
8446     case elfcpp::R_PPC64_GOT16_DS:
8447     case elfcpp::R_PPC64_SECTOFF_DS:
8448     case elfcpp::R_POWERPC_REL14:
8449     case elfcpp::R_POWERPC_REL14_BRTAKEN:
8450     case elfcpp::R_POWERPC_REL14_BRNTAKEN:
8451       overflow = Reloc::CHECK_SIGNED;
8452       break;
8453     }
8454
8455   Insn* iview = reinterpret_cast<Insn*>(view - d_offset);
8456   Insn insn = 0;
8457
8458   if (overflow == Reloc::CHECK_LOW_INSN
8459       || overflow == Reloc::CHECK_HIGH_INSN)
8460     {
8461       insn = elfcpp::Swap<32, big_endian>::readval(iview);
8462
8463       if ((insn & (0x3f << 26)) == 10u << 26 /* cmpli */)
8464         overflow = Reloc::CHECK_BITFIELD;
8465       else if (overflow == Reloc::CHECK_LOW_INSN
8466                ? ((insn & (0x3f << 26)) == 28u << 26 /* andi */
8467                   || (insn & (0x3f << 26)) == 24u << 26 /* ori */
8468                   || (insn & (0x3f << 26)) == 26u << 26 /* xori */)
8469                : ((insn & (0x3f << 26)) == 29u << 26 /* andis */
8470                   || (insn & (0x3f << 26)) == 25u << 26 /* oris */
8471                   || (insn & (0x3f << 26)) == 27u << 26 /* xoris */))
8472         overflow = Reloc::CHECK_UNSIGNED;
8473       else
8474         overflow = Reloc::CHECK_SIGNED;
8475     }
8476
8477   bool maybe_dq_reloc = false;
8478   typename Powerpc_relocate_functions<size, big_endian>::Status status
8479     = Powerpc_relocate_functions<size, big_endian>::STATUS_OK;
8480   switch (r_type)
8481     {
8482     case elfcpp::R_POWERPC_NONE:
8483     case elfcpp::R_POWERPC_TLS:
8484     case elfcpp::R_POWERPC_GNU_VTINHERIT:
8485     case elfcpp::R_POWERPC_GNU_VTENTRY:
8486       break;
8487
8488     case elfcpp::R_PPC64_ADDR64:
8489     case elfcpp::R_PPC64_REL64:
8490     case elfcpp::R_PPC64_TOC:
8491     case elfcpp::R_PPC64_ADDR64_LOCAL:
8492       Reloc::addr64(view, value);
8493       break;
8494
8495     case elfcpp::R_POWERPC_TPREL:
8496     case elfcpp::R_POWERPC_DTPREL:
8497       if (size == 64)
8498         Reloc::addr64(view, value);
8499       else
8500         status = Reloc::addr32(view, value, overflow);
8501       break;
8502
8503     case elfcpp::R_PPC64_UADDR64:
8504       Reloc::addr64_u(view, value);
8505       break;
8506
8507     case elfcpp::R_POWERPC_ADDR32:
8508       status = Reloc::addr32(view, value, overflow);
8509       break;
8510
8511     case elfcpp::R_POWERPC_REL32:
8512     case elfcpp::R_POWERPC_UADDR32:
8513       status = Reloc::addr32_u(view, value, overflow);
8514       break;
8515
8516     case elfcpp::R_POWERPC_ADDR24:
8517     case elfcpp::R_POWERPC_REL24:
8518     case elfcpp::R_PPC_PLTREL24:
8519     case elfcpp::R_PPC_LOCAL24PC:
8520       status = Reloc::addr24(view, value, overflow);
8521       break;
8522
8523     case elfcpp::R_POWERPC_GOT_DTPREL16:
8524     case elfcpp::R_POWERPC_GOT_DTPREL16_LO:
8525     case elfcpp::R_POWERPC_GOT_TPREL16:
8526     case elfcpp::R_POWERPC_GOT_TPREL16_LO:
8527       if (size == 64)
8528         {
8529           // On ppc64 these are all ds form
8530           maybe_dq_reloc = true;
8531           break;
8532         }
8533       // Fall through.
8534     case elfcpp::R_POWERPC_ADDR16:
8535     case elfcpp::R_POWERPC_REL16:
8536     case elfcpp::R_PPC64_TOC16:
8537     case elfcpp::R_POWERPC_GOT16:
8538     case elfcpp::R_POWERPC_SECTOFF:
8539     case elfcpp::R_POWERPC_TPREL16:
8540     case elfcpp::R_POWERPC_DTPREL16:
8541     case elfcpp::R_POWERPC_GOT_TLSGD16:
8542     case elfcpp::R_POWERPC_GOT_TLSLD16:
8543     case elfcpp::R_POWERPC_ADDR16_LO:
8544     case elfcpp::R_POWERPC_REL16_LO:
8545     case elfcpp::R_PPC64_TOC16_LO:
8546     case elfcpp::R_POWERPC_GOT16_LO:
8547     case elfcpp::R_POWERPC_SECTOFF_LO:
8548     case elfcpp::R_POWERPC_TPREL16_LO:
8549     case elfcpp::R_POWERPC_DTPREL16_LO:
8550     case elfcpp::R_POWERPC_GOT_TLSGD16_LO:
8551     case elfcpp::R_POWERPC_GOT_TLSLD16_LO:
8552       if (size == 64)
8553         status = Reloc::addr16(view, value, overflow);
8554       else
8555         maybe_dq_reloc = true;
8556       break;
8557
8558     case elfcpp::R_POWERPC_UADDR16:
8559       status = Reloc::addr16_u(view, value, overflow);
8560       break;
8561
8562     case elfcpp::R_PPC64_ADDR16_HIGH:
8563     case elfcpp::R_PPC64_TPREL16_HIGH:
8564     case elfcpp::R_PPC64_DTPREL16_HIGH:
8565       if (size == 32)
8566         // R_PPC_EMB_MRKREF, R_PPC_EMB_RELST_LO, R_PPC_EMB_RELST_HA
8567         goto unsupp;
8568       // Fall through.
8569     case elfcpp::R_POWERPC_ADDR16_HI:
8570     case elfcpp::R_POWERPC_REL16_HI:
8571     case elfcpp::R_PPC64_TOC16_HI:
8572     case elfcpp::R_POWERPC_GOT16_HI:
8573     case elfcpp::R_POWERPC_SECTOFF_HI:
8574     case elfcpp::R_POWERPC_TPREL16_HI:
8575     case elfcpp::R_POWERPC_DTPREL16_HI:
8576     case elfcpp::R_POWERPC_GOT_TLSGD16_HI:
8577     case elfcpp::R_POWERPC_GOT_TLSLD16_HI:
8578     case elfcpp::R_POWERPC_GOT_TPREL16_HI:
8579     case elfcpp::R_POWERPC_GOT_DTPREL16_HI:
8580       Reloc::addr16_hi(view, value);
8581       break;
8582
8583     case elfcpp::R_PPC64_ADDR16_HIGHA:
8584     case elfcpp::R_PPC64_TPREL16_HIGHA:
8585     case elfcpp::R_PPC64_DTPREL16_HIGHA:
8586       if (size == 32)
8587         // R_PPC_EMB_RELSEC16, R_PPC_EMB_RELST_HI, R_PPC_EMB_BIT_FLD
8588         goto unsupp;
8589       // Fall through.
8590     case elfcpp::R_POWERPC_ADDR16_HA:
8591     case elfcpp::R_POWERPC_REL16_HA:
8592     case elfcpp::R_PPC64_TOC16_HA:
8593     case elfcpp::R_POWERPC_GOT16_HA:
8594     case elfcpp::R_POWERPC_SECTOFF_HA:
8595     case elfcpp::R_POWERPC_TPREL16_HA:
8596     case elfcpp::R_POWERPC_DTPREL16_HA:
8597     case elfcpp::R_POWERPC_GOT_TLSGD16_HA:
8598     case elfcpp::R_POWERPC_GOT_TLSLD16_HA:
8599     case elfcpp::R_POWERPC_GOT_TPREL16_HA:
8600     case elfcpp::R_POWERPC_GOT_DTPREL16_HA:
8601       Reloc::addr16_ha(view, value);
8602       break;
8603
8604     case elfcpp::R_POWERPC_REL16DX_HA:
8605       status = Reloc::addr16dx_ha(view, value, overflow);
8606       break;
8607
8608     case elfcpp::R_PPC64_DTPREL16_HIGHER:
8609       if (size == 32)
8610         // R_PPC_EMB_NADDR16_LO
8611         goto unsupp;
8612       // Fall through.
8613     case elfcpp::R_PPC64_ADDR16_HIGHER:
8614     case elfcpp::R_PPC64_TPREL16_HIGHER:
8615       Reloc::addr16_hi2(view, value);
8616       break;
8617
8618     case elfcpp::R_PPC64_DTPREL16_HIGHERA:
8619       if (size == 32)
8620         // R_PPC_EMB_NADDR16_HI
8621         goto unsupp;
8622       // Fall through.
8623     case elfcpp::R_PPC64_ADDR16_HIGHERA:
8624     case elfcpp::R_PPC64_TPREL16_HIGHERA:
8625       Reloc::addr16_ha2(view, value);
8626       break;
8627
8628     case elfcpp::R_PPC64_DTPREL16_HIGHEST:
8629       if (size == 32)
8630         // R_PPC_EMB_NADDR16_HA
8631         goto unsupp;
8632       // Fall through.
8633     case elfcpp::R_PPC64_ADDR16_HIGHEST:
8634     case elfcpp::R_PPC64_TPREL16_HIGHEST:
8635       Reloc::addr16_hi3(view, value);
8636       break;
8637
8638     case elfcpp::R_PPC64_DTPREL16_HIGHESTA:
8639       if (size == 32)
8640         // R_PPC_EMB_SDAI16
8641         goto unsupp;
8642       // Fall through.
8643     case elfcpp::R_PPC64_ADDR16_HIGHESTA:
8644     case elfcpp::R_PPC64_TPREL16_HIGHESTA:
8645       Reloc::addr16_ha3(view, value);
8646       break;
8647
8648     case elfcpp::R_PPC64_DTPREL16_DS:
8649     case elfcpp::R_PPC64_DTPREL16_LO_DS:
8650       if (size == 32)
8651         // R_PPC_EMB_NADDR32, R_PPC_EMB_NADDR16
8652         goto unsupp;
8653       // Fall through.
8654     case elfcpp::R_PPC64_TPREL16_DS:
8655     case elfcpp::R_PPC64_TPREL16_LO_DS:
8656       if (size == 32)
8657         // R_PPC_TLSGD, R_PPC_TLSLD
8658         break;
8659       // Fall through.
8660     case elfcpp::R_PPC64_ADDR16_DS:
8661     case elfcpp::R_PPC64_ADDR16_LO_DS:
8662     case elfcpp::R_PPC64_TOC16_DS:
8663     case elfcpp::R_PPC64_TOC16_LO_DS:
8664     case elfcpp::R_PPC64_GOT16_DS:
8665     case elfcpp::R_PPC64_GOT16_LO_DS:
8666     case elfcpp::R_PPC64_SECTOFF_DS:
8667     case elfcpp::R_PPC64_SECTOFF_LO_DS:
8668       maybe_dq_reloc = true;
8669       break;
8670
8671     case elfcpp::R_POWERPC_ADDR14:
8672     case elfcpp::R_POWERPC_ADDR14_BRTAKEN:
8673     case elfcpp::R_POWERPC_ADDR14_BRNTAKEN:
8674     case elfcpp::R_POWERPC_REL14:
8675     case elfcpp::R_POWERPC_REL14_BRTAKEN:
8676     case elfcpp::R_POWERPC_REL14_BRNTAKEN:
8677       status = Reloc::addr14(view, value, overflow);
8678       break;
8679
8680     case elfcpp::R_POWERPC_COPY:
8681     case elfcpp::R_POWERPC_GLOB_DAT:
8682     case elfcpp::R_POWERPC_JMP_SLOT:
8683     case elfcpp::R_POWERPC_RELATIVE:
8684     case elfcpp::R_POWERPC_DTPMOD:
8685     case elfcpp::R_PPC64_JMP_IREL:
8686     case elfcpp::R_POWERPC_IRELATIVE:
8687       gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
8688                              _("unexpected reloc %u in object file"),
8689                              r_type);
8690       break;
8691
8692     case elfcpp::R_PPC_EMB_SDA21:
8693       if (size == 32)
8694         goto unsupp;
8695       else
8696         {
8697           // R_PPC64_TOCSAVE.  For the time being this can be ignored.
8698         }
8699       break;
8700
8701     case elfcpp::R_PPC_EMB_SDA2I16:
8702     case elfcpp::R_PPC_EMB_SDA2REL:
8703       if (size == 32)
8704         goto unsupp;
8705       // R_PPC64_TLSGD, R_PPC64_TLSLD
8706       break;
8707
8708     case elfcpp::R_POWERPC_PLT32:
8709     case elfcpp::R_POWERPC_PLTREL32:
8710     case elfcpp::R_POWERPC_PLT16_LO:
8711     case elfcpp::R_POWERPC_PLT16_HI:
8712     case elfcpp::R_POWERPC_PLT16_HA:
8713     case elfcpp::R_PPC_SDAREL16:
8714     case elfcpp::R_POWERPC_ADDR30:
8715     case elfcpp::R_PPC64_PLT64:
8716     case elfcpp::R_PPC64_PLTREL64:
8717     case elfcpp::R_PPC64_PLTGOT16:
8718     case elfcpp::R_PPC64_PLTGOT16_LO:
8719     case elfcpp::R_PPC64_PLTGOT16_HI:
8720     case elfcpp::R_PPC64_PLTGOT16_HA:
8721     case elfcpp::R_PPC64_PLT16_LO_DS:
8722     case elfcpp::R_PPC64_PLTGOT16_DS:
8723     case elfcpp::R_PPC64_PLTGOT16_LO_DS:
8724     case elfcpp::R_PPC_EMB_RELSDA:
8725     case elfcpp::R_PPC_TOC16:
8726     default:
8727     unsupp:
8728       gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
8729                              _("unsupported reloc %u"),
8730                              r_type);
8731       break;
8732     }
8733
8734   if (maybe_dq_reloc)
8735     {
8736       if (insn == 0)
8737         insn = elfcpp::Swap<32, big_endian>::readval(iview);
8738
8739       if ((insn & (0x3f << 26)) == 56u << 26 /* lq */
8740           || ((insn & (0x3f << 26)) == (61u << 26) /* lxv, stxv */
8741               && (insn & 3) == 1))
8742         status = Reloc::addr16_dq(view, value, overflow);
8743       else if (size == 64
8744                || (insn & (0x3f << 26)) == 58u << 26 /* ld,ldu,lwa */
8745                || (insn & (0x3f << 26)) == 62u << 26 /* std,stdu,stq */
8746                || (insn & (0x3f << 26)) == 57u << 26 /* lfdp */
8747                || (insn & (0x3f << 26)) == 61u << 26 /* stfdp */)
8748         status = Reloc::addr16_ds(view, value, overflow);
8749       else
8750         status = Reloc::addr16(view, value, overflow);
8751     }
8752
8753   if (status != Powerpc_relocate_functions<size, big_endian>::STATUS_OK
8754       && (has_stub_value
8755           || !(gsym != NULL
8756                && gsym->is_undefined()
8757                && is_branch_reloc(r_type))))
8758     {
8759       gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
8760                              _("relocation overflow"));
8761       if (has_stub_value)
8762         gold_info(_("try relinking with a smaller --stub-group-size"));
8763     }
8764
8765   return true;
8766 }
8767
8768 // Relocate section data.
8769
8770 template<int size, bool big_endian>
8771 void
8772 Target_powerpc<size, big_endian>::relocate_section(
8773     const Relocate_info<size, big_endian>* relinfo,
8774     unsigned int sh_type,
8775     const unsigned char* prelocs,
8776     size_t reloc_count,
8777     Output_section* output_section,
8778     bool needs_special_offset_handling,
8779     unsigned char* view,
8780     Address address,
8781     section_size_type view_size,
8782     const Reloc_symbol_changes* reloc_symbol_changes)
8783 {
8784   typedef Target_powerpc<size, big_endian> Powerpc;
8785   typedef typename Target_powerpc<size, big_endian>::Relocate Powerpc_relocate;
8786   typedef typename Target_powerpc<size, big_endian>::Relocate_comdat_behavior
8787     Powerpc_comdat_behavior;
8788   typedef gold::Default_classify_reloc<elfcpp::SHT_RELA, size, big_endian>
8789       Classify_reloc;
8790
8791   gold_assert(sh_type == elfcpp::SHT_RELA);
8792
8793   gold::relocate_section<size, big_endian, Powerpc, Powerpc_relocate,
8794                          Powerpc_comdat_behavior, Classify_reloc>(
8795     relinfo,
8796     this,
8797     prelocs,
8798     reloc_count,
8799     output_section,
8800     needs_special_offset_handling,
8801     view,
8802     address,
8803     view_size,
8804     reloc_symbol_changes);
8805 }
8806
8807 template<int size, bool big_endian>
8808 class Powerpc_scan_relocatable_reloc
8809 {
8810 public:
8811   typedef typename elfcpp::Rela<size, big_endian> Reltype;
8812   static const int reloc_size = elfcpp::Elf_sizes<size>::rela_size;
8813   static const int sh_type = elfcpp::SHT_RELA;
8814
8815   // Return the symbol referred to by the relocation.
8816   static inline unsigned int
8817   get_r_sym(const Reltype* reloc)
8818   { return elfcpp::elf_r_sym<size>(reloc->get_r_info()); }
8819
8820   // Return the type of the relocation.
8821   static inline unsigned int
8822   get_r_type(const Reltype* reloc)
8823   { return elfcpp::elf_r_type<size>(reloc->get_r_info()); }
8824
8825   // Return the strategy to use for a local symbol which is not a
8826   // section symbol, given the relocation type.
8827   inline Relocatable_relocs::Reloc_strategy
8828   local_non_section_strategy(unsigned int r_type, Relobj*, unsigned int r_sym)
8829   {
8830     if (r_type == 0 && r_sym == 0)
8831       return Relocatable_relocs::RELOC_DISCARD;
8832     return Relocatable_relocs::RELOC_COPY;
8833   }
8834
8835   // Return the strategy to use for a local symbol which is a section
8836   // symbol, given the relocation type.
8837   inline Relocatable_relocs::Reloc_strategy
8838   local_section_strategy(unsigned int, Relobj*)
8839   {
8840     return Relocatable_relocs::RELOC_ADJUST_FOR_SECTION_RELA;
8841   }
8842
8843   // Return the strategy to use for a global symbol, given the
8844   // relocation type, the object, and the symbol index.
8845   inline Relocatable_relocs::Reloc_strategy
8846   global_strategy(unsigned int r_type, Relobj*, unsigned int)
8847   {
8848     if (r_type == elfcpp::R_PPC_PLTREL24)
8849       return Relocatable_relocs::RELOC_SPECIAL;
8850     return Relocatable_relocs::RELOC_COPY;
8851   }
8852 };
8853
8854 // Scan the relocs during a relocatable link.
8855
8856 template<int size, bool big_endian>
8857 void
8858 Target_powerpc<size, big_endian>::scan_relocatable_relocs(
8859     Symbol_table* symtab,
8860     Layout* layout,
8861     Sized_relobj_file<size, big_endian>* object,
8862     unsigned int data_shndx,
8863     unsigned int sh_type,
8864     const unsigned char* prelocs,
8865     size_t reloc_count,
8866     Output_section* output_section,
8867     bool needs_special_offset_handling,
8868     size_t local_symbol_count,
8869     const unsigned char* plocal_symbols,
8870     Relocatable_relocs* rr)
8871 {
8872   typedef Powerpc_scan_relocatable_reloc<size, big_endian> Scan_strategy;
8873
8874   gold_assert(sh_type == elfcpp::SHT_RELA);
8875
8876   gold::scan_relocatable_relocs<size, big_endian, Scan_strategy>(
8877     symtab,
8878     layout,
8879     object,
8880     data_shndx,
8881     prelocs,
8882     reloc_count,
8883     output_section,
8884     needs_special_offset_handling,
8885     local_symbol_count,
8886     plocal_symbols,
8887     rr);
8888 }
8889
8890 // Scan the relocs for --emit-relocs.
8891
8892 template<int size, bool big_endian>
8893 void
8894 Target_powerpc<size, big_endian>::emit_relocs_scan(
8895     Symbol_table* symtab,
8896     Layout* layout,
8897     Sized_relobj_file<size, big_endian>* object,
8898     unsigned int data_shndx,
8899     unsigned int sh_type,
8900     const unsigned char* prelocs,
8901     size_t reloc_count,
8902     Output_section* output_section,
8903     bool needs_special_offset_handling,
8904     size_t local_symbol_count,
8905     const unsigned char* plocal_syms,
8906     Relocatable_relocs* rr)
8907 {
8908   typedef gold::Default_classify_reloc<elfcpp::SHT_RELA, size, big_endian>
8909       Classify_reloc;
8910   typedef gold::Default_emit_relocs_strategy<Classify_reloc>
8911       Emit_relocs_strategy;
8912
8913   gold_assert(sh_type == elfcpp::SHT_RELA);
8914
8915   gold::scan_relocatable_relocs<size, big_endian, Emit_relocs_strategy>(
8916     symtab,
8917     layout,
8918     object,
8919     data_shndx,
8920     prelocs,
8921     reloc_count,
8922     output_section,
8923     needs_special_offset_handling,
8924     local_symbol_count,
8925     plocal_syms,
8926     rr);
8927 }
8928
8929 // Emit relocations for a section.
8930 // This is a modified version of the function by the same name in
8931 // target-reloc.h.  Using relocate_special_relocatable for
8932 // R_PPC_PLTREL24 would require duplication of the entire body of the
8933 // loop, so we may as well duplicate the whole thing.
8934
8935 template<int size, bool big_endian>
8936 void
8937 Target_powerpc<size, big_endian>::relocate_relocs(
8938     const Relocate_info<size, big_endian>* relinfo,
8939     unsigned int sh_type,
8940     const unsigned char* prelocs,
8941     size_t reloc_count,
8942     Output_section* output_section,
8943     typename elfcpp::Elf_types<size>::Elf_Off offset_in_output_section,
8944     unsigned char*,
8945     Address view_address,
8946     section_size_type,
8947     unsigned char* reloc_view,
8948     section_size_type reloc_view_size)
8949 {
8950   gold_assert(sh_type == elfcpp::SHT_RELA);
8951
8952   typedef typename elfcpp::Rela<size, big_endian> Reltype;
8953   typedef typename elfcpp::Rela_write<size, big_endian> Reltype_write;
8954   const int reloc_size = elfcpp::Elf_sizes<size>::rela_size;
8955   // Offset from start of insn to d-field reloc.
8956   const int d_offset = big_endian ? 2 : 0;
8957
8958   Powerpc_relobj<size, big_endian>* const object
8959     = static_cast<Powerpc_relobj<size, big_endian>*>(relinfo->object);
8960   const unsigned int local_count = object->local_symbol_count();
8961   unsigned int got2_shndx = object->got2_shndx();
8962   Address got2_addend = 0;
8963   if (got2_shndx != 0)
8964     {
8965       got2_addend = object->get_output_section_offset(got2_shndx);
8966       gold_assert(got2_addend != invalid_address);
8967     }
8968
8969   unsigned char* pwrite = reloc_view;
8970   bool zap_next = false;
8971   for (size_t i = 0; i < reloc_count; ++i, prelocs += reloc_size)
8972     {
8973       Relocatable_relocs::Reloc_strategy strategy = relinfo->rr->strategy(i);
8974       if (strategy == Relocatable_relocs::RELOC_DISCARD)
8975         continue;
8976
8977       Reltype reloc(prelocs);
8978       Reltype_write reloc_write(pwrite);
8979
8980       Address offset = reloc.get_r_offset();
8981       typename elfcpp::Elf_types<size>::Elf_WXword r_info = reloc.get_r_info();
8982       unsigned int r_sym = elfcpp::elf_r_sym<size>(r_info);
8983       unsigned int r_type = elfcpp::elf_r_type<size>(r_info);
8984       const unsigned int orig_r_sym = r_sym;
8985       typename elfcpp::Elf_types<size>::Elf_Swxword addend
8986         = reloc.get_r_addend();
8987       const Symbol* gsym = NULL;
8988
8989       if (zap_next)
8990         {
8991           // We could arrange to discard these and other relocs for
8992           // tls optimised sequences in the strategy methods, but for
8993           // now do as BFD ld does.
8994           r_type = elfcpp::R_POWERPC_NONE;
8995           zap_next = false;
8996         }
8997
8998       // Get the new symbol index.
8999       Output_section* os = NULL;
9000       if (r_sym < local_count)
9001         {
9002           switch (strategy)
9003             {
9004             case Relocatable_relocs::RELOC_COPY:
9005             case Relocatable_relocs::RELOC_SPECIAL:
9006               if (r_sym != 0)
9007                 {
9008                   r_sym = object->symtab_index(r_sym);
9009                   gold_assert(r_sym != -1U);
9010                 }
9011               break;
9012
9013             case Relocatable_relocs::RELOC_ADJUST_FOR_SECTION_RELA:
9014               {
9015                 // We are adjusting a section symbol.  We need to find
9016                 // the symbol table index of the section symbol for
9017                 // the output section corresponding to input section
9018                 // in which this symbol is defined.
9019                 gold_assert(r_sym < local_count);
9020                 bool is_ordinary;
9021                 unsigned int shndx =
9022                   object->local_symbol_input_shndx(r_sym, &is_ordinary);
9023                 gold_assert(is_ordinary);
9024                 os = object->output_section(shndx);
9025                 gold_assert(os != NULL);
9026                 gold_assert(os->needs_symtab_index());
9027                 r_sym = os->symtab_index();
9028               }
9029               break;
9030
9031             default:
9032               gold_unreachable();
9033             }
9034         }
9035       else
9036         {
9037           gsym = object->global_symbol(r_sym);
9038           gold_assert(gsym != NULL);
9039           if (gsym->is_forwarder())
9040             gsym = relinfo->symtab->resolve_forwards(gsym);
9041
9042           gold_assert(gsym->has_symtab_index());
9043           r_sym = gsym->symtab_index();
9044         }
9045
9046       // Get the new offset--the location in the output section where
9047       // this relocation should be applied.
9048       if (static_cast<Address>(offset_in_output_section) != invalid_address)
9049         offset += offset_in_output_section;
9050       else
9051         {
9052           section_offset_type sot_offset =
9053             convert_types<section_offset_type, Address>(offset);
9054           section_offset_type new_sot_offset =
9055             output_section->output_offset(object, relinfo->data_shndx,
9056                                           sot_offset);
9057           gold_assert(new_sot_offset != -1);
9058           offset = new_sot_offset;
9059         }
9060
9061       // In an object file, r_offset is an offset within the section.
9062       // In an executable or dynamic object, generated by
9063       // --emit-relocs, r_offset is an absolute address.
9064       if (!parameters->options().relocatable())
9065         {
9066           offset += view_address;
9067           if (static_cast<Address>(offset_in_output_section) != invalid_address)
9068             offset -= offset_in_output_section;
9069         }
9070
9071       // Handle the reloc addend based on the strategy.
9072       if (strategy == Relocatable_relocs::RELOC_COPY)
9073         ;
9074       else if (strategy == Relocatable_relocs::RELOC_ADJUST_FOR_SECTION_RELA)
9075         {
9076           const Symbol_value<size>* psymval = object->local_symbol(orig_r_sym);
9077           gold_assert(os != NULL);
9078           addend = psymval->value(object, addend) - os->address();
9079         }
9080       else if (strategy == Relocatable_relocs::RELOC_SPECIAL)
9081         {
9082           if (size == 32)
9083             {
9084               if (addend >= 32768)
9085                 addend += got2_addend;
9086             }
9087           else if (r_type == elfcpp::R_POWERPC_REL16_HA)
9088             {
9089               r_type = elfcpp::R_POWERPC_ADDR16_HA;
9090               addend -= d_offset;
9091             }
9092           else if (r_type == elfcpp::R_POWERPC_REL16_LO)
9093             {
9094               r_type = elfcpp::R_POWERPC_ADDR16_LO;
9095               addend -= d_offset + 4;
9096             }
9097         }
9098       else
9099         gold_unreachable();
9100
9101       if (!parameters->options().relocatable())
9102         {
9103           if (r_type == elfcpp::R_POWERPC_GOT_TLSGD16
9104               || r_type == elfcpp::R_POWERPC_GOT_TLSGD16_LO
9105               || r_type == elfcpp::R_POWERPC_GOT_TLSGD16_HI
9106               || r_type == elfcpp::R_POWERPC_GOT_TLSGD16_HA)
9107             {
9108               // First instruction of a global dynamic sequence,
9109               // arg setup insn.
9110               const bool final = gsym == NULL || gsym->final_value_is_known();
9111               switch (this->optimize_tls_gd(final))
9112                 {
9113                 case tls::TLSOPT_TO_IE:
9114                   r_type += (elfcpp::R_POWERPC_GOT_TPREL16
9115                              - elfcpp::R_POWERPC_GOT_TLSGD16);
9116                   break;
9117                 case tls::TLSOPT_TO_LE:
9118                   if (r_type == elfcpp::R_POWERPC_GOT_TLSGD16
9119                       || r_type == elfcpp::R_POWERPC_GOT_TLSGD16_LO)
9120                     r_type = elfcpp::R_POWERPC_TPREL16_HA;
9121                   else
9122                     {
9123                       r_type = elfcpp::R_POWERPC_NONE;
9124                       offset -= d_offset;
9125                     }
9126                   break;
9127                 default:
9128                   break;
9129                 }
9130             }
9131           else if (r_type == elfcpp::R_POWERPC_GOT_TLSLD16
9132                    || r_type == elfcpp::R_POWERPC_GOT_TLSLD16_LO
9133                    || r_type == elfcpp::R_POWERPC_GOT_TLSLD16_HI
9134                    || r_type == elfcpp::R_POWERPC_GOT_TLSLD16_HA)
9135             {
9136               // First instruction of a local dynamic sequence,
9137               // arg setup insn.
9138               if (this->optimize_tls_ld() == tls::TLSOPT_TO_LE)
9139                 {
9140                   if (r_type == elfcpp::R_POWERPC_GOT_TLSLD16
9141                       || r_type == elfcpp::R_POWERPC_GOT_TLSLD16_LO)
9142                     {
9143                       r_type = elfcpp::R_POWERPC_TPREL16_HA;
9144                       const Output_section* os = relinfo->layout->tls_segment()
9145                         ->first_section();
9146                       gold_assert(os != NULL);
9147                       gold_assert(os->needs_symtab_index());
9148                       r_sym = os->symtab_index();
9149                       addend = dtp_offset;
9150                     }
9151                   else
9152                     {
9153                       r_type = elfcpp::R_POWERPC_NONE;
9154                       offset -= d_offset;
9155                     }
9156                 }
9157             }
9158           else if (r_type == elfcpp::R_POWERPC_GOT_TPREL16
9159                    || r_type == elfcpp::R_POWERPC_GOT_TPREL16_LO
9160                    || r_type == elfcpp::R_POWERPC_GOT_TPREL16_HI
9161                    || r_type == elfcpp::R_POWERPC_GOT_TPREL16_HA)
9162             {
9163               // First instruction of initial exec sequence.
9164               const bool final = gsym == NULL || gsym->final_value_is_known();
9165               if (this->optimize_tls_ie(final) == tls::TLSOPT_TO_LE)
9166                 {
9167                   if (r_type == elfcpp::R_POWERPC_GOT_TPREL16
9168                       || r_type == elfcpp::R_POWERPC_GOT_TPREL16_LO)
9169                     r_type = elfcpp::R_POWERPC_TPREL16_HA;
9170                   else
9171                     {
9172                       r_type = elfcpp::R_POWERPC_NONE;
9173                       offset -= d_offset;
9174                     }
9175                 }
9176             }
9177           else if ((size == 64 && r_type == elfcpp::R_PPC64_TLSGD)
9178                    || (size == 32 && r_type == elfcpp::R_PPC_TLSGD))
9179             {
9180               // Second instruction of a global dynamic sequence,
9181               // the __tls_get_addr call
9182               const bool final = gsym == NULL || gsym->final_value_is_known();
9183               switch (this->optimize_tls_gd(final))
9184                 {
9185                 case tls::TLSOPT_TO_IE:
9186                   r_type = elfcpp::R_POWERPC_NONE;
9187                   zap_next = true;
9188                   break;
9189                 case tls::TLSOPT_TO_LE:
9190                   r_type = elfcpp::R_POWERPC_TPREL16_LO;
9191                   offset += d_offset;
9192                   zap_next = true;
9193                   break;
9194                 default:
9195                   break;
9196                 }
9197             }
9198           else if ((size == 64 && r_type == elfcpp::R_PPC64_TLSLD)
9199                    || (size == 32 && r_type == elfcpp::R_PPC_TLSLD))
9200             {
9201               // Second instruction of a local dynamic sequence,
9202               // the __tls_get_addr call
9203               if (this->optimize_tls_ld() == tls::TLSOPT_TO_LE)
9204                 {
9205                   const Output_section* os = relinfo->layout->tls_segment()
9206                     ->first_section();
9207                   gold_assert(os != NULL);
9208                   gold_assert(os->needs_symtab_index());
9209                   r_sym = os->symtab_index();
9210                   addend = dtp_offset;
9211                   r_type = elfcpp::R_POWERPC_TPREL16_LO;
9212                   offset += d_offset;
9213                   zap_next = true;
9214                 }
9215             }
9216           else if (r_type == elfcpp::R_POWERPC_TLS)
9217             {
9218               // Second instruction of an initial exec sequence
9219               const bool final = gsym == NULL || gsym->final_value_is_known();
9220               if (this->optimize_tls_ie(final) == tls::TLSOPT_TO_LE)
9221                 {
9222                   r_type = elfcpp::R_POWERPC_TPREL16_LO;
9223                   offset += d_offset;
9224                 }
9225             }
9226         }
9227
9228       reloc_write.put_r_offset(offset);
9229       reloc_write.put_r_info(elfcpp::elf_r_info<size>(r_sym, r_type));
9230       reloc_write.put_r_addend(addend);
9231
9232       pwrite += reloc_size;
9233     }
9234
9235   gold_assert(static_cast<section_size_type>(pwrite - reloc_view)
9236               == reloc_view_size);
9237 }
9238
9239 // Return the value to use for a dynamic symbol which requires special
9240 // treatment.  This is how we support equality comparisons of function
9241 // pointers across shared library boundaries, as described in the
9242 // processor specific ABI supplement.
9243
9244 template<int size, bool big_endian>
9245 uint64_t
9246 Target_powerpc<size, big_endian>::do_dynsym_value(const Symbol* gsym) const
9247 {
9248   if (size == 32)
9249     {
9250       gold_assert(gsym->is_from_dynobj() && gsym->has_plt_offset());
9251       for (typename Stub_tables::const_iterator p = this->stub_tables_.begin();
9252            p != this->stub_tables_.end();
9253            ++p)
9254         {
9255           Address off = (*p)->find_plt_call_entry(gsym);
9256           if (off != invalid_address)
9257             return (*p)->stub_address() + off;
9258         }
9259     }
9260   else if (this->abiversion() >= 2)
9261     {
9262       Address off = this->glink_section()->find_global_entry(gsym);
9263       if (off != invalid_address)
9264         return this->glink_section()->global_entry_address() + off;
9265     }
9266   gold_unreachable();
9267 }
9268
9269 // Return the PLT address to use for a local symbol.
9270 template<int size, bool big_endian>
9271 uint64_t
9272 Target_powerpc<size, big_endian>::do_plt_address_for_local(
9273     const Relobj* object,
9274     unsigned int symndx) const
9275 {
9276   if (size == 32)
9277     {
9278       const Sized_relobj<size, big_endian>* relobj
9279         = static_cast<const Sized_relobj<size, big_endian>*>(object);
9280       for (typename Stub_tables::const_iterator p = this->stub_tables_.begin();
9281            p != this->stub_tables_.end();
9282            ++p)
9283         {
9284           Address off = (*p)->find_plt_call_entry(relobj->sized_relobj(),
9285                                                   symndx);
9286           if (off != invalid_address)
9287             return (*p)->stub_address() + off;
9288         }
9289     }
9290   gold_unreachable();
9291 }
9292
9293 // Return the PLT address to use for a global symbol.
9294 template<int size, bool big_endian>
9295 uint64_t
9296 Target_powerpc<size, big_endian>::do_plt_address_for_global(
9297     const Symbol* gsym) const
9298 {
9299   if (size == 32)
9300     {
9301       for (typename Stub_tables::const_iterator p = this->stub_tables_.begin();
9302            p != this->stub_tables_.end();
9303            ++p)
9304         {
9305           Address off = (*p)->find_plt_call_entry(gsym);
9306           if (off != invalid_address)
9307             return (*p)->stub_address() + off;
9308         }
9309     }
9310   else if (this->abiversion() >= 2)
9311     {
9312       Address off = this->glink_section()->find_global_entry(gsym);
9313       if (off != invalid_address)
9314         return this->glink_section()->global_entry_address() + off;
9315     }
9316   gold_unreachable();
9317 }
9318
9319 // Return the offset to use for the GOT_INDX'th got entry which is
9320 // for a local tls symbol specified by OBJECT, SYMNDX.
9321 template<int size, bool big_endian>
9322 int64_t
9323 Target_powerpc<size, big_endian>::do_tls_offset_for_local(
9324     const Relobj* object,
9325     unsigned int symndx,
9326     unsigned int got_indx) const
9327 {
9328   const Powerpc_relobj<size, big_endian>* ppc_object
9329     = static_cast<const Powerpc_relobj<size, big_endian>*>(object);
9330   if (ppc_object->local_symbol(symndx)->is_tls_symbol())
9331     {
9332       for (Got_type got_type = GOT_TYPE_TLSGD;
9333            got_type <= GOT_TYPE_TPREL;
9334            got_type = Got_type(got_type + 1))
9335         if (ppc_object->local_has_got_offset(symndx, got_type))
9336           {
9337             unsigned int off = ppc_object->local_got_offset(symndx, got_type);
9338             if (got_type == GOT_TYPE_TLSGD)
9339               off += size / 8;
9340             if (off == got_indx * (size / 8))
9341               {
9342                 if (got_type == GOT_TYPE_TPREL)
9343                   return -tp_offset;
9344                 else
9345                   return -dtp_offset;
9346               }
9347           }
9348     }
9349   gold_unreachable();
9350 }
9351
9352 // Return the offset to use for the GOT_INDX'th got entry which is
9353 // for global tls symbol GSYM.
9354 template<int size, bool big_endian>
9355 int64_t
9356 Target_powerpc<size, big_endian>::do_tls_offset_for_global(
9357     Symbol* gsym,
9358     unsigned int got_indx) const
9359 {
9360   if (gsym->type() == elfcpp::STT_TLS)
9361     {
9362       for (Got_type got_type = GOT_TYPE_TLSGD;
9363            got_type <= GOT_TYPE_TPREL;
9364            got_type = Got_type(got_type + 1))
9365         if (gsym->has_got_offset(got_type))
9366           {
9367             unsigned int off = gsym->got_offset(got_type);
9368             if (got_type == GOT_TYPE_TLSGD)
9369               off += size / 8;
9370             if (off == got_indx * (size / 8))
9371               {
9372                 if (got_type == GOT_TYPE_TPREL)
9373                   return -tp_offset;
9374                 else
9375                   return -dtp_offset;
9376               }
9377           }
9378     }
9379   gold_unreachable();
9380 }
9381
9382 // The selector for powerpc object files.
9383
9384 template<int size, bool big_endian>
9385 class Target_selector_powerpc : public Target_selector
9386 {
9387 public:
9388   Target_selector_powerpc()
9389     : Target_selector(size == 64 ? elfcpp::EM_PPC64 : elfcpp::EM_PPC,
9390                       size, big_endian,
9391                       (size == 64
9392                        ? (big_endian ? "elf64-powerpc" : "elf64-powerpcle")
9393                        : (big_endian ? "elf32-powerpc" : "elf32-powerpcle")),
9394                       (size == 64
9395                        ? (big_endian ? "elf64ppc" : "elf64lppc")
9396                        : (big_endian ? "elf32ppc" : "elf32lppc")))
9397   { }
9398
9399   virtual Target*
9400   do_instantiate_target()
9401   { return new Target_powerpc<size, big_endian>(); }
9402 };
9403
9404 Target_selector_powerpc<32, true> target_selector_ppc32;
9405 Target_selector_powerpc<32, false> target_selector_ppc32le;
9406 Target_selector_powerpc<64, true> target_selector_ppc64;
9407 Target_selector_powerpc<64, false> target_selector_ppc64le;
9408
9409 // Instantiate these constants for -O0
9410 template<int size, bool big_endian>
9411 const int Output_data_glink<size, big_endian>::pltresolve_size;
9412 template<int size, bool big_endian>
9413 const typename Output_data_glink<size, big_endian>::Address
9414   Output_data_glink<size, big_endian>::invalid_address;
9415 template<int size, bool big_endian>
9416 const typename Stub_table<size, big_endian>::Address
9417   Stub_table<size, big_endian>::invalid_address;
9418 template<int size, bool big_endian>
9419 const typename Target_powerpc<size, big_endian>::Address
9420   Target_powerpc<size, big_endian>::invalid_address;
9421
9422 } // End anonymous namespace.