xref: /llvm-project/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp (revision c1d10d67a1b6f27b242208ebb09de1b9b35801b8)
1 //===--- Bitcode/Writer/Writer.cpp - Bitcode Writer -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Bitcode writer implementation.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Bitcode/ReaderWriter.h"
15 #include "llvm/Bitcode/BitstreamWriter.h"
16 #include "../LLVMBitCodes.h"
17 #include "ValueEnumerator.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/TypeSymbolTable.h"
21 #include "llvm/Support/MathExtras.h"
22 using namespace llvm;
23 
24 static const unsigned CurVersion = 0;
25 
26 static void WriteStringRecord(unsigned Code, const std::string &Str,
27                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
28   SmallVector<unsigned, 64> Vals;
29 
30   // Code: [strlen, strchar x N]
31   Vals.push_back(Str.size());
32   for (unsigned i = 0, e = Str.size(); i != e; ++i)
33     Vals.push_back(Str[i]);
34 
35   // Emit the finished record.
36   Stream.EmitRecord(Code, Vals, AbbrevToUse);
37 }
38 
39 
40 /// WriteTypeTable - Write out the type table for a module.
41 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
42   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
43 
44   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
45   SmallVector<uint64_t, 64> TypeVals;
46 
47   // FIXME: Set up abbrevs now that we know the width of the type fields, etc.
48 
49   // Emit an entry count so the reader can reserve space.
50   TypeVals.push_back(TypeList.size());
51   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
52   TypeVals.clear();
53 
54   // Loop over all of the types, emitting each in turn.
55   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
56     const Type *T = TypeList[i].first;
57     int AbbrevToUse = 0;
58     unsigned Code = 0;
59 
60     switch (T->getTypeID()) {
61     case Type::PackedStructTyID: // FIXME: Delete Type::PackedStructTyID.
62     default: assert(0 && "Unknown type!");
63     case Type::VoidTyID:   Code = bitc::TYPE_CODE_VOID;   break;
64     case Type::FloatTyID:  Code = bitc::TYPE_CODE_FLOAT;  break;
65     case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
66     case Type::LabelTyID:  Code = bitc::TYPE_CODE_LABEL;  break;
67     case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
68     case Type::IntegerTyID:
69       // INTEGER: [width]
70       Code = bitc::TYPE_CODE_INTEGER;
71       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
72       break;
73     case Type::PointerTyID:
74       // POINTER: [pointee type]
75       Code = bitc::TYPE_CODE_POINTER;
76       TypeVals.push_back(VE.getTypeID(cast<PointerType>(T)->getElementType()));
77       break;
78 
79     case Type::FunctionTyID: {
80       const FunctionType *FT = cast<FunctionType>(T);
81       // FUNCTION: [isvararg, #pararms, paramty x N]
82       Code = bitc::TYPE_CODE_FUNCTION;
83       TypeVals.push_back(FT->isVarArg());
84       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
85       // FIXME: PARAM ATTR ID!
86       TypeVals.push_back(FT->getNumParams());
87       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
88         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
89       break;
90     }
91     case Type::StructTyID: {
92       const StructType *ST = cast<StructType>(T);
93       // STRUCT: [ispacked, #elts, eltty x N]
94       Code = bitc::TYPE_CODE_STRUCT;
95       TypeVals.push_back(ST->isPacked());
96       TypeVals.push_back(ST->getNumElements());
97       // Output all of the element types...
98       for (StructType::element_iterator I = ST->element_begin(),
99            E = ST->element_end(); I != E; ++I)
100         TypeVals.push_back(VE.getTypeID(*I));
101       break;
102     }
103     case Type::ArrayTyID: {
104       const ArrayType *AT = cast<ArrayType>(T);
105       // ARRAY: [numelts, eltty]
106       Code = bitc::TYPE_CODE_ARRAY;
107       TypeVals.push_back(AT->getNumElements());
108       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
109       break;
110     }
111     case Type::VectorTyID: {
112       const VectorType *VT = cast<VectorType>(T);
113       // VECTOR [numelts, eltty]
114       Code = bitc::TYPE_CODE_VECTOR;
115       TypeVals.push_back(VT->getNumElements());
116       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
117       break;
118     }
119     }
120 
121     // Emit the finished record.
122     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
123     TypeVals.clear();
124   }
125 
126   Stream.ExitBlock();
127 }
128 
129 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
130 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
131                                  const ValueEnumerator &VE,
132                                  BitstreamWriter &Stream) {
133   if (TST.empty()) return;
134 
135   Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
136 
137   // FIXME: Set up the abbrev, we know how many types there are!
138   // FIXME: We know if the type names can use 7-bit ascii.
139 
140   SmallVector<unsigned, 64> NameVals;
141 
142   for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
143        TI != TE; ++TI) {
144     unsigned AbbrevToUse = 0;
145 
146     // TST_ENTRY: [typeid, namelen, namechar x N]
147     NameVals.push_back(VE.getTypeID(TI->second));
148 
149     const std::string &Str = TI->first;
150     NameVals.push_back(Str.size());
151     for (unsigned i = 0, e = Str.size(); i != e; ++i)
152       NameVals.push_back(Str[i]);
153 
154     // Emit the finished record.
155     Stream.EmitRecord(bitc::TST_ENTRY_CODE, NameVals, AbbrevToUse);
156     NameVals.clear();
157   }
158 
159   Stream.ExitBlock();
160 }
161 
162 static unsigned getEncodedLinkage(const GlobalValue *GV) {
163   switch (GV->getLinkage()) {
164   default: assert(0 && "Invalid linkage!");
165   case GlobalValue::ExternalLinkage:     return 0;
166   case GlobalValue::WeakLinkage:         return 1;
167   case GlobalValue::AppendingLinkage:    return 2;
168   case GlobalValue::InternalLinkage:     return 3;
169   case GlobalValue::LinkOnceLinkage:     return 4;
170   case GlobalValue::DLLImportLinkage:    return 5;
171   case GlobalValue::DLLExportLinkage:    return 6;
172   case GlobalValue::ExternalWeakLinkage: return 7;
173   }
174 }
175 
176 static unsigned getEncodedVisibility(const GlobalValue *GV) {
177   switch (GV->getVisibility()) {
178   default: assert(0 && "Invalid visibility!");
179   case GlobalValue::DefaultVisibility: return 0;
180   case GlobalValue::HiddenVisibility:  return 1;
181   }
182 }
183 
184 // Emit top-level description of module, including target triple, inline asm,
185 // descriptors for global variables, and function prototype info.
186 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
187                             BitstreamWriter &Stream) {
188   // Emit the list of dependent libraries for the Module.
189   for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
190     WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
191 
192   // Emit various pieces of data attached to a module.
193   if (!M->getTargetTriple().empty())
194     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
195                       0/*TODO*/, Stream);
196   if (!M->getDataLayout().empty())
197     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
198                       0/*TODO*/, Stream);
199   if (!M->getModuleInlineAsm().empty())
200     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
201                       0/*TODO*/, Stream);
202 
203   // Emit information about sections.
204   std::map<std::string, unsigned> SectionMap;
205   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
206        GV != E; ++GV) {
207     if (!GV->hasSection()) continue;
208     // Give section names unique ID's.
209     unsigned &Entry = SectionMap[GV->getSection()];
210     if (Entry != 0) continue;
211     WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
212                       0/*TODO*/, Stream);
213     Entry = SectionMap.size();
214   }
215   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
216     if (!F->hasSection()) continue;
217     // Give section names unique ID's.
218     unsigned &Entry = SectionMap[F->getSection()];
219     if (Entry != 0) continue;
220     WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
221                       0/*TODO*/, Stream);
222     Entry = SectionMap.size();
223   }
224 
225   // TODO: Emit abbrev, now that we know # sections.
226 
227   // Emit the global variable information.
228   SmallVector<unsigned, 64> Vals;
229   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
230        GV != E; ++GV) {
231 
232     // GLOBALVAR: [type, isconst, initid,
233     //             linkage, alignment, section, visibility, threadlocal]
234     Vals.push_back(VE.getTypeID(GV->getType()));
235     Vals.push_back(GV->isConstant());
236     Vals.push_back(GV->isDeclaration() ? 0 :
237                    (VE.getValueID(GV->getInitializer()) + 1));
238     Vals.push_back(getEncodedLinkage(GV));
239     Vals.push_back(Log2_32(GV->getAlignment())+1);
240     Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
241     Vals.push_back(getEncodedVisibility(GV));
242     Vals.push_back(GV->isThreadLocal());
243 
244     unsigned AbbrevToUse = 0;
245     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
246     Vals.clear();
247   }
248 
249   // Emit the function proto information.
250   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
251     // FUNCTION:  [type, callingconv, isproto, linkage, alignment, section,
252     //             visibility]
253     Vals.push_back(VE.getTypeID(F->getType()));
254     Vals.push_back(F->getCallingConv());
255     Vals.push_back(F->isDeclaration());
256     Vals.push_back(getEncodedLinkage(F));
257     Vals.push_back(Log2_32(F->getAlignment())+1);
258     Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
259     Vals.push_back(getEncodedVisibility(F));
260 
261     unsigned AbbrevToUse = 0;
262     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
263     Vals.clear();
264   }
265 }
266 
267 
268 /// WriteModule - Emit the specified module to the bitstream.
269 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
270   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 2);
271 
272   // Emit the version number if it is non-zero.
273   if (CurVersion) {
274     SmallVector<unsigned, 1> VersionVals;
275     VersionVals.push_back(CurVersion);
276     Stream.EmitRecord(bitc::MODULE_CODE_VERSION, VersionVals);
277   }
278 
279   // Analyze the module, enumerating globals, functions, etc.
280   ValueEnumerator VE(M);
281 
282   // Emit information describing all of the types in the module.
283   WriteTypeTable(VE, Stream);
284 
285   // FIXME: Emit constants.
286 
287   // Emit top-level description of module, including target triple, inline asm,
288   // descriptors for global variables, and function prototype info.
289   WriteModuleInfo(M, VE, Stream);
290 
291   // Emit the type symbol table information.
292   WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
293   Stream.ExitBlock();
294 }
295 
296 /// WriteBitcodeToFile - Write the specified module to the specified output
297 /// stream.
298 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
299   std::vector<unsigned char> Buffer;
300   BitstreamWriter Stream(Buffer);
301 
302   Buffer.reserve(256*1024);
303 
304   // Emit the file header.
305   Stream.Emit((unsigned)'B', 8);
306   Stream.Emit((unsigned)'C', 8);
307   Stream.Emit(0x0, 4);
308   Stream.Emit(0xC, 4);
309   Stream.Emit(0xE, 4);
310   Stream.Emit(0xD, 4);
311 
312   // Emit the module.
313   WriteModule(M, Stream);
314 
315   // Write the generated bitstream to "Out".
316   Out.write((char*)&Buffer.front(), Buffer.size());
317 }
318