Flush the file after writing bitcode so that clients who don't close their
[oota-llvm.git] / lib / Bitcode / Writer / BitcodeWriter.cpp
1 //===--- Bitcode/Writer/BitcodeWriter.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/InlineAsm.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/ParameterAttributes.h"
24 #include "llvm/TypeSymbolTable.h"
25 #include "llvm/ValueSymbolTable.h"
26 #include "llvm/Support/MathExtras.h"
27 using namespace llvm;
28
29 /// These are manifest constants used by the bitcode writer. They do not need to
30 /// be kept in sync with the reader, but need to be consistent within this file.
31 enum {
32   CurVersion = 0,
33   
34   // VALUE_SYMTAB_BLOCK abbrev id's.
35   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
36   VST_ENTRY_7_ABBREV,
37   VST_ENTRY_6_ABBREV,
38   VST_BBENTRY_6_ABBREV,
39   
40   // CONSTANTS_BLOCK abbrev id's.
41   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
42   CONSTANTS_INTEGER_ABBREV,
43   CONSTANTS_CE_CAST_Abbrev,
44   CONSTANTS_NULL_Abbrev,
45   
46   // FUNCTION_BLOCK abbrev id's.
47   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
48   FUNCTION_INST_BINOP_ABBREV,
49   FUNCTION_INST_CAST_ABBREV,
50   FUNCTION_INST_RET_VOID_ABBREV,
51   FUNCTION_INST_RET_VAL_ABBREV,
52   FUNCTION_INST_UNREACHABLE_ABBREV
53 };
54
55
56 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
57   switch (Opcode) {
58   default: assert(0 && "Unknown cast instruction!");
59   case Instruction::Trunc   : return bitc::CAST_TRUNC;
60   case Instruction::ZExt    : return bitc::CAST_ZEXT;
61   case Instruction::SExt    : return bitc::CAST_SEXT;
62   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
63   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
64   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
65   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
66   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
67   case Instruction::FPExt   : return bitc::CAST_FPEXT;
68   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
69   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
70   case Instruction::BitCast : return bitc::CAST_BITCAST;
71   }
72 }
73
74 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
75   switch (Opcode) {
76   default: assert(0 && "Unknown binary instruction!");
77   case Instruction::Add:  return bitc::BINOP_ADD;
78   case Instruction::Sub:  return bitc::BINOP_SUB;
79   case Instruction::Mul:  return bitc::BINOP_MUL;
80   case Instruction::UDiv: return bitc::BINOP_UDIV;
81   case Instruction::FDiv:
82   case Instruction::SDiv: return bitc::BINOP_SDIV;
83   case Instruction::URem: return bitc::BINOP_UREM;
84   case Instruction::FRem:
85   case Instruction::SRem: return bitc::BINOP_SREM;
86   case Instruction::Shl:  return bitc::BINOP_SHL;
87   case Instruction::LShr: return bitc::BINOP_LSHR;
88   case Instruction::AShr: return bitc::BINOP_ASHR;
89   case Instruction::And:  return bitc::BINOP_AND;
90   case Instruction::Or:   return bitc::BINOP_OR;
91   case Instruction::Xor:  return bitc::BINOP_XOR;
92   }
93 }
94
95
96
97 static void WriteStringRecord(unsigned Code, const std::string &Str, 
98                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
99   SmallVector<unsigned, 64> Vals;
100   
101   // Code: [strchar x N]
102   for (unsigned i = 0, e = Str.size(); i != e; ++i)
103     Vals.push_back(Str[i]);
104     
105   // Emit the finished record.
106   Stream.EmitRecord(Code, Vals, AbbrevToUse);
107 }
108
109 // Emit information about parameter attributes.
110 static void WriteParamAttrTable(const ValueEnumerator &VE, 
111                                 BitstreamWriter &Stream) {
112   const std::vector<const ParamAttrsList*> &Attrs = VE.getParamAttrs();
113   if (Attrs.empty()) return;
114   
115   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
116
117   SmallVector<uint64_t, 64> Record;
118   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
119     const ParamAttrsList *A = Attrs[i];
120     for (unsigned op = 0, e = A->size(); op != e; ++op) {
121       Record.push_back(A->getParamIndex(op));
122       Record.push_back(A->getParamAttrsAtIndex(op));
123     }
124     
125     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
126     Record.clear();
127   }
128   
129   Stream.ExitBlock();
130 }
131
132 /// WriteTypeTable - Write out the type table for a module.
133 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
134   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
135   
136   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
137   SmallVector<uint64_t, 64> TypeVals;
138   
139   // Abbrev for TYPE_CODE_POINTER.
140   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
141   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
142   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
143                             Log2_32_Ceil(VE.getTypes().size()+1)));
144   unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
145   
146   // Abbrev for TYPE_CODE_FUNCTION.
147   Abbv = new BitCodeAbbrev();
148   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
149   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
150   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
151                             Log2_32_Ceil(VE.getParamAttrs().size()+1)));
152   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
153   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
154                             Log2_32_Ceil(VE.getTypes().size()+1)));
155   unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
156   
157   // Abbrev for TYPE_CODE_STRUCT.
158   Abbv = new BitCodeAbbrev();
159   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT));
160   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
161   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
162   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
163                             Log2_32_Ceil(VE.getTypes().size()+1)));
164   unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
165  
166   // Abbrev for TYPE_CODE_ARRAY.
167   Abbv = new BitCodeAbbrev();
168   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
169   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
170   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
171                             Log2_32_Ceil(VE.getTypes().size()+1)));
172   unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
173   
174   // Emit an entry count so the reader can reserve space.
175   TypeVals.push_back(TypeList.size());
176   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
177   TypeVals.clear();
178   
179   // Loop over all of the types, emitting each in turn.
180   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
181     const Type *T = TypeList[i].first;
182     int AbbrevToUse = 0;
183     unsigned Code = 0;
184     
185     switch (T->getTypeID()) {
186     case Type::PackedStructTyID: // FIXME: Delete Type::PackedStructTyID.
187     default: assert(0 && "Unknown type!");
188     case Type::VoidTyID:   Code = bitc::TYPE_CODE_VOID;   break;
189     case Type::FloatTyID:  Code = bitc::TYPE_CODE_FLOAT;  break;
190     case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
191     case Type::LabelTyID:  Code = bitc::TYPE_CODE_LABEL;  break;
192     case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
193     case Type::IntegerTyID:
194       // INTEGER: [width]
195       Code = bitc::TYPE_CODE_INTEGER;
196       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
197       break;
198     case Type::PointerTyID:
199       // POINTER: [pointee type]
200       Code = bitc::TYPE_CODE_POINTER;
201       TypeVals.push_back(VE.getTypeID(cast<PointerType>(T)->getElementType()));
202       AbbrevToUse = PtrAbbrev;
203       break;
204
205     case Type::FunctionTyID: {
206       const FunctionType *FT = cast<FunctionType>(T);
207       // FUNCTION: [isvararg, attrid, retty, paramty x N]
208       Code = bitc::TYPE_CODE_FUNCTION;
209       TypeVals.push_back(FT->isVarArg());
210       TypeVals.push_back(VE.getParamAttrID(FT->getParamAttrs()));
211       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
212       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
213         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
214       AbbrevToUse = FunctionAbbrev;
215       break;
216     }
217     case Type::StructTyID: {
218       const StructType *ST = cast<StructType>(T);
219       // STRUCT: [ispacked, eltty x N]
220       Code = bitc::TYPE_CODE_STRUCT;
221       TypeVals.push_back(ST->isPacked());
222       // Output all of the element types.
223       for (StructType::element_iterator I = ST->element_begin(),
224            E = ST->element_end(); I != E; ++I)
225         TypeVals.push_back(VE.getTypeID(*I));
226       AbbrevToUse = StructAbbrev;
227       break;
228     }
229     case Type::ArrayTyID: {
230       const ArrayType *AT = cast<ArrayType>(T);
231       // ARRAY: [numelts, eltty]
232       Code = bitc::TYPE_CODE_ARRAY;
233       TypeVals.push_back(AT->getNumElements());
234       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
235       AbbrevToUse = ArrayAbbrev;
236       break;
237     }
238     case Type::VectorTyID: {
239       const VectorType *VT = cast<VectorType>(T);
240       // VECTOR [numelts, eltty]
241       Code = bitc::TYPE_CODE_VECTOR;
242       TypeVals.push_back(VT->getNumElements());
243       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
244       break;
245     }
246     }
247
248     // Emit the finished record.
249     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
250     TypeVals.clear();
251   }
252   
253   Stream.ExitBlock();
254 }
255
256 static unsigned getEncodedLinkage(const GlobalValue *GV) {
257   switch (GV->getLinkage()) {
258   default: assert(0 && "Invalid linkage!");
259   case GlobalValue::ExternalLinkage:     return 0;
260   case GlobalValue::WeakLinkage:         return 1;
261   case GlobalValue::AppendingLinkage:    return 2;
262   case GlobalValue::InternalLinkage:     return 3;
263   case GlobalValue::LinkOnceLinkage:     return 4;
264   case GlobalValue::DLLImportLinkage:    return 5;
265   case GlobalValue::DLLExportLinkage:    return 6;
266   case GlobalValue::ExternalWeakLinkage: return 7;
267   }
268 }
269
270 static unsigned getEncodedVisibility(const GlobalValue *GV) {
271   switch (GV->getVisibility()) {
272   default: assert(0 && "Invalid visibility!");
273   case GlobalValue::DefaultVisibility:   return 0;
274   case GlobalValue::HiddenVisibility:    return 1;
275   case GlobalValue::ProtectedVisibility: return 2;
276   }
277 }
278
279 // Emit top-level description of module, including target triple, inline asm,
280 // descriptors for global variables, and function prototype info.
281 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
282                             BitstreamWriter &Stream) {
283   // Emit the list of dependent libraries for the Module.
284   for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
285     WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
286
287   // Emit various pieces of data attached to a module.
288   if (!M->getTargetTriple().empty())
289     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
290                       0/*TODO*/, Stream);
291   if (!M->getDataLayout().empty())
292     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
293                       0/*TODO*/, Stream);
294   if (!M->getModuleInlineAsm().empty())
295     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
296                       0/*TODO*/, Stream);
297
298   // Emit information about sections, computing how many there are.  Also
299   // compute the maximum alignment value.
300   std::map<std::string, unsigned> SectionMap;
301   unsigned MaxAlignment = 0;
302   unsigned MaxGlobalType = 0;
303   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
304        GV != E; ++GV) {
305     MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
306     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
307     
308     if (!GV->hasSection()) continue;
309     // Give section names unique ID's.
310     unsigned &Entry = SectionMap[GV->getSection()];
311     if (Entry != 0) continue;
312     WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
313                       0/*TODO*/, Stream);
314     Entry = SectionMap.size();
315   }
316   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
317     MaxAlignment = std::max(MaxAlignment, F->getAlignment());
318     if (!F->hasSection()) continue;
319     // Give section names unique ID's.
320     unsigned &Entry = SectionMap[F->getSection()];
321     if (Entry != 0) continue;
322     WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
323                       0/*TODO*/, Stream);
324     Entry = SectionMap.size();
325   }
326   
327   // Emit abbrev for globals, now that we know # sections and max alignment.
328   unsigned SimpleGVarAbbrev = 0;
329   if (!M->global_empty()) { 
330     // Add an abbrev for common globals with no visibility or thread localness.
331     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
332     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
333     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
334                               Log2_32_Ceil(MaxGlobalType+1)));
335     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));      // Constant.
336     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));        // Initializer.
337     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));      // Linkage.
338     if (MaxAlignment == 0)                                      // Alignment.
339       Abbv->Add(BitCodeAbbrevOp(0));
340     else {
341       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
342       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
343                                Log2_32_Ceil(MaxEncAlignment+1)));
344     }
345     if (SectionMap.empty())                                    // Section.
346       Abbv->Add(BitCodeAbbrevOp(0));
347     else
348       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
349                                Log2_32_Ceil(SectionMap.size()+1)));
350     // Don't bother emitting vis + thread local.
351     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
352   }
353   
354   // Emit the global variable information.
355   SmallVector<unsigned, 64> Vals;
356   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
357        GV != E; ++GV) {
358     unsigned AbbrevToUse = 0;
359
360     // GLOBALVAR: [type, isconst, initid, 
361     //             linkage, alignment, section, visibility, threadlocal]
362     Vals.push_back(VE.getTypeID(GV->getType()));
363     Vals.push_back(GV->isConstant());
364     Vals.push_back(GV->isDeclaration() ? 0 :
365                    (VE.getValueID(GV->getInitializer()) + 1));
366     Vals.push_back(getEncodedLinkage(GV));
367     Vals.push_back(Log2_32(GV->getAlignment())+1);
368     Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
369     if (GV->isThreadLocal() || 
370         GV->getVisibility() != GlobalValue::DefaultVisibility) {
371       Vals.push_back(getEncodedVisibility(GV));
372       Vals.push_back(GV->isThreadLocal());
373     } else {
374       AbbrevToUse = SimpleGVarAbbrev;
375     }
376     
377     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
378     Vals.clear();
379   }
380
381   // Emit the function proto information.
382   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
383     // FUNCTION:  [type, callingconv, isproto, linkage, alignment, section,
384     //             visibility]
385     Vals.push_back(VE.getTypeID(F->getType()));
386     Vals.push_back(F->getCallingConv());
387     Vals.push_back(F->isDeclaration());
388     Vals.push_back(getEncodedLinkage(F));
389     Vals.push_back(Log2_32(F->getAlignment())+1);
390     Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
391     Vals.push_back(getEncodedVisibility(F));
392     
393     unsigned AbbrevToUse = 0;
394     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
395     Vals.clear();
396   }
397   
398   
399   // Emit the alias information.
400   for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
401        AI != E; ++AI) {
402     Vals.push_back(VE.getTypeID(AI->getType()));
403     Vals.push_back(VE.getValueID(AI->getAliasee()));
404     Vals.push_back(getEncodedLinkage(AI));
405     unsigned AbbrevToUse = 0;
406     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
407     Vals.clear();
408   }
409 }
410
411
412 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
413                            const ValueEnumerator &VE,
414                            BitstreamWriter &Stream, bool isGlobal) {
415   if (FirstVal == LastVal) return;
416   
417   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
418
419   unsigned AggregateAbbrev = 0;
420   unsigned String8Abbrev = 0;
421   unsigned CString7Abbrev = 0;
422   unsigned CString6Abbrev = 0;
423   // If this is a constant pool for the module, emit module-specific abbrevs.
424   if (isGlobal) {
425     // Abbrev for CST_CODE_AGGREGATE.
426     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
427     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
428     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
429     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
430     AggregateAbbrev = Stream.EmitAbbrev(Abbv);
431
432     // Abbrev for CST_CODE_STRING.
433     Abbv = new BitCodeAbbrev();
434     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
435     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
436     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
437     String8Abbrev = Stream.EmitAbbrev(Abbv);
438     // Abbrev for CST_CODE_CSTRING.
439     Abbv = new BitCodeAbbrev();
440     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
441     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
442     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
443     CString7Abbrev = Stream.EmitAbbrev(Abbv);
444     // Abbrev for CST_CODE_CSTRING.
445     Abbv = new BitCodeAbbrev();
446     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
447     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
448     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
449     CString6Abbrev = Stream.EmitAbbrev(Abbv);
450   }  
451   
452   SmallVector<uint64_t, 64> Record;
453
454   const ValueEnumerator::ValueList &Vals = VE.getValues();
455   const Type *LastTy = 0;
456   for (unsigned i = FirstVal; i != LastVal; ++i) {
457     const Value *V = Vals[i].first;
458     // If we need to switch types, do so now.
459     if (V->getType() != LastTy) {
460       LastTy = V->getType();
461       Record.push_back(VE.getTypeID(LastTy));
462       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
463                         CONSTANTS_SETTYPE_ABBREV);
464       Record.clear();
465     }
466     
467     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
468       Record.push_back(unsigned(IA->hasSideEffects()));
469       
470       // Add the asm string.
471       const std::string &AsmStr = IA->getAsmString();
472       Record.push_back(AsmStr.size());
473       for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
474         Record.push_back(AsmStr[i]);
475       
476       // Add the constraint string.
477       const std::string &ConstraintStr = IA->getConstraintString();
478       Record.push_back(ConstraintStr.size());
479       for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
480         Record.push_back(ConstraintStr[i]);
481       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
482       Record.clear();
483       continue;
484     }
485     const Constant *C = cast<Constant>(V);
486     unsigned Code = -1U;
487     unsigned AbbrevToUse = 0;
488     if (C->isNullValue()) {
489       Code = bitc::CST_CODE_NULL;
490     } else if (isa<UndefValue>(C)) {
491       Code = bitc::CST_CODE_UNDEF;
492     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
493       if (IV->getBitWidth() <= 64) {
494         int64_t V = IV->getSExtValue();
495         if (V >= 0)
496           Record.push_back(V << 1);
497         else
498           Record.push_back((-V << 1) | 1);
499         Code = bitc::CST_CODE_INTEGER;
500         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
501       } else {                             // Wide integers, > 64 bits in size.
502         // We have an arbitrary precision integer value to write whose 
503         // bit width is > 64. However, in canonical unsigned integer 
504         // format it is likely that the high bits are going to be zero.
505         // So, we only write the number of active words.
506         unsigned NWords = IV->getValue().getActiveWords(); 
507         const uint64_t *RawWords = IV->getValue().getRawData();
508         for (unsigned i = 0; i != NWords; ++i) {
509           int64_t V = RawWords[i];
510           if (V >= 0)
511             Record.push_back(V << 1);
512           else
513             Record.push_back((-V << 1) | 1);
514         }
515         Code = bitc::CST_CODE_WIDE_INTEGER;
516       }
517     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
518       Code = bitc::CST_CODE_FLOAT;
519       if (CFP->getType() == Type::FloatTy) {
520         Record.push_back(FloatToBits((float)CFP->getValue()));
521       } else {
522         assert (CFP->getType() == Type::DoubleTy && "Unknown FP type!");
523         Record.push_back(DoubleToBits((double)CFP->getValue()));
524       }
525     } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
526       // Emit constant strings specially.
527       unsigned NumOps = C->getNumOperands();
528       // If this is a null-terminated string, use the denser CSTRING encoding.
529       if (C->getOperand(NumOps-1)->isNullValue()) {
530         Code = bitc::CST_CODE_CSTRING;
531         --NumOps;  // Don't encode the null, which isn't allowed by char6.
532       } else {
533         Code = bitc::CST_CODE_STRING;
534         AbbrevToUse = String8Abbrev;
535       }
536       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
537       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
538       for (unsigned i = 0; i != NumOps; ++i) {
539         unsigned char V = cast<ConstantInt>(C->getOperand(i))->getZExtValue();
540         Record.push_back(V);
541         isCStr7 &= (V & 128) == 0;
542         if (isCStrChar6) 
543           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
544       }
545       
546       if (isCStrChar6)
547         AbbrevToUse = CString6Abbrev;
548       else if (isCStr7)
549         AbbrevToUse = CString7Abbrev;
550     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
551                isa<ConstantVector>(V)) {
552       Code = bitc::CST_CODE_AGGREGATE;
553       for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
554         Record.push_back(VE.getValueID(C->getOperand(i)));
555       AbbrevToUse = AggregateAbbrev;
556     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
557       switch (CE->getOpcode()) {
558       default:
559         if (Instruction::isCast(CE->getOpcode())) {
560           Code = bitc::CST_CODE_CE_CAST;
561           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
562           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
563           Record.push_back(VE.getValueID(C->getOperand(0)));
564           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
565         } else {
566           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
567           Code = bitc::CST_CODE_CE_BINOP;
568           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
569           Record.push_back(VE.getValueID(C->getOperand(0)));
570           Record.push_back(VE.getValueID(C->getOperand(1)));
571         }
572         break;
573       case Instruction::GetElementPtr:
574         Code = bitc::CST_CODE_CE_GEP;
575         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
576           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
577           Record.push_back(VE.getValueID(C->getOperand(i)));
578         }
579         break;
580       case Instruction::Select:
581         Code = bitc::CST_CODE_CE_SELECT;
582         Record.push_back(VE.getValueID(C->getOperand(0)));
583         Record.push_back(VE.getValueID(C->getOperand(1)));
584         Record.push_back(VE.getValueID(C->getOperand(2)));
585         break;
586       case Instruction::ExtractElement:
587         Code = bitc::CST_CODE_CE_EXTRACTELT;
588         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
589         Record.push_back(VE.getValueID(C->getOperand(0)));
590         Record.push_back(VE.getValueID(C->getOperand(1)));
591         break;
592       case Instruction::InsertElement:
593         Code = bitc::CST_CODE_CE_INSERTELT;
594         Record.push_back(VE.getValueID(C->getOperand(0)));
595         Record.push_back(VE.getValueID(C->getOperand(1)));
596         Record.push_back(VE.getValueID(C->getOperand(2)));
597         break;
598       case Instruction::ShuffleVector:
599         Code = bitc::CST_CODE_CE_SHUFFLEVEC;
600         Record.push_back(VE.getValueID(C->getOperand(0)));
601         Record.push_back(VE.getValueID(C->getOperand(1)));
602         Record.push_back(VE.getValueID(C->getOperand(2)));
603         break;
604       case Instruction::ICmp:
605       case Instruction::FCmp:
606         Code = bitc::CST_CODE_CE_CMP;
607         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
608         Record.push_back(VE.getValueID(C->getOperand(0)));
609         Record.push_back(VE.getValueID(C->getOperand(1)));
610         Record.push_back(CE->getPredicate());
611         break;
612       }
613     } else {
614       assert(0 && "Unknown constant!");
615     }
616     Stream.EmitRecord(Code, Record, AbbrevToUse);
617     Record.clear();
618   }
619
620   Stream.ExitBlock();
621 }
622
623 static void WriteModuleConstants(const ValueEnumerator &VE,
624                                  BitstreamWriter &Stream) {
625   const ValueEnumerator::ValueList &Vals = VE.getValues();
626   
627   // Find the first constant to emit, which is the first non-globalvalue value.
628   // We know globalvalues have been emitted by WriteModuleInfo.
629   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
630     if (!isa<GlobalValue>(Vals[i].first)) {
631       WriteConstants(i, Vals.size(), VE, Stream, true);
632       return;
633     }
634   }
635 }
636
637 /// PushValueAndType - The file has to encode both the value and type id for
638 /// many values, because we need to know what type to create for forward
639 /// references.  However, most operands are not forward references, so this type
640 /// field is not needed.
641 ///
642 /// This function adds V's value ID to Vals.  If the value ID is higher than the
643 /// instruction ID, then it is a forward reference, and it also includes the
644 /// type ID.
645 static bool PushValueAndType(Value *V, unsigned InstID,
646                              SmallVector<unsigned, 64> &Vals, 
647                              ValueEnumerator &VE) {
648   unsigned ValID = VE.getValueID(V);
649   Vals.push_back(ValID);
650   if (ValID >= InstID) {
651     Vals.push_back(VE.getTypeID(V->getType()));
652     return true;
653   }
654   return false;
655 }
656
657 /// WriteInstruction - Emit an instruction to the specified stream.
658 static void WriteInstruction(const Instruction &I, unsigned InstID,
659                              ValueEnumerator &VE, BitstreamWriter &Stream,
660                              SmallVector<unsigned, 64> &Vals) {
661   unsigned Code = 0;
662   unsigned AbbrevToUse = 0;
663   switch (I.getOpcode()) {
664   default:
665     if (Instruction::isCast(I.getOpcode())) {
666       Code = bitc::FUNC_CODE_INST_CAST;
667       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
668         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
669       Vals.push_back(VE.getTypeID(I.getType()));
670       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
671     } else {
672       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
673       Code = bitc::FUNC_CODE_INST_BINOP;
674       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
675         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
676       Vals.push_back(VE.getValueID(I.getOperand(1)));
677       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
678     }
679     break;
680
681   case Instruction::GetElementPtr:
682     Code = bitc::FUNC_CODE_INST_GEP;
683     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
684       PushValueAndType(I.getOperand(i), InstID, Vals, VE);
685     break;
686   case Instruction::Select:
687     Code = bitc::FUNC_CODE_INST_SELECT;
688     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
689     Vals.push_back(VE.getValueID(I.getOperand(2)));
690     Vals.push_back(VE.getValueID(I.getOperand(0)));
691     break;
692   case Instruction::ExtractElement:
693     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
694     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
695     Vals.push_back(VE.getValueID(I.getOperand(1)));
696     break;
697   case Instruction::InsertElement:
698     Code = bitc::FUNC_CODE_INST_INSERTELT;
699     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
700     Vals.push_back(VE.getValueID(I.getOperand(1)));
701     Vals.push_back(VE.getValueID(I.getOperand(2)));
702     break;
703   case Instruction::ShuffleVector:
704     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
705     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
706     Vals.push_back(VE.getValueID(I.getOperand(1)));
707     Vals.push_back(VE.getValueID(I.getOperand(2)));
708     break;
709   case Instruction::ICmp:
710   case Instruction::FCmp:
711     Code = bitc::FUNC_CODE_INST_CMP;
712     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
713     Vals.push_back(VE.getValueID(I.getOperand(1)));
714     Vals.push_back(cast<CmpInst>(I).getPredicate());
715     break;
716
717   case Instruction::Ret:
718     Code = bitc::FUNC_CODE_INST_RET;
719     if (!I.getNumOperands())
720       AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
721     else if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
722       AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
723     break;
724   case Instruction::Br:
725     Code = bitc::FUNC_CODE_INST_BR;
726     Vals.push_back(VE.getValueID(I.getOperand(0)));
727     if (cast<BranchInst>(I).isConditional()) {
728       Vals.push_back(VE.getValueID(I.getOperand(1)));
729       Vals.push_back(VE.getValueID(I.getOperand(2)));
730     }
731     break;
732   case Instruction::Switch:
733     Code = bitc::FUNC_CODE_INST_SWITCH;
734     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
735     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
736       Vals.push_back(VE.getValueID(I.getOperand(i)));
737     break;
738   case Instruction::Invoke: {
739     Code = bitc::FUNC_CODE_INST_INVOKE;
740     Vals.push_back(cast<InvokeInst>(I).getCallingConv());
741     Vals.push_back(VE.getValueID(I.getOperand(1)));      // normal dest
742     Vals.push_back(VE.getValueID(I.getOperand(2)));      // unwind dest
743     PushValueAndType(I.getOperand(0), InstID, Vals, VE); // callee
744     
745     // Emit value #'s for the fixed parameters.
746     const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
747     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
748     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
749       Vals.push_back(VE.getValueID(I.getOperand(i+3)));  // fixed param.
750
751     // Emit type/value pairs for varargs params.
752     if (FTy->isVarArg()) {
753       for (unsigned i = 3+FTy->getNumParams(), e = I.getNumOperands();
754            i != e; ++i)
755         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
756     }
757     break;
758   }
759   case Instruction::Unwind:
760     Code = bitc::FUNC_CODE_INST_UNWIND;
761     break;
762   case Instruction::Unreachable:
763     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
764     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
765     break;
766   
767   case Instruction::PHI:
768     Code = bitc::FUNC_CODE_INST_PHI;
769     Vals.push_back(VE.getTypeID(I.getType()));
770     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
771       Vals.push_back(VE.getValueID(I.getOperand(i)));
772     break;
773     
774   case Instruction::Malloc:
775     Code = bitc::FUNC_CODE_INST_MALLOC;
776     Vals.push_back(VE.getTypeID(I.getType()));
777     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
778     Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
779     break;
780     
781   case Instruction::Free:
782     Code = bitc::FUNC_CODE_INST_FREE;
783     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
784     break;
785     
786   case Instruction::Alloca:
787     Code = bitc::FUNC_CODE_INST_ALLOCA;
788     Vals.push_back(VE.getTypeID(I.getType()));
789     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
790     Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
791     break;
792     
793   case Instruction::Load:
794     Code = bitc::FUNC_CODE_INST_LOAD;
795     if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
796       AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
797       
798     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
799     Vals.push_back(cast<LoadInst>(I).isVolatile());
800     break;
801   case Instruction::Store:
802     Code = bitc::FUNC_CODE_INST_STORE;
803     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // val.
804     Vals.push_back(VE.getValueID(I.getOperand(1)));       // ptr.
805     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
806     Vals.push_back(cast<StoreInst>(I).isVolatile());
807     break;
808   case Instruction::Call: {
809     Code = bitc::FUNC_CODE_INST_CALL;
810     Vals.push_back((cast<CallInst>(I).getCallingConv() << 1) |
811                    unsigned(cast<CallInst>(I).isTailCall()));
812     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // Callee
813     
814     // Emit value #'s for the fixed parameters.
815     const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
816     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
817     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
818       Vals.push_back(VE.getValueID(I.getOperand(i+1)));  // fixed param.
819       
820     // Emit type/value pairs for varargs params.
821     if (FTy->isVarArg()) {
822       unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
823       for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
824            i != e; ++i)
825         PushValueAndType(I.getOperand(i), InstID, Vals, VE);  // varargs
826     }
827     break;
828   }
829   case Instruction::VAArg:
830     Code = bitc::FUNC_CODE_INST_VAARG;
831     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
832     Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
833     Vals.push_back(VE.getTypeID(I.getType())); // restype.
834     break;
835   }
836   
837   Stream.EmitRecord(Code, Vals, AbbrevToUse);
838   Vals.clear();
839 }
840
841 // Emit names for globals/functions etc.
842 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
843                                   const ValueEnumerator &VE,
844                                   BitstreamWriter &Stream) {
845   if (VST.empty()) return;
846   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
847
848   // FIXME: Set up the abbrev, we know how many values there are!
849   // FIXME: We know if the type names can use 7-bit ascii.
850   SmallVector<unsigned, 64> NameVals;
851   
852   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
853        SI != SE; ++SI) {
854     
855     const ValueName &Name = *SI;
856     
857     // Figure out the encoding to use for the name.
858     bool is7Bit = true;
859     bool isChar6 = true;
860     for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
861          C != E; ++C) {
862       if (isChar6) 
863         isChar6 = BitCodeAbbrevOp::isChar6(*C);
864       if ((unsigned char)*C & 128) {
865         is7Bit = false;
866         break;  // don't bother scanning the rest.
867       }
868     }
869     
870     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
871     
872     // VST_ENTRY:   [valueid, namechar x N]
873     // VST_BBENTRY: [bbid, namechar x N]
874     unsigned Code;
875     if (isa<BasicBlock>(SI->getValue())) {
876       Code = bitc::VST_CODE_BBENTRY;
877       if (isChar6)
878         AbbrevToUse = VST_BBENTRY_6_ABBREV;
879     } else {
880       Code = bitc::VST_CODE_ENTRY;
881       if (isChar6)
882         AbbrevToUse = VST_ENTRY_6_ABBREV;
883       else if (is7Bit)
884         AbbrevToUse = VST_ENTRY_7_ABBREV;
885     }
886     
887     NameVals.push_back(VE.getValueID(SI->getValue()));
888     for (const char *P = Name.getKeyData(),
889          *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
890       NameVals.push_back((unsigned char)*P);
891     
892     // Emit the finished record.
893     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
894     NameVals.clear();
895   }
896   Stream.ExitBlock();
897 }
898
899 /// WriteFunction - Emit a function body to the module stream.
900 static void WriteFunction(const Function &F, ValueEnumerator &VE, 
901                           BitstreamWriter &Stream) {
902   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
903   VE.incorporateFunction(F);
904
905   SmallVector<unsigned, 64> Vals;
906   
907   // Emit the number of basic blocks, so the reader can create them ahead of
908   // time.
909   Vals.push_back(VE.getBasicBlocks().size());
910   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
911   Vals.clear();
912   
913   // If there are function-local constants, emit them now.
914   unsigned CstStart, CstEnd;
915   VE.getFunctionConstantRange(CstStart, CstEnd);
916   WriteConstants(CstStart, CstEnd, VE, Stream, false);
917   
918   // Keep a running idea of what the instruction ID is. 
919   unsigned InstID = CstEnd;
920   
921   // Finally, emit all the instructions, in order.
922   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
923     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
924          I != E; ++I) {
925       WriteInstruction(*I, InstID, VE, Stream, Vals);
926       if (I->getType() != Type::VoidTy)
927         ++InstID;
928     }
929   
930   // Emit names for all the instructions etc.
931   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
932     
933   VE.purgeFunction();
934   Stream.ExitBlock();
935 }
936
937 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
938 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
939                                  const ValueEnumerator &VE,
940                                  BitstreamWriter &Stream) {
941   if (TST.empty()) return;
942   
943   Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
944   
945   // 7-bit fixed width VST_CODE_ENTRY strings.
946   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
947   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
948   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
949                             Log2_32_Ceil(VE.getTypes().size()+1)));
950   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
951   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
952   unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
953   
954   SmallVector<unsigned, 64> NameVals;
955   
956   for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 
957        TI != TE; ++TI) {
958     // TST_ENTRY: [typeid, namechar x N]
959     NameVals.push_back(VE.getTypeID(TI->second));
960     
961     const std::string &Str = TI->first;
962     bool is7Bit = true;
963     for (unsigned i = 0, e = Str.size(); i != e; ++i) {
964       NameVals.push_back((unsigned char)Str[i]);
965       if (Str[i] & 128)
966         is7Bit = false;
967     }
968     
969     // Emit the finished record.
970     Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
971     NameVals.clear();
972   }
973   
974   Stream.ExitBlock();
975 }
976
977 // Emit blockinfo, which defines the standard abbreviations etc.
978 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
979   // We only want to emit block info records for blocks that have multiple
980   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.  Other
981   // blocks can defined their abbrevs inline.
982   Stream.EnterBlockInfoBlock(2);
983   
984   { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
985     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
986     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
987     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
988     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
989     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
990     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 
991                                    Abbv) != VST_ENTRY_8_ABBREV)
992       assert(0 && "Unexpected abbrev ordering!");
993   }
994   
995   { // 7-bit fixed width VST_ENTRY strings.
996     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
997     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
998     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
999     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1000     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1001     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1002                                    Abbv) != VST_ENTRY_7_ABBREV)
1003       assert(0 && "Unexpected abbrev ordering!");
1004   }
1005   { // 6-bit char6 VST_ENTRY strings.
1006     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1007     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1008     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1009     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1010     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1011     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1012                                    Abbv) != VST_ENTRY_6_ABBREV)
1013       assert(0 && "Unexpected abbrev ordering!");
1014   }
1015   { // 6-bit char6 VST_BBENTRY strings.
1016     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1017     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1018     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1019     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1020     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1021     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1022                                    Abbv) != VST_BBENTRY_6_ABBREV)
1023       assert(0 && "Unexpected abbrev ordering!");
1024   }
1025   
1026   
1027   
1028   { // SETTYPE abbrev for CONSTANTS_BLOCK.
1029     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1030     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1031     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1032                               Log2_32_Ceil(VE.getTypes().size()+1)));
1033     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1034                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
1035       assert(0 && "Unexpected abbrev ordering!");
1036   }
1037   
1038   { // INTEGER abbrev for CONSTANTS_BLOCK.
1039     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1040     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1041     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1042     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1043                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
1044       assert(0 && "Unexpected abbrev ordering!");
1045   }
1046   
1047   { // CE_CAST abbrev for CONSTANTS_BLOCK.
1048     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1049     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1050     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
1051     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
1052                               Log2_32_Ceil(VE.getTypes().size()+1)));
1053     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
1054
1055     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1056                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
1057       assert(0 && "Unexpected abbrev ordering!");
1058   }
1059   { // NULL abbrev for CONSTANTS_BLOCK.
1060     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1061     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1062     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1063                                    Abbv) != CONSTANTS_NULL_Abbrev)
1064       assert(0 && "Unexpected abbrev ordering!");
1065   }
1066   
1067   // FIXME: This should only use space for first class types!
1068  
1069   { // INST_LOAD abbrev for FUNCTION_BLOCK.
1070     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1071     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1072     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1073     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1074     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1075     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1076                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
1077       assert(0 && "Unexpected abbrev ordering!");
1078   }
1079   { // INST_BINOP abbrev for FUNCTION_BLOCK.
1080     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1081     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1082     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1083     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1084     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1085     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1086                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
1087       assert(0 && "Unexpected abbrev ordering!");
1088   }
1089   { // INST_CAST abbrev for FUNCTION_BLOCK.
1090     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1091     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1092     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
1093     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
1094                               Log2_32_Ceil(VE.getTypes().size()+1)));
1095     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
1096     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1097                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
1098       assert(0 && "Unexpected abbrev ordering!");
1099   }
1100   
1101   { // INST_RET abbrev for FUNCTION_BLOCK.
1102     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1103     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1104     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1105                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1106       assert(0 && "Unexpected abbrev ordering!");
1107   }
1108   { // INST_RET abbrev for FUNCTION_BLOCK.
1109     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1110     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1111     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1112     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1113                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1114       assert(0 && "Unexpected abbrev ordering!");
1115   }
1116   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1117     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1118     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1119     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1120                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1121       assert(0 && "Unexpected abbrev ordering!");
1122   }
1123   
1124   Stream.ExitBlock();
1125 }
1126
1127
1128 /// WriteModule - Emit the specified module to the bitstream.
1129 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1130   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1131   
1132   // Emit the version number if it is non-zero.
1133   if (CurVersion) {
1134     SmallVector<unsigned, 1> Vals;
1135     Vals.push_back(CurVersion);
1136     Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1137   }
1138   
1139   // Analyze the module, enumerating globals, functions, etc.
1140   ValueEnumerator VE(M);
1141
1142   // Emit blockinfo, which defines the standard abbreviations etc.
1143   WriteBlockInfo(VE, Stream);
1144   
1145   // Emit information about parameter attributes.
1146   WriteParamAttrTable(VE, Stream);
1147   
1148   // Emit information describing all of the types in the module.
1149   WriteTypeTable(VE, Stream);
1150   
1151   // Emit top-level description of module, including target triple, inline asm,
1152   // descriptors for global variables, and function prototype info.
1153   WriteModuleInfo(M, VE, Stream);
1154   
1155   // Emit constants.
1156   WriteModuleConstants(VE, Stream);
1157   
1158   // If we have any aggregate values in the value table, purge them - these can
1159   // only be used to initialize global variables.  Doing so makes the value
1160   // namespace smaller for code in functions.
1161   int NumNonAggregates = VE.PurgeAggregateValues();
1162   if (NumNonAggregates != -1) {
1163     SmallVector<unsigned, 1> Vals;
1164     Vals.push_back(NumNonAggregates);
1165     Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
1166   }
1167   
1168   // Emit function bodies.
1169   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
1170     if (!I->isDeclaration())
1171       WriteFunction(*I, VE, Stream);
1172   
1173   // Emit the type symbol table information.
1174   WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
1175   
1176   // Emit names for globals/functions etc.
1177   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1178   
1179   Stream.ExitBlock();
1180 }
1181
1182
1183 /// WriteBitcodeToFile - Write the specified module to the specified output
1184 /// stream.
1185 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
1186   std::vector<unsigned char> Buffer;
1187   BitstreamWriter Stream(Buffer);
1188   
1189   Buffer.reserve(256*1024);
1190   
1191   // Emit the file header.
1192   Stream.Emit((unsigned)'B', 8);
1193   Stream.Emit((unsigned)'C', 8);
1194   Stream.Emit(0x0, 4);
1195   Stream.Emit(0xC, 4);
1196   Stream.Emit(0xE, 4);
1197   Stream.Emit(0xD, 4);
1198
1199   // Emit the module.
1200   WriteModule(M, Stream);
1201   
1202   // Write the generated bitstream to "Out".
1203   Out.write((char*)&Buffer.front(), Buffer.size());
1204   
1205   // Make sure it hits disk now.
1206   Out.flush();
1207 }