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