[WinCOFF] Add support for the .safeseh directive
[oota-llvm.git] / include / llvm / MC / MCAssembler.h
1 //===- MCAssembler.h - Object File Generation -------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #ifndef LLVM_MC_MCASSEMBLER_H
11 #define LLVM_MC_MCASSEMBLER_H
12
13 #include "llvm/ADT/DenseMap.h"
14 #include "llvm/ADT/DenseSet.h"
15 #include "llvm/ADT/SetVector.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/ilist.h"
19 #include "llvm/ADT/ilist_node.h"
20 #include "llvm/ADT/iterator.h"
21 #include "llvm/MC/MCDirectives.h"
22 #include "llvm/MC/MCFixup.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCLinkerOptimizationHint.h"
25 #include "llvm/MC/MCSection.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/DataTypes.h"
30 #include <algorithm>
31 #include <vector> // FIXME: Shouldn't be needed.
32
33 namespace llvm {
34 class raw_ostream;
35 class MCAsmLayout;
36 class MCAssembler;
37 class MCContext;
38 class MCCodeEmitter;
39 class MCExpr;
40 class MCFragment;
41 class MCObjectWriter;
42 class MCSection;
43 class MCSubtargetInfo;
44 class MCValue;
45 class MCAsmBackend;
46
47 class MCFragment : public ilist_node<MCFragment> {
48   friend class MCAsmLayout;
49
50   MCFragment(const MCFragment &) = delete;
51   void operator=(const MCFragment &) = delete;
52
53 public:
54   enum FragmentType {
55     FT_Align,
56     FT_Data,
57     FT_CompactEncodedInst,
58     FT_Fill,
59     FT_Relaxable,
60     FT_Org,
61     FT_Dwarf,
62     FT_DwarfFrame,
63     FT_LEB,
64     FT_SafeSEH
65   };
66
67 private:
68   FragmentType Kind;
69
70   /// The data for the section this fragment is in.
71   MCSection *Parent;
72
73   /// Atom - The atom this fragment is in, as represented by it's defining
74   /// symbol.
75   const MCSymbol *Atom;
76
77   /// \name Assembler Backend Data
78   /// @{
79   //
80   // FIXME: This could all be kept private to the assembler implementation.
81
82   /// Offset - The offset of this fragment in its section. This is ~0 until
83   /// initialized.
84   uint64_t Offset;
85
86   /// LayoutOrder - The layout order of this fragment.
87   unsigned LayoutOrder;
88
89   /// @}
90
91 protected:
92   MCFragment(FragmentType Kind, MCSection *Parent = nullptr);
93
94 public:
95   // Only for sentinel.
96   MCFragment();
97   virtual ~MCFragment();
98
99   FragmentType getKind() const { return Kind; }
100
101   MCSection *getParent() const { return Parent; }
102   void setParent(MCSection *Value) { Parent = Value; }
103
104   const MCSymbol *getAtom() const { return Atom; }
105   void setAtom(const MCSymbol *Value) { Atom = Value; }
106
107   unsigned getLayoutOrder() const { return LayoutOrder; }
108   void setLayoutOrder(unsigned Value) { LayoutOrder = Value; }
109
110   /// \brief Does this fragment have instructions emitted into it? By default
111   /// this is false, but specific fragment types may set it to true.
112   virtual bool hasInstructions() const { return false; }
113
114   /// \brief Should this fragment be placed at the end of an aligned bundle?
115   virtual bool alignToBundleEnd() const { return false; }
116   virtual void setAlignToBundleEnd(bool V) {}
117
118   /// \brief Get the padding size that must be inserted before this fragment.
119   /// Used for bundling. By default, no padding is inserted.
120   /// Note that padding size is restricted to 8 bits. This is an optimization
121   /// to reduce the amount of space used for each fragment. In practice, larger
122   /// padding should never be required.
123   virtual uint8_t getBundlePadding() const { return 0; }
124
125   /// \brief Set the padding size for this fragment. By default it's a no-op,
126   /// and only some fragments have a meaningful implementation.
127   virtual void setBundlePadding(uint8_t N) {}
128
129   void dump();
130 };
131
132 /// Interface implemented by fragments that contain encoded instructions and/or
133 /// data.
134 ///
135 class MCEncodedFragment : public MCFragment {
136   virtual void anchor();
137
138   uint8_t BundlePadding;
139
140 public:
141   MCEncodedFragment(MCFragment::FragmentType FType, MCSection *Sec = nullptr)
142       : MCFragment(FType, Sec), BundlePadding(0) {}
143   ~MCEncodedFragment() override;
144
145   virtual SmallVectorImpl<char> &getContents() = 0;
146   virtual const SmallVectorImpl<char> &getContents() const = 0;
147
148   uint8_t getBundlePadding() const override { return BundlePadding; }
149
150   void setBundlePadding(uint8_t N) override { BundlePadding = N; }
151
152   static bool classof(const MCFragment *F) {
153     MCFragment::FragmentType Kind = F->getKind();
154     switch (Kind) {
155     default:
156       return false;
157     case MCFragment::FT_Relaxable:
158     case MCFragment::FT_CompactEncodedInst:
159     case MCFragment::FT_Data:
160       return true;
161     }
162   }
163 };
164
165 /// Interface implemented by fragments that contain encoded instructions and/or
166 /// data and also have fixups registered.
167 ///
168 class MCEncodedFragmentWithFixups : public MCEncodedFragment {
169   void anchor() override;
170
171 public:
172   MCEncodedFragmentWithFixups(MCFragment::FragmentType FType,
173                               MCSection *Sec = nullptr)
174       : MCEncodedFragment(FType, Sec) {}
175
176   ~MCEncodedFragmentWithFixups() override;
177
178   typedef SmallVectorImpl<MCFixup>::const_iterator const_fixup_iterator;
179   typedef SmallVectorImpl<MCFixup>::iterator fixup_iterator;
180
181   virtual SmallVectorImpl<MCFixup> &getFixups() = 0;
182   virtual const SmallVectorImpl<MCFixup> &getFixups() const = 0;
183
184   virtual fixup_iterator fixup_begin() = 0;
185   virtual const_fixup_iterator fixup_begin() const = 0;
186   virtual fixup_iterator fixup_end() = 0;
187   virtual const_fixup_iterator fixup_end() const = 0;
188
189   static bool classof(const MCFragment *F) {
190     MCFragment::FragmentType Kind = F->getKind();
191     return Kind == MCFragment::FT_Relaxable || Kind == MCFragment::FT_Data;
192   }
193 };
194
195 /// Fragment for data and encoded instructions.
196 ///
197 class MCDataFragment : public MCEncodedFragmentWithFixups {
198   void anchor() override;
199
200   /// \brief Does this fragment contain encoded instructions anywhere in it?
201   bool HasInstructions;
202
203   /// \brief Should this fragment be aligned to the end of a bundle?
204   bool AlignToBundleEnd;
205
206   SmallVector<char, 32> Contents;
207
208   /// Fixups - The list of fixups in this fragment.
209   SmallVector<MCFixup, 4> Fixups;
210
211 public:
212   MCDataFragment(MCSection *Sec = nullptr)
213       : MCEncodedFragmentWithFixups(FT_Data, Sec), HasInstructions(false),
214         AlignToBundleEnd(false) {}
215
216   SmallVectorImpl<char> &getContents() override { return Contents; }
217   const SmallVectorImpl<char> &getContents() const override { return Contents; }
218
219   SmallVectorImpl<MCFixup> &getFixups() override { return Fixups; }
220
221   const SmallVectorImpl<MCFixup> &getFixups() const override { return Fixups; }
222
223   bool hasInstructions() const override { return HasInstructions; }
224   virtual void setHasInstructions(bool V) { HasInstructions = V; }
225
226   bool alignToBundleEnd() const override { return AlignToBundleEnd; }
227   void setAlignToBundleEnd(bool V) override { AlignToBundleEnd = V; }
228
229   fixup_iterator fixup_begin() override { return Fixups.begin(); }
230   const_fixup_iterator fixup_begin() const override { return Fixups.begin(); }
231
232   fixup_iterator fixup_end() override { return Fixups.end(); }
233   const_fixup_iterator fixup_end() const override { return Fixups.end(); }
234
235   static bool classof(const MCFragment *F) {
236     return F->getKind() == MCFragment::FT_Data;
237   }
238 };
239
240 /// This is a compact (memory-size-wise) fragment for holding an encoded
241 /// instruction (non-relaxable) that has no fixups registered. When applicable,
242 /// it can be used instead of MCDataFragment and lead to lower memory
243 /// consumption.
244 ///
245 class MCCompactEncodedInstFragment : public MCEncodedFragment {
246   void anchor() override;
247
248   /// \brief Should this fragment be aligned to the end of a bundle?
249   bool AlignToBundleEnd;
250
251   SmallVector<char, 4> Contents;
252
253 public:
254   MCCompactEncodedInstFragment(MCSection *Sec = nullptr)
255       : MCEncodedFragment(FT_CompactEncodedInst, Sec), AlignToBundleEnd(false) {
256   }
257
258   bool hasInstructions() const override { return true; }
259
260   SmallVectorImpl<char> &getContents() override { return Contents; }
261   const SmallVectorImpl<char> &getContents() const override { return Contents; }
262
263   bool alignToBundleEnd() const override { return AlignToBundleEnd; }
264   void setAlignToBundleEnd(bool V) override { AlignToBundleEnd = V; }
265
266   static bool classof(const MCFragment *F) {
267     return F->getKind() == MCFragment::FT_CompactEncodedInst;
268   }
269 };
270
271 /// A relaxable fragment holds on to its MCInst, since it may need to be
272 /// relaxed during the assembler layout and relaxation stage.
273 ///
274 class MCRelaxableFragment : public MCEncodedFragmentWithFixups {
275   void anchor() override;
276
277   /// Inst - The instruction this is a fragment for.
278   MCInst Inst;
279
280   /// STI - The MCSubtargetInfo in effect when the instruction was encoded.
281   /// Keep a copy instead of a reference to make sure that updates to STI
282   /// in the assembler are not seen here.
283   const MCSubtargetInfo STI;
284
285   /// Contents - Binary data for the currently encoded instruction.
286   SmallVector<char, 8> Contents;
287
288   /// Fixups - The list of fixups in this fragment.
289   SmallVector<MCFixup, 1> Fixups;
290
291 public:
292   MCRelaxableFragment(const MCInst &Inst, const MCSubtargetInfo &STI,
293                       MCSection *Sec = nullptr)
294       : MCEncodedFragmentWithFixups(FT_Relaxable, Sec), Inst(Inst), STI(STI) {}
295
296   SmallVectorImpl<char> &getContents() override { return Contents; }
297   const SmallVectorImpl<char> &getContents() const override { return Contents; }
298
299   const MCInst &getInst() const { return Inst; }
300   void setInst(const MCInst &Value) { Inst = Value; }
301
302   const MCSubtargetInfo &getSubtargetInfo() { return STI; }
303
304   SmallVectorImpl<MCFixup> &getFixups() override { return Fixups; }
305
306   const SmallVectorImpl<MCFixup> &getFixups() const override { return Fixups; }
307
308   bool hasInstructions() const override { return true; }
309
310   fixup_iterator fixup_begin() override { return Fixups.begin(); }
311   const_fixup_iterator fixup_begin() const override { return Fixups.begin(); }
312
313   fixup_iterator fixup_end() override { return Fixups.end(); }
314   const_fixup_iterator fixup_end() const override { return Fixups.end(); }
315
316   static bool classof(const MCFragment *F) {
317     return F->getKind() == MCFragment::FT_Relaxable;
318   }
319 };
320
321 class MCAlignFragment : public MCFragment {
322   virtual void anchor();
323
324   /// Alignment - The alignment to ensure, in bytes.
325   unsigned Alignment;
326
327   /// Value - Value to use for filling padding bytes.
328   int64_t Value;
329
330   /// ValueSize - The size of the integer (in bytes) of \p Value.
331   unsigned ValueSize;
332
333   /// MaxBytesToEmit - The maximum number of bytes to emit; if the alignment
334   /// cannot be satisfied in this width then this fragment is ignored.
335   unsigned MaxBytesToEmit;
336
337   /// EmitNops - Flag to indicate that (optimal) NOPs should be emitted instead
338   /// of using the provided value. The exact interpretation of this flag is
339   /// target dependent.
340   bool EmitNops : 1;
341
342 public:
343   MCAlignFragment(unsigned Alignment, int64_t Value, unsigned ValueSize,
344                   unsigned MaxBytesToEmit, MCSection *Sec = nullptr)
345       : MCFragment(FT_Align, Sec), Alignment(Alignment), Value(Value),
346         ValueSize(ValueSize), MaxBytesToEmit(MaxBytesToEmit), EmitNops(false) {}
347
348   /// \name Accessors
349   /// @{
350
351   unsigned getAlignment() const { return Alignment; }
352
353   int64_t getValue() const { return Value; }
354
355   unsigned getValueSize() const { return ValueSize; }
356
357   unsigned getMaxBytesToEmit() const { return MaxBytesToEmit; }
358
359   bool hasEmitNops() const { return EmitNops; }
360   void setEmitNops(bool Value) { EmitNops = Value; }
361
362   /// @}
363
364   static bool classof(const MCFragment *F) {
365     return F->getKind() == MCFragment::FT_Align;
366   }
367 };
368
369 class MCFillFragment : public MCFragment {
370   virtual void anchor();
371
372   /// Value - Value to use for filling bytes.
373   int64_t Value;
374
375   /// ValueSize - The size (in bytes) of \p Value to use when filling, or 0 if
376   /// this is a virtual fill fragment.
377   unsigned ValueSize;
378
379   /// Size - The number of bytes to insert.
380   uint64_t Size;
381
382 public:
383   MCFillFragment(int64_t Value, unsigned ValueSize, uint64_t Size,
384                  MCSection *Sec = nullptr)
385       : MCFragment(FT_Fill, Sec), Value(Value), ValueSize(ValueSize),
386         Size(Size) {
387     assert((!ValueSize || (Size % ValueSize) == 0) &&
388            "Fill size must be a multiple of the value size!");
389   }
390
391   /// \name Accessors
392   /// @{
393
394   int64_t getValue() const { return Value; }
395
396   unsigned getValueSize() const { return ValueSize; }
397
398   uint64_t getSize() const { return Size; }
399
400   /// @}
401
402   static bool classof(const MCFragment *F) {
403     return F->getKind() == MCFragment::FT_Fill;
404   }
405 };
406
407 class MCOrgFragment : public MCFragment {
408   virtual void anchor();
409
410   /// Offset - The offset this fragment should start at.
411   const MCExpr *Offset;
412
413   /// Value - Value to use for filling bytes.
414   int8_t Value;
415
416 public:
417   MCOrgFragment(const MCExpr &Offset, int8_t Value, MCSection *Sec = nullptr)
418       : MCFragment(FT_Org, Sec), Offset(&Offset), Value(Value) {}
419
420   /// \name Accessors
421   /// @{
422
423   const MCExpr &getOffset() const { return *Offset; }
424
425   uint8_t getValue() const { return Value; }
426
427   /// @}
428
429   static bool classof(const MCFragment *F) {
430     return F->getKind() == MCFragment::FT_Org;
431   }
432 };
433
434 class MCLEBFragment : public MCFragment {
435   virtual void anchor();
436
437   /// Value - The value this fragment should contain.
438   const MCExpr *Value;
439
440   /// IsSigned - True if this is a sleb128, false if uleb128.
441   bool IsSigned;
442
443   SmallString<8> Contents;
444
445 public:
446   MCLEBFragment(const MCExpr &Value_, bool IsSigned_, MCSection *Sec = nullptr)
447       : MCFragment(FT_LEB, Sec), Value(&Value_), IsSigned(IsSigned_) {
448     Contents.push_back(0);
449   }
450
451   /// \name Accessors
452   /// @{
453
454   const MCExpr &getValue() const { return *Value; }
455
456   bool isSigned() const { return IsSigned; }
457
458   SmallString<8> &getContents() { return Contents; }
459   const SmallString<8> &getContents() const { return Contents; }
460
461   /// @}
462
463   static bool classof(const MCFragment *F) {
464     return F->getKind() == MCFragment::FT_LEB;
465   }
466 };
467
468 class MCDwarfLineAddrFragment : public MCFragment {
469   virtual void anchor();
470
471   /// LineDelta - the value of the difference between the two line numbers
472   /// between two .loc dwarf directives.
473   int64_t LineDelta;
474
475   /// AddrDelta - The expression for the difference of the two symbols that
476   /// make up the address delta between two .loc dwarf directives.
477   const MCExpr *AddrDelta;
478
479   SmallString<8> Contents;
480
481 public:
482   MCDwarfLineAddrFragment(int64_t LineDelta, const MCExpr &AddrDelta,
483                           MCSection *Sec = nullptr)
484       : MCFragment(FT_Dwarf, Sec), LineDelta(LineDelta), AddrDelta(&AddrDelta) {
485     Contents.push_back(0);
486   }
487
488   /// \name Accessors
489   /// @{
490
491   int64_t getLineDelta() const { return LineDelta; }
492
493   const MCExpr &getAddrDelta() const { return *AddrDelta; }
494
495   SmallString<8> &getContents() { return Contents; }
496   const SmallString<8> &getContents() const { return Contents; }
497
498   /// @}
499
500   static bool classof(const MCFragment *F) {
501     return F->getKind() == MCFragment::FT_Dwarf;
502   }
503 };
504
505 class MCDwarfCallFrameFragment : public MCFragment {
506   virtual void anchor();
507
508   /// AddrDelta - The expression for the difference of the two symbols that
509   /// make up the address delta between two .cfi_* dwarf directives.
510   const MCExpr *AddrDelta;
511
512   SmallString<8> Contents;
513
514 public:
515   MCDwarfCallFrameFragment(const MCExpr &AddrDelta, MCSection *Sec = nullptr)
516       : MCFragment(FT_DwarfFrame, Sec), AddrDelta(&AddrDelta) {
517     Contents.push_back(0);
518   }
519
520   /// \name Accessors
521   /// @{
522
523   const MCExpr &getAddrDelta() const { return *AddrDelta; }
524
525   SmallString<8> &getContents() { return Contents; }
526   const SmallString<8> &getContents() const { return Contents; }
527
528   /// @}
529
530   static bool classof(const MCFragment *F) {
531     return F->getKind() == MCFragment::FT_DwarfFrame;
532   }
533 };
534
535 class MCSafeSEHFragment : public MCFragment {
536   virtual void anchor();
537
538   const MCSymbol *Sym;
539
540 public:
541   MCSafeSEHFragment(const MCSymbol *Sym, MCSection *Sec = nullptr)
542       : MCFragment(FT_SafeSEH, Sec), Sym(Sym) {}
543
544   /// \name Accessors
545   /// @{
546
547   const MCSymbol *getSymbol() { return Sym; }
548   const MCSymbol *getSymbol() const { return Sym; }
549
550   /// @}
551
552   static bool classof(const MCFragment *F) {
553     return F->getKind() == MCFragment::FT_SafeSEH;
554   }
555 };
556
557 // FIXME: This really doesn't belong here. See comments below.
558 struct IndirectSymbolData {
559   MCSymbol *Symbol;
560   MCSection *Section;
561 };
562
563 // FIXME: Ditto this. Purely so the Streamer and the ObjectWriter can talk
564 // to one another.
565 struct DataRegionData {
566   // This enum should be kept in sync w/ the mach-o definition in
567   // llvm/Object/MachOFormat.h.
568   enum KindTy { Data = 1, JumpTable8, JumpTable16, JumpTable32 } Kind;
569   MCSymbol *Start;
570   MCSymbol *End;
571 };
572
573 class MCAssembler {
574   friend class MCAsmLayout;
575
576 public:
577   typedef SetVector<MCSection *> SectionListType;
578   typedef std::vector<const MCSymbol *> SymbolDataListType;
579
580   typedef pointee_iterator<SectionListType::const_iterator> const_iterator;
581   typedef pointee_iterator<SectionListType::iterator> iterator;
582
583   typedef pointee_iterator<SymbolDataListType::const_iterator>
584   const_symbol_iterator;
585   typedef pointee_iterator<SymbolDataListType::iterator> symbol_iterator;
586
587   typedef iterator_range<symbol_iterator> symbol_range;
588   typedef iterator_range<const_symbol_iterator> const_symbol_range;
589
590   typedef std::vector<IndirectSymbolData>::const_iterator
591       const_indirect_symbol_iterator;
592   typedef std::vector<IndirectSymbolData>::iterator indirect_symbol_iterator;
593
594   typedef std::vector<DataRegionData>::const_iterator
595       const_data_region_iterator;
596   typedef std::vector<DataRegionData>::iterator data_region_iterator;
597
598   /// MachO specific deployment target version info.
599   // A Major version of 0 indicates that no version information was supplied
600   // and so the corresponding load command should not be emitted.
601   typedef struct {
602     MCVersionMinType Kind;
603     unsigned Major;
604     unsigned Minor;
605     unsigned Update;
606   } VersionMinInfoType;
607
608 private:
609   MCAssembler(const MCAssembler &) = delete;
610   void operator=(const MCAssembler &) = delete;
611
612   MCContext &Context;
613
614   MCAsmBackend &Backend;
615
616   MCCodeEmitter &Emitter;
617
618   MCObjectWriter &Writer;
619
620   raw_ostream &OS;
621
622   SectionListType Sections;
623
624   SymbolDataListType Symbols;
625
626   DenseSet<const MCSymbol *> LocalsUsedInReloc;
627
628   std::vector<IndirectSymbolData> IndirectSymbols;
629
630   std::vector<DataRegionData> DataRegions;
631
632   /// The list of linker options to propagate into the object file.
633   std::vector<std::vector<std::string>> LinkerOptions;
634
635   /// List of declared file names
636   std::vector<std::string> FileNames;
637
638   /// The set of function symbols for which a .thumb_func directive has
639   /// been seen.
640   //
641   // FIXME: We really would like this in target specific code rather than
642   // here. Maybe when the relocation stuff moves to target specific,
643   // this can go with it? The streamer would need some target specific
644   // refactoring too.
645   mutable SmallPtrSet<const MCSymbol *, 64> ThumbFuncs;
646
647   /// \brief The bundle alignment size currently set in the assembler.
648   ///
649   /// By default it's 0, which means bundling is disabled.
650   unsigned BundleAlignSize;
651
652   unsigned RelaxAll : 1;
653   unsigned SubsectionsViaSymbols : 1;
654
655   /// ELF specific e_header flags
656   // It would be good if there were an MCELFAssembler class to hold this.
657   // ELF header flags are used both by the integrated and standalone assemblers.
658   // Access to the flags is necessary in cases where assembler directives affect
659   // which flags to be set.
660   unsigned ELFHeaderEFlags;
661
662   /// Used to communicate Linker Optimization Hint information between
663   /// the Streamer and the .o writer
664   MCLOHContainer LOHContainer;
665
666   VersionMinInfoType VersionMinInfo;
667
668 private:
669   /// Evaluate a fixup to a relocatable expression and the value which should be
670   /// placed into the fixup.
671   ///
672   /// \param Layout The layout to use for evaluation.
673   /// \param Fixup The fixup to evaluate.
674   /// \param DF The fragment the fixup is inside.
675   /// \param Target [out] On return, the relocatable expression the fixup
676   /// evaluates to.
677   /// \param Value [out] On return, the value of the fixup as currently laid
678   /// out.
679   /// \return Whether the fixup value was fully resolved. This is true if the
680   /// \p Value result is fixed, otherwise the value may change due to
681   /// relocation.
682   bool evaluateFixup(const MCAsmLayout &Layout, const MCFixup &Fixup,
683                      const MCFragment *DF, MCValue &Target,
684                      uint64_t &Value) const;
685
686   /// Check whether a fixup can be satisfied, or whether it needs to be relaxed
687   /// (increased in size, in order to hold its value correctly).
688   bool fixupNeedsRelaxation(const MCFixup &Fixup, const MCRelaxableFragment *DF,
689                             const MCAsmLayout &Layout) const;
690
691   /// Check whether the given fragment needs relaxation.
692   bool fragmentNeedsRelaxation(const MCRelaxableFragment *IF,
693                                const MCAsmLayout &Layout) const;
694
695   /// \brief Perform one layout iteration and return true if any offsets
696   /// were adjusted.
697   bool layoutOnce(MCAsmLayout &Layout);
698
699   /// \brief Perform one layout iteration of the given section and return true
700   /// if any offsets were adjusted.
701   bool layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec);
702
703   bool relaxInstruction(MCAsmLayout &Layout, MCRelaxableFragment &IF);
704
705   bool relaxLEB(MCAsmLayout &Layout, MCLEBFragment &IF);
706
707   bool relaxDwarfLineAddr(MCAsmLayout &Layout, MCDwarfLineAddrFragment &DF);
708   bool relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
709                                    MCDwarfCallFrameFragment &DF);
710
711   /// finishLayout - Finalize a layout, including fragment lowering.
712   void finishLayout(MCAsmLayout &Layout);
713
714   std::pair<uint64_t, bool> handleFixup(const MCAsmLayout &Layout,
715                                         MCFragment &F, const MCFixup &Fixup);
716
717 public:
718   void addLocalUsedInReloc(const MCSymbol &Sym);
719   bool isLocalUsedInReloc(const MCSymbol &Sym) const;
720
721   /// Compute the effective fragment size assuming it is laid out at the given
722   /// \p SectionAddress and \p FragmentOffset.
723   uint64_t computeFragmentSize(const MCAsmLayout &Layout,
724                                const MCFragment &F) const;
725
726   /// Find the symbol which defines the atom containing the given symbol, or
727   /// null if there is no such symbol.
728   const MCSymbol *getAtom(const MCSymbol &S) const;
729
730   /// Check whether a particular symbol is visible to the linker and is required
731   /// in the symbol table, or whether it can be discarded by the assembler. This
732   /// also effects whether the assembler treats the label as potentially
733   /// defining a separate atom.
734   bool isSymbolLinkerVisible(const MCSymbol &SD) const;
735
736   /// Emit the section contents using the given object writer.
737   void writeSectionData(const MCSection *Section,
738                         const MCAsmLayout &Layout) const;
739
740   /// Check whether a given symbol has been flagged with .thumb_func.
741   bool isThumbFunc(const MCSymbol *Func) const;
742
743   /// Flag a function symbol as the target of a .thumb_func directive.
744   void setIsThumbFunc(const MCSymbol *Func) { ThumbFuncs.insert(Func); }
745
746   /// ELF e_header flags
747   unsigned getELFHeaderEFlags() const { return ELFHeaderEFlags; }
748   void setELFHeaderEFlags(unsigned Flags) { ELFHeaderEFlags = Flags; }
749
750   /// MachO deployment target version information.
751   const VersionMinInfoType &getVersionMinInfo() const { return VersionMinInfo; }
752   void setVersionMinInfo(MCVersionMinType Kind, unsigned Major, unsigned Minor,
753                          unsigned Update) {
754     VersionMinInfo.Kind = Kind;
755     VersionMinInfo.Major = Major;
756     VersionMinInfo.Minor = Minor;
757     VersionMinInfo.Update = Update;
758   }
759
760 public:
761   /// Construct a new assembler instance.
762   ///
763   /// \param OS The stream to output to.
764   //
765   // FIXME: How are we going to parameterize this? Two obvious options are stay
766   // concrete and require clients to pass in a target like object. The other
767   // option is to make this abstract, and have targets provide concrete
768   // implementations as we do with AsmParser.
769   MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
770               MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
771               raw_ostream &OS);
772   ~MCAssembler();
773
774   /// Reuse an assembler instance
775   ///
776   void reset();
777
778   MCContext &getContext() const { return Context; }
779
780   MCAsmBackend &getBackend() const { return Backend; }
781
782   MCCodeEmitter &getEmitter() const { return Emitter; }
783
784   MCObjectWriter &getWriter() const { return Writer; }
785
786   /// Finish - Do final processing and write the object to the output stream.
787   /// \p Writer is used for custom object writer (as the MCJIT does),
788   /// if not specified it is automatically created from backend.
789   void Finish();
790
791   // FIXME: This does not belong here.
792   bool getSubsectionsViaSymbols() const { return SubsectionsViaSymbols; }
793   void setSubsectionsViaSymbols(bool Value) { SubsectionsViaSymbols = Value; }
794
795   bool getRelaxAll() const { return RelaxAll; }
796   void setRelaxAll(bool Value) { RelaxAll = Value; }
797
798   bool isBundlingEnabled() const { return BundleAlignSize != 0; }
799
800   unsigned getBundleAlignSize() const { return BundleAlignSize; }
801
802   void setBundleAlignSize(unsigned Size) {
803     assert((Size == 0 || !(Size & (Size - 1))) &&
804            "Expect a power-of-two bundle align size");
805     BundleAlignSize = Size;
806   }
807
808   /// \name Section List Access
809   /// @{
810
811   iterator begin() { return Sections.begin(); }
812   const_iterator begin() const { return Sections.begin(); }
813
814   iterator end() { return Sections.end(); }
815   const_iterator end() const { return Sections.end(); }
816
817   size_t size() const { return Sections.size(); }
818
819   /// @}
820   /// \name Symbol List Access
821   /// @{
822   symbol_iterator symbol_begin() { return Symbols.begin(); }
823   const_symbol_iterator symbol_begin() const { return Symbols.begin(); }
824
825   symbol_iterator symbol_end() { return Symbols.end(); }
826   const_symbol_iterator symbol_end() const { return Symbols.end(); }
827
828   symbol_range symbols() { return make_range(symbol_begin(), symbol_end()); }
829   const_symbol_range symbols() const {
830     return make_range(symbol_begin(), symbol_end());
831   }
832
833   size_t symbol_size() const { return Symbols.size(); }
834
835   /// @}
836   /// \name Indirect Symbol List Access
837   /// @{
838
839   // FIXME: This is a total hack, this should not be here. Once things are
840   // factored so that the streamer has direct access to the .o writer, it can
841   // disappear.
842   std::vector<IndirectSymbolData> &getIndirectSymbols() {
843     return IndirectSymbols;
844   }
845
846   indirect_symbol_iterator indirect_symbol_begin() {
847     return IndirectSymbols.begin();
848   }
849   const_indirect_symbol_iterator indirect_symbol_begin() const {
850     return IndirectSymbols.begin();
851   }
852
853   indirect_symbol_iterator indirect_symbol_end() {
854     return IndirectSymbols.end();
855   }
856   const_indirect_symbol_iterator indirect_symbol_end() const {
857     return IndirectSymbols.end();
858   }
859
860   size_t indirect_symbol_size() const { return IndirectSymbols.size(); }
861
862   /// @}
863   /// \name Linker Option List Access
864   /// @{
865
866   std::vector<std::vector<std::string>> &getLinkerOptions() {
867     return LinkerOptions;
868   }
869
870   /// @}
871   /// \name Data Region List Access
872   /// @{
873
874   // FIXME: This is a total hack, this should not be here. Once things are
875   // factored so that the streamer has direct access to the .o writer, it can
876   // disappear.
877   std::vector<DataRegionData> &getDataRegions() { return DataRegions; }
878
879   data_region_iterator data_region_begin() { return DataRegions.begin(); }
880   const_data_region_iterator data_region_begin() const {
881     return DataRegions.begin();
882   }
883
884   data_region_iterator data_region_end() { return DataRegions.end(); }
885   const_data_region_iterator data_region_end() const {
886     return DataRegions.end();
887   }
888
889   size_t data_region_size() const { return DataRegions.size(); }
890
891   /// @}
892   /// \name Data Region List Access
893   /// @{
894
895   // FIXME: This is a total hack, this should not be here. Once things are
896   // factored so that the streamer has direct access to the .o writer, it can
897   // disappear.
898   MCLOHContainer &getLOHContainer() { return LOHContainer; }
899   const MCLOHContainer &getLOHContainer() const {
900     return const_cast<MCAssembler *>(this)->getLOHContainer();
901   }
902   /// @}
903   /// \name Backend Data Access
904   /// @{
905
906   bool registerSection(MCSection &Section) { return Sections.insert(&Section); }
907
908   bool hasSymbolData(const MCSymbol &Symbol) const { return Symbol.hasData(); }
909
910   void registerSymbol(const MCSymbol &Symbol, bool *Created = nullptr) {
911     if (Created)
912       *Created = !hasSymbolData(Symbol);
913     if (!hasSymbolData(Symbol)) {
914       Symbol.initializeData();
915       Symbols.push_back(&Symbol);
916     }
917   }
918
919   ArrayRef<std::string> getFileNames() { return FileNames; }
920
921   void addFileName(StringRef FileName) {
922     if (std::find(FileNames.begin(), FileNames.end(), FileName) ==
923         FileNames.end())
924       FileNames.push_back(FileName);
925   }
926
927   /// \brief Write the necessary bundle padding to the given object writer.
928   /// Expects a fragment \p F containing instructions and its size \p FSize.
929   void writeFragmentPadding(const MCFragment &F, uint64_t FSize,
930                             MCObjectWriter *OW) const;
931
932   /// @}
933
934   void dump();
935 };
936
937 /// \brief Compute the amount of padding required before the fragment \p F to
938 /// obey bundling restrictions, where \p FOffset is the fragment's offset in
939 /// its section and \p FSize is the fragment's size.
940 uint64_t computeBundlePadding(const MCAssembler &Assembler, const MCFragment *F,
941                               uint64_t FOffset, uint64_t FSize);
942
943 } // end namespace llvm
944
945 #endif