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