add support for incorporating and purging functions to the value enumerator
[oota-llvm.git] / lib / Bitcode / Writer / BitcodeWriter.cpp
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 "llvm/Bitcode/LLVMBitCodes.h"
17 #include "ValueEnumerator.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Module.h"
21 #include "llvm/TypeSymbolTable.h"
22 #include "llvm/ValueSymbolTable.h"
23 #include "llvm/Support/MathExtras.h"
24 using namespace llvm;
25
26 static const unsigned CurVersion = 0;
27
28 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
29   switch (Opcode) {
30   default: assert(0 && "Unknown cast instruction!");
31   case Instruction::Trunc   : return bitc::CAST_TRUNC;
32   case Instruction::ZExt    : return bitc::CAST_ZEXT;
33   case Instruction::SExt    : return bitc::CAST_SEXT;
34   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
35   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
36   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
37   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
38   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
39   case Instruction::FPExt   : return bitc::CAST_FPEXT;
40   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
41   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
42   case Instruction::BitCast : return bitc::CAST_BITCAST;
43   }
44 }
45
46 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
47   switch (Opcode) {
48   default: assert(0 && "Unknown binary instruction!");
49   case Instruction::Add:  return bitc::BINOP_ADD;
50   case Instruction::Sub:  return bitc::BINOP_SUB;
51   case Instruction::Mul:  return bitc::BINOP_MUL;
52   case Instruction::UDiv: return bitc::BINOP_UDIV;
53   case Instruction::FDiv:
54   case Instruction::SDiv: return bitc::BINOP_SDIV;
55   case Instruction::URem: return bitc::BINOP_UREM;
56   case Instruction::FRem:
57   case Instruction::SRem: return bitc::BINOP_SREM;
58   case Instruction::Shl:  return bitc::BINOP_SHL;
59   case Instruction::LShr: return bitc::BINOP_LSHR;
60   case Instruction::AShr: return bitc::BINOP_ASHR;
61   case Instruction::And:  return bitc::BINOP_AND;
62   case Instruction::Or:   return bitc::BINOP_OR;
63   case Instruction::Xor:  return bitc::BINOP_XOR;
64   }
65 }
66
67
68
69 static void WriteStringRecord(unsigned Code, const std::string &Str, 
70                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
71   SmallVector<unsigned, 64> Vals;
72   
73   // Code: [strlen, strchar x N]
74   Vals.push_back(Str.size());
75   for (unsigned i = 0, e = Str.size(); i != e; ++i)
76     Vals.push_back(Str[i]);
77     
78   // Emit the finished record.
79   Stream.EmitRecord(Code, Vals, AbbrevToUse);
80 }
81
82
83 /// WriteTypeTable - Write out the type table for a module.
84 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
85   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
86   
87   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
88   SmallVector<uint64_t, 64> TypeVals;
89   
90   // FIXME: Set up abbrevs now that we know the width of the type fields, etc.
91   
92   // Emit an entry count so the reader can reserve space.
93   TypeVals.push_back(TypeList.size());
94   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
95   TypeVals.clear();
96   
97   // Loop over all of the types, emitting each in turn.
98   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
99     const Type *T = TypeList[i].first;
100     int AbbrevToUse = 0;
101     unsigned Code = 0;
102     
103     switch (T->getTypeID()) {
104     case Type::PackedStructTyID: // FIXME: Delete Type::PackedStructTyID.
105     default: assert(0 && "Unknown type!");
106     case Type::VoidTyID:   Code = bitc::TYPE_CODE_VOID;   break;
107     case Type::FloatTyID:  Code = bitc::TYPE_CODE_FLOAT;  break;
108     case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
109     case Type::LabelTyID:  Code = bitc::TYPE_CODE_LABEL;  break;
110     case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
111     case Type::IntegerTyID:
112       // INTEGER: [width]
113       Code = bitc::TYPE_CODE_INTEGER;
114       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
115       break;
116     case Type::PointerTyID:
117       // POINTER: [pointee type]
118       Code = bitc::TYPE_CODE_POINTER;
119       TypeVals.push_back(VE.getTypeID(cast<PointerType>(T)->getElementType()));
120       break;
121
122     case Type::FunctionTyID: {
123       const FunctionType *FT = cast<FunctionType>(T);
124       // FUNCTION: [isvararg, #pararms, paramty x N]
125       Code = bitc::TYPE_CODE_FUNCTION;
126       TypeVals.push_back(FT->isVarArg());
127       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
128       // FIXME: PARAM ATTR ID!
129       TypeVals.push_back(FT->getNumParams());
130       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
131         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
132       break;
133     }
134     case Type::StructTyID: {
135       const StructType *ST = cast<StructType>(T);
136       // STRUCT: [ispacked, #elts, eltty x N]
137       Code = bitc::TYPE_CODE_STRUCT;
138       TypeVals.push_back(ST->isPacked());
139       TypeVals.push_back(ST->getNumElements());
140       // Output all of the element types...
141       for (StructType::element_iterator I = ST->element_begin(),
142            E = ST->element_end(); I != E; ++I)
143         TypeVals.push_back(VE.getTypeID(*I));
144       break;
145     }
146     case Type::ArrayTyID: {
147       const ArrayType *AT = cast<ArrayType>(T);
148       // ARRAY: [numelts, eltty]
149       Code = bitc::TYPE_CODE_ARRAY;
150       TypeVals.push_back(AT->getNumElements());
151       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
152       break;
153     }
154     case Type::VectorTyID: {
155       const VectorType *VT = cast<VectorType>(T);
156       // VECTOR [numelts, eltty]
157       Code = bitc::TYPE_CODE_VECTOR;
158       TypeVals.push_back(VT->getNumElements());
159       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
160       break;
161     }
162     }
163
164     // Emit the finished record.
165     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
166     TypeVals.clear();
167   }
168   
169   Stream.ExitBlock();
170 }
171
172 static unsigned getEncodedLinkage(const GlobalValue *GV) {
173   switch (GV->getLinkage()) {
174   default: assert(0 && "Invalid linkage!");
175   case GlobalValue::ExternalLinkage:     return 0;
176   case GlobalValue::WeakLinkage:         return 1;
177   case GlobalValue::AppendingLinkage:    return 2;
178   case GlobalValue::InternalLinkage:     return 3;
179   case GlobalValue::LinkOnceLinkage:     return 4;
180   case GlobalValue::DLLImportLinkage:    return 5;
181   case GlobalValue::DLLExportLinkage:    return 6;
182   case GlobalValue::ExternalWeakLinkage: return 7;
183   }
184 }
185
186 static unsigned getEncodedVisibility(const GlobalValue *GV) {
187   switch (GV->getVisibility()) {
188   default: assert(0 && "Invalid visibility!");
189   case GlobalValue::DefaultVisibility: return 0;
190   case GlobalValue::HiddenVisibility:  return 1;
191   }
192 }
193
194 // Emit top-level description of module, including target triple, inline asm,
195 // descriptors for global variables, and function prototype info.
196 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
197                             BitstreamWriter &Stream) {
198   // Emit the list of dependent libraries for the Module.
199   for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
200     WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
201
202   // Emit various pieces of data attached to a module.
203   if (!M->getTargetTriple().empty())
204     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
205                       0/*TODO*/, Stream);
206   if (!M->getDataLayout().empty())
207     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
208                       0/*TODO*/, Stream);
209   if (!M->getModuleInlineAsm().empty())
210     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
211                       0/*TODO*/, Stream);
212
213   // Emit information about sections, computing how many there are.  Also
214   // compute the maximum alignment value.
215   std::map<std::string, unsigned> SectionMap;
216   unsigned MaxAlignment = 0;
217   unsigned MaxGlobalType = 0;
218   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
219        GV != E; ++GV) {
220     MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
221     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
222     
223     if (!GV->hasSection()) continue;
224     // Give section names unique ID's.
225     unsigned &Entry = SectionMap[GV->getSection()];
226     if (Entry != 0) continue;
227     WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
228                       0/*TODO*/, Stream);
229     Entry = SectionMap.size();
230   }
231   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
232     MaxAlignment = std::max(MaxAlignment, F->getAlignment());
233     if (!F->hasSection()) continue;
234     // Give section names unique ID's.
235     unsigned &Entry = SectionMap[F->getSection()];
236     if (Entry != 0) continue;
237     WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
238                       0/*TODO*/, Stream);
239     Entry = SectionMap.size();
240   }
241   
242   // Emit abbrev for globals, now that we know # sections and max alignment.
243   unsigned SimpleGVarAbbrev = 0;
244   if (!M->global_empty()) { 
245     // Add an abbrev for common globals with no visibility or thread localness.
246     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
247     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
248     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
249                               Log2_32_Ceil(MaxGlobalType+1)));
250     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 1)); // Constant.
251     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));        // Initializer.
252     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 3)); // Linkage.
253     if (MaxAlignment == 0)                                     // Alignment.
254       Abbv->Add(BitCodeAbbrevOp(0));
255     else {
256       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
257       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
258                                Log2_32_Ceil(MaxEncAlignment+1)));
259     }
260     if (SectionMap.empty())                                    // Section.
261       Abbv->Add(BitCodeAbbrevOp(0));
262     else
263       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth,
264                                Log2_32_Ceil(SectionMap.size()+1)));
265     // Don't bother emitting vis + thread local.
266     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
267   }
268   
269   // Emit the global variable information.
270   SmallVector<unsigned, 64> Vals;
271   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
272        GV != E; ++GV) {
273     unsigned AbbrevToUse = 0;
274
275     // GLOBALVAR: [type, isconst, initid, 
276     //             linkage, alignment, section, visibility, threadlocal]
277     Vals.push_back(VE.getTypeID(GV->getType()));
278     Vals.push_back(GV->isConstant());
279     Vals.push_back(GV->isDeclaration() ? 0 :
280                    (VE.getValueID(GV->getInitializer()) + 1));
281     Vals.push_back(getEncodedLinkage(GV));
282     Vals.push_back(Log2_32(GV->getAlignment())+1);
283     Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
284     if (GV->isThreadLocal() || 
285         GV->getVisibility() != GlobalValue::DefaultVisibility) {
286       Vals.push_back(getEncodedVisibility(GV));
287       Vals.push_back(GV->isThreadLocal());
288     } else {
289       AbbrevToUse = SimpleGVarAbbrev;
290     }
291     
292     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
293     Vals.clear();
294   }
295
296   // Emit the function proto information.
297   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
298     // FUNCTION:  [type, callingconv, isproto, linkage, alignment, section,
299     //             visibility]
300     Vals.push_back(VE.getTypeID(F->getType()));
301     Vals.push_back(F->getCallingConv());
302     Vals.push_back(F->isDeclaration());
303     Vals.push_back(getEncodedLinkage(F));
304     Vals.push_back(Log2_32(F->getAlignment())+1);
305     Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
306     Vals.push_back(getEncodedVisibility(F));
307     
308     unsigned AbbrevToUse = 0;
309     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
310     Vals.clear();
311   }
312   
313   
314   // Emit the alias information.
315   for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
316        AI != E; ++AI) {
317     Vals.push_back(VE.getTypeID(AI->getType()));
318     Vals.push_back(VE.getValueID(AI->getAliasee()));
319     Vals.push_back(getEncodedLinkage(AI));
320     unsigned AbbrevToUse = 0;
321     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
322     Vals.clear();
323   }
324 }
325
326
327 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
328                            const ValueEnumerator &VE,
329                            BitstreamWriter &Stream) {
330   if (FirstVal == LastVal) return;
331   
332   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 2);
333
334   // FIXME: Install and use abbrevs to reduce size.
335   
336   SmallVector<uint64_t, 64> Record;
337
338   const ValueEnumerator::ValueList &Vals = VE.getValues();
339   const Type *LastTy = 0;
340   for (unsigned i = FirstVal; i != LastVal; ++i) {
341     const Value *V = Vals[i].first;
342     // If we need to switch types, do so now.
343     if (V->getType() != LastTy) {
344       LastTy = V->getType();
345       Record.push_back(VE.getTypeID(LastTy));
346       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record);
347       Record.clear();
348     }
349     
350     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
351       assert(0 && IA && "FIXME: Inline asm writing unimp!");
352       continue;
353     }
354     const Constant *C = cast<Constant>(V);
355     unsigned Code = -1U;
356     unsigned AbbrevToUse = 0;
357     if (C->isNullValue()) {
358       Code = bitc::CST_CODE_NULL;
359     } else if (isa<UndefValue>(C)) {
360       Code = bitc::CST_CODE_UNDEF;
361     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
362       if (IV->getBitWidth() <= 64) {
363         int64_t V = IV->getSExtValue();
364         if (V >= 0)
365           Record.push_back(V << 1);
366         else
367           Record.push_back((-V << 1) | 1);
368         Code = bitc::CST_CODE_INTEGER;
369       } else {                             // Wide integers, > 64 bits in size.
370         // We have an arbitrary precision integer value to write whose 
371         // bit width is > 64. However, in canonical unsigned integer 
372         // format it is likely that the high bits are going to be zero.
373         // So, we only write the number of active words.
374         unsigned NWords = IV->getValue().getActiveWords(); 
375         const uint64_t *RawWords = IV->getValue().getRawData();
376         Record.push_back(NWords);
377         for (unsigned i = 0; i != NWords; ++i) {
378           int64_t V = RawWords[i];
379           if (V >= 0)
380             Record.push_back(V << 1);
381           else
382             Record.push_back((-V << 1) | 1);
383         }
384         Code = bitc::CST_CODE_WIDE_INTEGER;
385       }
386     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
387       Code = bitc::CST_CODE_FLOAT;
388       if (CFP->getType() == Type::FloatTy) {
389         Record.push_back(FloatToBits((float)CFP->getValue()));
390       } else {
391         assert (CFP->getType() == Type::DoubleTy && "Unknown FP type!");
392         Record.push_back(DoubleToBits((double)CFP->getValue()));
393       }
394     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
395                isa<ConstantVector>(V)) {
396       Code = bitc::CST_CODE_AGGREGATE;
397       Record.push_back(C->getNumOperands());
398       for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
399         Record.push_back(VE.getValueID(C->getOperand(i)));
400     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
401       switch (CE->getOpcode()) {
402       default:
403         if (Instruction::isCast(CE->getOpcode())) {
404           Code = bitc::CST_CODE_CE_CAST;
405           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
406           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
407           Record.push_back(VE.getValueID(C->getOperand(0)));
408         } else {
409           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
410           Code = bitc::CST_CODE_CE_BINOP;
411           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
412           Record.push_back(VE.getValueID(C->getOperand(0)));
413           Record.push_back(VE.getValueID(C->getOperand(1)));
414         }
415         break;
416       case Instruction::GetElementPtr:
417         Code = bitc::CST_CODE_CE_GEP;
418         Record.push_back(CE->getNumOperands());
419         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
420           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
421           Record.push_back(VE.getValueID(C->getOperand(i)));
422         }
423         break;
424       case Instruction::Select:
425         Code = bitc::CST_CODE_CE_SELECT;
426         Record.push_back(VE.getValueID(C->getOperand(0)));
427         Record.push_back(VE.getValueID(C->getOperand(1)));
428         Record.push_back(VE.getValueID(C->getOperand(2)));
429         break;
430       case Instruction::ExtractElement:
431         Code = bitc::CST_CODE_CE_EXTRACTELT;
432         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
433         Record.push_back(VE.getValueID(C->getOperand(0)));
434         Record.push_back(VE.getValueID(C->getOperand(1)));
435         break;
436       case Instruction::InsertElement:
437         Code = bitc::CST_CODE_CE_INSERTELT;
438         Record.push_back(VE.getValueID(C->getOperand(0)));
439         Record.push_back(VE.getValueID(C->getOperand(1)));
440         Record.push_back(VE.getValueID(C->getOperand(2)));
441         break;
442       case Instruction::ShuffleVector:
443         Code = bitc::CST_CODE_CE_SHUFFLEVEC;
444         Record.push_back(VE.getValueID(C->getOperand(0)));
445         Record.push_back(VE.getValueID(C->getOperand(1)));
446         Record.push_back(VE.getValueID(C->getOperand(2)));
447         break;
448       case Instruction::ICmp:
449       case Instruction::FCmp:
450         Code = bitc::CST_CODE_CE_CMP;
451         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
452         Record.push_back(VE.getValueID(C->getOperand(0)));
453         Record.push_back(VE.getValueID(C->getOperand(1)));
454         Record.push_back(CE->getPredicate());
455         break;
456       }
457     } else {
458       assert(0 && "Unknown constant!");
459     }
460     Stream.EmitRecord(Code, Record, AbbrevToUse);
461     Record.clear();
462   }
463
464   Stream.ExitBlock();
465 }
466
467 static void WriteModuleConstants(const ValueEnumerator &VE,
468                                  BitstreamWriter &Stream) {
469   const ValueEnumerator::ValueList &Vals = VE.getValues();
470   
471   // Find the first constant to emit, which is the first non-globalvalue value.
472   // We know globalvalues have been emitted by WriteModuleInfo.
473   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
474     if (!isa<GlobalValue>(Vals[i].first)) {
475       WriteConstants(i, Vals.size(), VE, Stream);
476       return;
477     }
478   }
479 }
480
481 /// WriteFunction - Emit a function body to the module stream.
482 static void WriteFunction(const Function &F, ValueEnumerator &VE, 
483                           BitstreamWriter &Stream) {
484   VE.incorporateFunction(F);
485   
486   VE.purgeFunction();
487 }
488
489 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
490 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
491                                  const ValueEnumerator &VE,
492                                  BitstreamWriter &Stream) {
493   if (TST.empty()) return;
494   
495   Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
496   
497   // FIXME: Set up the abbrev, we know how many types there are!
498   // FIXME: We know if the type names can use 7-bit ascii.
499   
500   SmallVector<unsigned, 64> NameVals;
501   
502   for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 
503        TI != TE; ++TI) {
504     unsigned AbbrevToUse = 0;
505     
506     // TST_ENTRY: [typeid, namelen, namechar x N]
507     NameVals.push_back(VE.getTypeID(TI->second));
508     
509     const std::string &Str = TI->first;
510     NameVals.push_back(Str.size());
511     for (unsigned i = 0, e = Str.size(); i != e; ++i)
512       NameVals.push_back(Str[i]);
513     
514     // Emit the finished record.
515     Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, AbbrevToUse);
516     NameVals.clear();
517   }
518   
519   Stream.ExitBlock();
520 }
521
522 // Emit names for globals/functions etc.
523 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
524                                   const ValueEnumerator &VE,
525                                   BitstreamWriter &Stream) {
526   if (VST.empty()) return;
527   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 3);
528   
529   // FIXME: Set up the abbrev, we know how many values there are!
530   // FIXME: We know if the type names can use 7-bit ascii.
531   SmallVector<unsigned, 64> NameVals;
532   
533   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
534        SI != SE; ++SI) {
535     unsigned AbbrevToUse = 0;
536     
537     // VST_ENTRY: [valueid, namelen, namechar x N]
538     NameVals.push_back(VE.getValueID(SI->getValue()));
539     
540     NameVals.push_back(SI->getKeyLength());
541     for (const char *P = SI->getKeyData(),
542          *E = SI->getKeyData()+SI->getKeyLength(); P != E; ++P)
543       NameVals.push_back((unsigned char)*P);
544     
545     // Emit the finished record.
546     Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, AbbrevToUse);
547     NameVals.clear();
548   }
549   Stream.ExitBlock();
550 }
551
552
553 /// WriteModule - Emit the specified module to the bitstream.
554 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
555   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
556   
557   // Emit the version number if it is non-zero.
558   if (CurVersion) {
559     SmallVector<unsigned, 1> Vals;
560     Vals.push_back(CurVersion);
561     Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
562   }
563   
564   // Analyze the module, enumerating globals, functions, etc.
565   ValueEnumerator VE(M);
566   
567   // Emit information describing all of the types in the module.
568   WriteTypeTable(VE, Stream);
569   
570   // Emit top-level description of module, including target triple, inline asm,
571   // descriptors for global variables, and function prototype info.
572   WriteModuleInfo(M, VE, Stream);
573   
574   // Emit constants.
575   WriteModuleConstants(VE, Stream);
576   
577   // If we have any aggregate values in the value table, purge them - these can
578   // only be used to initialize global variables.  Doing so makes the value
579   // namespace smaller for code in functions.
580   int NumNonAggregates = VE.PurgeAggregateValues();
581   if (NumNonAggregates != -1) {
582     SmallVector<unsigned, 1> Vals;
583     Vals.push_back(NumNonAggregates);
584     Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
585   }
586   
587   // Emit function bodies.
588   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
589     if (!I->isDeclaration())
590       WriteFunction(*I, VE, Stream);
591   
592   // Emit the type symbol table information.
593   WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
594   
595   // Emit names for globals/functions etc.
596   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
597   
598   Stream.ExitBlock();
599 }
600
601 /// WriteBitcodeToFile - Write the specified module to the specified output
602 /// stream.
603 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
604   std::vector<unsigned char> Buffer;
605   BitstreamWriter Stream(Buffer);
606   
607   Buffer.reserve(256*1024);
608   
609   // Emit the file header.
610   Stream.Emit((unsigned)'B', 8);
611   Stream.Emit((unsigned)'C', 8);
612   Stream.Emit(0x0, 4);
613   Stream.Emit(0xC, 4);
614   Stream.Emit(0xE, 4);
615   Stream.Emit(0xD, 4);
616
617   // Emit the module.
618   WriteModule(M, Stream);
619   
620   // Write the generated bitstream to "Out".
621   Out.write((char*)&Buffer.front(), Buffer.size());
622 }