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