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