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