BitcodeWriter.cpp revision c706907a8041faaa882f9bd87f1d1c1669023a62
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 "ReaderWriter_2_9.h"
15#include "legacy_bitcode.h"
16#include "ValueEnumerator.h"
17#include "llvm/ADT/Triple.h"
18#include "llvm/Bitcode/BitstreamWriter.h"
19#include "llvm/Bitcode/LLVMBitCodes.h"
20#include "llvm/IR/Constants.h"
21#include "llvm/IR/DebugInfoMetadata.h"
22#include "llvm/IR/DerivedTypes.h"
23#include "llvm/IR/InlineAsm.h"
24#include "llvm/IR/Instructions.h"
25#include "llvm/IR/Module.h"
26#include "llvm/IR/Operator.h"
27#include "llvm/IR/ValueSymbolTable.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/MathExtras.h"
30#include "llvm/Support/Program.h"
31#include "llvm/Support/raw_ostream.h"
32#include <cctype>
33#include <map>
34using namespace llvm;
35
36// Redefine older bitcode opcodes for use here. Note that these come from
37// LLVM 2.7 (which is what HC shipped with).
38#define METADATA_NODE_2_7             2
39#define METADATA_FN_NODE_2_7          3
40#define METADATA_NAMED_NODE_2_7       5
41#define METADATA_ATTACHMENT_2_7       7
42#define FUNC_CODE_INST_CALL_2_7       22
43#define FUNC_CODE_DEBUG_LOC_2_7       32
44
45// Redefine older bitcode opcodes for use here. Note that these come from
46// LLVM 2.7 - 3.0.
47#define TYPE_BLOCK_ID_OLD_3_0 10
48#define TYPE_SYMTAB_BLOCK_ID_OLD_3_0 13
49#define TYPE_CODE_STRUCT_OLD_3_0 10
50
51/// These are manifest constants used by the bitcode writer. They do not need to
52/// be kept in sync with the reader, but need to be consistent within this file.
53enum {
54  CurVersion = 0,
55
56  // VALUE_SYMTAB_BLOCK abbrev id's.
57  VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
58  VST_ENTRY_7_ABBREV,
59  VST_ENTRY_6_ABBREV,
60  VST_BBENTRY_6_ABBREV,
61
62  // CONSTANTS_BLOCK abbrev id's.
63  CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
64  CONSTANTS_INTEGER_ABBREV,
65  CONSTANTS_CE_CAST_Abbrev,
66  CONSTANTS_NULL_Abbrev,
67
68  // FUNCTION_BLOCK abbrev id's.
69  FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
70  FUNCTION_INST_BINOP_ABBREV,
71  FUNCTION_INST_BINOP_FLAGS_ABBREV,
72  FUNCTION_INST_CAST_ABBREV,
73  FUNCTION_INST_RET_VOID_ABBREV,
74  FUNCTION_INST_RET_VAL_ABBREV,
75  FUNCTION_INST_UNREACHABLE_ABBREV
76};
77
78static unsigned GetEncodedCastOpcode(unsigned Opcode) {
79  switch (Opcode) {
80  default: llvm_unreachable("Unknown cast instruction!");
81  case Instruction::Trunc   : return bitc::CAST_TRUNC;
82  case Instruction::ZExt    : return bitc::CAST_ZEXT;
83  case Instruction::SExt    : return bitc::CAST_SEXT;
84  case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
85  case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
86  case Instruction::UIToFP  : return bitc::CAST_UITOFP;
87  case Instruction::SIToFP  : return bitc::CAST_SITOFP;
88  case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
89  case Instruction::FPExt   : return bitc::CAST_FPEXT;
90  case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
91  case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
92  case Instruction::BitCast : return bitc::CAST_BITCAST;
93  }
94}
95
96static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
97  switch (Opcode) {
98  default: llvm_unreachable("Unknown binary instruction!");
99  case Instruction::Add:
100  case Instruction::FAdd: return bitc::BINOP_ADD;
101  case Instruction::Sub:
102  case Instruction::FSub: return bitc::BINOP_SUB;
103  case Instruction::Mul:
104  case Instruction::FMul: return bitc::BINOP_MUL;
105  case Instruction::UDiv: return bitc::BINOP_UDIV;
106  case Instruction::FDiv:
107  case Instruction::SDiv: return bitc::BINOP_SDIV;
108  case Instruction::URem: return bitc::BINOP_UREM;
109  case Instruction::FRem:
110  case Instruction::SRem: return bitc::BINOP_SREM;
111  case Instruction::Shl:  return bitc::BINOP_SHL;
112  case Instruction::LShr: return bitc::BINOP_LSHR;
113  case Instruction::AShr: return bitc::BINOP_ASHR;
114  case Instruction::And:  return bitc::BINOP_AND;
115  case Instruction::Or:   return bitc::BINOP_OR;
116  case Instruction::Xor:  return bitc::BINOP_XOR;
117  }
118}
119
120static void WriteStringRecord(unsigned Code, StringRef Str,
121                              unsigned AbbrevToUse, BitstreamWriter &Stream) {
122  SmallVector<unsigned, 64> Vals;
123
124  // Code: [strchar x N]
125  for (unsigned i = 0, e = Str.size(); i != e; ++i) {
126    if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
127      AbbrevToUse = 0;
128    Vals.push_back(Str[i]);
129  }
130
131  // Emit the finished record.
132  Stream.EmitRecord(Code, Vals, AbbrevToUse);
133}
134
135// Emit information about parameter attributes.
136static void WriteAttributeTable(const llvm_2_9::ValueEnumerator &VE,
137                                BitstreamWriter &Stream) {
138  const std::vector<AttributeSet> &Attrs = VE.getAttributes();
139  if (Attrs.empty()) return;
140
141  Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
142
143  SmallVector<uint64_t, 64> Record;
144  for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
145    const AttributeSet &A = Attrs[i];
146    for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
147      Record.push_back(A.getSlotIndex(i));
148      Record.push_back(encodeLLVMAttributesForBitcode(A, A.getSlotIndex(i)));
149    }
150
151    // This needs to use the 3.2 entry type
152    Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY_OLD, Record);
153    Record.clear();
154  }
155
156  Stream.ExitBlock();
157}
158
159static void WriteTypeSymbolTable(const llvm_2_9::ValueEnumerator &VE,
160                                 BitstreamWriter &Stream) {
161  const llvm_2_9::ValueEnumerator::TypeList &TypeList = VE.getTypes();
162  Stream.EnterSubblock(TYPE_SYMTAB_BLOCK_ID_OLD_3_0, 3);
163
164  // 7-bit fixed width VST_CODE_ENTRY strings.
165  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
166  Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
167  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
168                            Log2_32_Ceil(VE.getTypes().size()+1)));
169  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
170  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
171  unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
172
173  SmallVector<unsigned, 64> NameVals;
174
175  for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
176    Type *T = TypeList[i];
177
178    switch (T->getTypeID()) {
179    case Type::StructTyID: {
180      StructType *ST = cast<StructType>(T);
181      if (ST->isLiteral()) {
182        // Skip anonymous struct definitions in type symbol table
183        // FIXME(srhines)
184        break;
185      }
186
187      // TST_ENTRY: [typeid, namechar x N]
188      NameVals.push_back(i);
189
190      const std::string &Str = ST->getName();
191      bool is7Bit = true;
192      for (unsigned i = 0, e = Str.size(); i != e; ++i) {
193        NameVals.push_back((unsigned char)Str[i]);
194        if (Str[i] & 128)
195          is7Bit = false;
196      }
197
198      // Emit the finished record.
199      Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
200      NameVals.clear();
201
202      break;
203    }
204    default: break;
205    }
206  }
207
208  Stream.ExitBlock();
209}
210
211/// WriteTypeTable - Write out the type table for a module.
212static void WriteTypeTable(const llvm_2_9::ValueEnumerator &VE,
213                           BitstreamWriter &Stream) {
214  const llvm_2_9::ValueEnumerator::TypeList &TypeList = VE.getTypes();
215
216  Stream.EnterSubblock(TYPE_BLOCK_ID_OLD_3_0, 4 /*count from # abbrevs */);
217  SmallVector<uint64_t, 64> TypeVals;
218
219  uint64_t NumBits = Log2_32_Ceil(VE.getTypes().size()+1);
220
221  // Abbrev for TYPE_CODE_POINTER.
222  BitCodeAbbrev *Abbv = new BitCodeAbbrev();
223  Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
224  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
225  Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
226  unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
227
228  // Abbrev for TYPE_CODE_FUNCTION.
229  Abbv = new BitCodeAbbrev();
230  Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION_OLD));
231  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
232  Abbv->Add(BitCodeAbbrevOp(0));  // FIXME: DEAD value, remove in LLVM 3.0
233  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
234  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
235  unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
236
237
238  // Abbrev for TYPE_CODE_STRUCT.
239  Abbv = new BitCodeAbbrev();
240  Abbv->Add(BitCodeAbbrevOp(TYPE_CODE_STRUCT_OLD_3_0));
241  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
242  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
243  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
244  unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
245
246  // Abbrev for TYPE_CODE_ARRAY.
247  Abbv = new BitCodeAbbrev();
248  Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
249  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
250  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
251
252  unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
253
254  // Emit an entry count so the reader can reserve space.
255  TypeVals.push_back(TypeList.size());
256  Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
257  TypeVals.clear();
258
259  // Loop over all of the types, emitting each in turn.
260  for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
261    Type *T = TypeList[i];
262    int AbbrevToUse = 0;
263    unsigned Code = 0;
264
265    switch (T->getTypeID()) {
266    default: llvm_unreachable("Unknown type!");
267    case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;   break;
268    case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;  break;
269    case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE; break;
270    case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80; break;
271    case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128; break;
272    case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
273    case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;  break;
274    case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA; break;
275    case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX; break;
276    case Type::IntegerTyID:
277      // INTEGER: [width]
278      Code = bitc::TYPE_CODE_INTEGER;
279      TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
280      break;
281    case Type::PointerTyID: {
282      PointerType *PTy = cast<PointerType>(T);
283      // POINTER: [pointee type, address space]
284      Code = bitc::TYPE_CODE_POINTER;
285      TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
286      unsigned AddressSpace = PTy->getAddressSpace();
287      TypeVals.push_back(AddressSpace);
288      if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
289      break;
290    }
291    case Type::FunctionTyID: {
292      FunctionType *FT = cast<FunctionType>(T);
293      // FUNCTION: [isvararg, attrid, retty, paramty x N]
294      Code = bitc::TYPE_CODE_FUNCTION_OLD;
295      TypeVals.push_back(FT->isVarArg());
296      TypeVals.push_back(0);  // FIXME: DEAD: remove in llvm 3.0
297      TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
298      for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
299        TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
300      AbbrevToUse = FunctionAbbrev;
301      break;
302    }
303    case Type::StructTyID: {
304      StructType *ST = cast<StructType>(T);
305      // STRUCT: [ispacked, eltty x N]
306      TypeVals.push_back(ST->isPacked());
307      // Output all of the element types.
308      for (StructType::element_iterator I = ST->element_begin(),
309           E = ST->element_end(); I != E; ++I)
310        TypeVals.push_back(VE.getTypeID(*I));
311      AbbrevToUse = StructAbbrev;
312      break;
313    }
314    case Type::ArrayTyID: {
315      ArrayType *AT = cast<ArrayType>(T);
316      // ARRAY: [numelts, eltty]
317      Code = bitc::TYPE_CODE_ARRAY;
318      TypeVals.push_back(AT->getNumElements());
319      TypeVals.push_back(VE.getTypeID(AT->getElementType()));
320      AbbrevToUse = ArrayAbbrev;
321      break;
322    }
323    case Type::VectorTyID: {
324      VectorType *VT = cast<VectorType>(T);
325      // VECTOR [numelts, eltty]
326      Code = bitc::TYPE_CODE_VECTOR;
327      TypeVals.push_back(VT->getNumElements());
328      TypeVals.push_back(VE.getTypeID(VT->getElementType()));
329      break;
330    }
331    }
332
333    // Emit the finished record.
334    Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
335    TypeVals.clear();
336  }
337
338  Stream.ExitBlock();
339
340  WriteTypeSymbolTable(VE, Stream);
341}
342
343static unsigned getEncodedLinkage(const GlobalValue &GV) {
344  switch (GV.getLinkage()) {
345  case GlobalValue::ExternalLinkage:
346    return 0;
347  case GlobalValue::WeakAnyLinkage:
348    return 1;
349  case GlobalValue::AppendingLinkage:
350    return 2;
351  case GlobalValue::InternalLinkage:
352    return 3;
353  case GlobalValue::LinkOnceAnyLinkage:
354    return 4;
355  case GlobalValue::ExternalWeakLinkage:
356    return 7;
357  case GlobalValue::CommonLinkage:
358    return 8;
359  case GlobalValue::PrivateLinkage:
360    return 9;
361  case GlobalValue::WeakODRLinkage:
362    return 10;
363  case GlobalValue::LinkOnceODRLinkage:
364    return 11;
365  case GlobalValue::AvailableExternallyLinkage:
366    return 12;
367  }
368  llvm_unreachable("Invalid linkage");
369}
370
371static unsigned getEncodedVisibility(const GlobalValue &GV) {
372  switch (GV.getVisibility()) {
373  case GlobalValue::DefaultVisibility:   return 0;
374  case GlobalValue::HiddenVisibility:    return 1;
375  case GlobalValue::ProtectedVisibility: return 2;
376  }
377  llvm_unreachable("Invalid visibility");
378}
379
380// Emit top-level description of module, including target triple, inline asm,
381// descriptors for global variables, and function prototype info.
382static void WriteModuleInfo(const Module *M,
383                            const llvm_2_9::ValueEnumerator &VE,
384                            BitstreamWriter &Stream) {
385  // Emit various pieces of data attached to a module.
386  if (!M->getTargetTriple().empty())
387    WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
388                      0/*TODO*/, Stream);
389  const std::string &DL = M->getDataLayoutStr();
390  if (!DL.empty())
391    WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream);
392  if (!M->getModuleInlineAsm().empty())
393    WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
394                      0/*TODO*/, Stream);
395
396  // Emit information about sections and GC, computing how many there are. Also
397  // compute the maximum alignment value.
398  std::map<std::string, unsigned> SectionMap;
399  std::map<std::string, unsigned> GCMap;
400  unsigned MaxAlignment = 0;
401  unsigned MaxGlobalType = 0;
402  for (const GlobalValue &GV : M->globals()) {
403    MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
404    MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getType()));
405    if (GV.hasSection()) {
406      // Give section names unique ID's.
407      unsigned &Entry = SectionMap[GV.getSection()];
408      if (!Entry) {
409        WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
410                          0/*TODO*/, Stream);
411        Entry = SectionMap.size();
412      }
413    }
414  }
415  for (const Function &F : *M) {
416    MaxAlignment = std::max(MaxAlignment, F.getAlignment());
417    if (F.hasSection()) {
418      // Give section names unique ID's.
419      unsigned &Entry = SectionMap[F.getSection()];
420      if (!Entry) {
421        WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
422                          0/*TODO*/, Stream);
423        Entry = SectionMap.size();
424      }
425    }
426    if (F.hasGC()) {
427      // Same for GC names.
428      unsigned &Entry = GCMap[F.getGC()];
429      if (!Entry) {
430        WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(),
431                          0/*TODO*/, Stream);
432        Entry = GCMap.size();
433      }
434    }
435  }
436
437  // Emit abbrev for globals, now that we know # sections and max alignment.
438  unsigned SimpleGVarAbbrev = 0;
439  if (!M->global_empty()) {
440    // Add an abbrev for common globals with no visibility or thread localness.
441    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
442    Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
443    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
444                              Log2_32_Ceil(MaxGlobalType+1)));
445    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));      // Constant.
446    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));        // Initializer.
447    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));      // Linkage.
448    if (MaxAlignment == 0)                                      // Alignment.
449      Abbv->Add(BitCodeAbbrevOp(0));
450    else {
451      unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
452      Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
453                               Log2_32_Ceil(MaxEncAlignment+1)));
454    }
455    if (SectionMap.empty())                                    // Section.
456      Abbv->Add(BitCodeAbbrevOp(0));
457    else
458      Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
459                               Log2_32_Ceil(SectionMap.size()+1)));
460    // Don't bother emitting vis + thread local.
461    SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
462  }
463
464  // Emit the global variable information.
465  SmallVector<unsigned, 64> Vals;
466  for (const GlobalVariable &GV : M->globals()) {
467    unsigned AbbrevToUse = 0;
468
469    // GLOBALVAR: [type, isconst, initid,
470    //             linkage, alignment, section, visibility, threadlocal,
471    //             unnamed_addr]
472    Vals.push_back(VE.getTypeID(GV.getType()));
473    Vals.push_back(GV.isConstant());
474    Vals.push_back(GV.isDeclaration() ? 0 :
475                   (VE.getValueID(GV.getInitializer()) + 1));
476    Vals.push_back(getEncodedLinkage(GV));
477    Vals.push_back(Log2_32(GV.getAlignment())+1);
478    Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
479    if (GV.isThreadLocal() ||
480        GV.getVisibility() != GlobalValue::DefaultVisibility ||
481        GV.hasUnnamedAddr()) {
482      Vals.push_back(getEncodedVisibility(GV));
483      Vals.push_back(GV.isThreadLocal());
484      Vals.push_back(GV.hasUnnamedAddr());
485    } else {
486      AbbrevToUse = SimpleGVarAbbrev;
487    }
488
489    Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
490    Vals.clear();
491  }
492
493  // Emit the function proto information.
494  for (const Function &F : *M) {
495    // FUNCTION:  [type, callingconv, isproto, paramattr,
496    //             linkage, alignment, section, visibility, gc, unnamed_addr]
497    Vals.push_back(VE.getTypeID(F.getType()));
498    Vals.push_back(F.getCallingConv());
499    Vals.push_back(F.isDeclaration());
500    Vals.push_back(getEncodedLinkage(F));
501    Vals.push_back(VE.getAttributeID(F.getAttributes()));
502    Vals.push_back(Log2_32(F.getAlignment())+1);
503    Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
504    Vals.push_back(getEncodedVisibility(F));
505    Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
506    Vals.push_back(F.hasUnnamedAddr());
507
508    unsigned AbbrevToUse = 0;
509    Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
510    Vals.clear();
511  }
512
513  // Emit the alias information.
514  for (const GlobalAlias &A : M->aliases()) {
515    Vals.push_back(VE.getTypeID(A.getType()));
516    Vals.push_back(VE.getValueID(A.getAliasee()));
517    Vals.push_back(getEncodedLinkage(A));
518    Vals.push_back(getEncodedVisibility(A));
519    unsigned AbbrevToUse = 0;
520    Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
521    Vals.clear();
522  }
523}
524
525static uint64_t GetOptimizationFlags(const Value *V) {
526  uint64_t Flags = 0;
527
528  if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
529    if (OBO->hasNoSignedWrap())
530      Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
531    if (OBO->hasNoUnsignedWrap())
532      Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
533  } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
534    if (PEO->isExact())
535      Flags |= 1 << bitc::PEO_EXACT;
536  }
537
538  return Flags;
539}
540
541static void WriteValueAsMetadata(const ValueAsMetadata *MD,
542                                 const llvm_2_9::ValueEnumerator &VE,
543                                 BitstreamWriter &Stream,
544                                 SmallVectorImpl<uint64_t> &Record) {
545  // Mimic an MDNode with a value as one operand.
546  Value *V = MD->getValue();
547  Record.push_back(VE.getTypeID(V->getType()));
548  Record.push_back(VE.getValueID(V));
549  Stream.EmitRecord(METADATA_NODE_2_7, Record, 0);
550  Record.clear();
551}
552
553static void WriteMDTuple(const MDTuple *N, const llvm_2_9::ValueEnumerator &VE,
554                         BitstreamWriter &Stream,
555                         SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
556  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
557    Metadata *MD = N->getOperand(i);
558    assert(!(MD && isa<LocalAsMetadata>(MD)) &&
559           "Unexpected function-local metadata");
560    if (!MD) {
561      // TODO(srhines): I don't believe this case can exist for RS.
562      Record.push_back(VE.getTypeID(llvm::Type::getVoidTy(N->getContext())));
563      Record.push_back(0);
564    } else if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
565      Record.push_back(VE.getTypeID(MDC->getType()));
566      Record.push_back(VE.getValueID(MDC->getValue()));
567    } else {
568      Record.push_back(VE.getTypeID(
569          llvm::Type::getMetadataTy(N->getContext())));
570      Record.push_back(VE.getMetadataID(MD));
571    }
572  }
573  Stream.EmitRecord(METADATA_NODE_2_7, Record, Abbrev);
574  Record.clear();
575}
576
577/*static void WriteMDLocation(const MDLocation *N, const llvm_2_9::ValueEnumerator &VE,
578                            BitstreamWriter &Stream,
579                            SmallVectorImpl<uint64_t> &Record,
580                            unsigned Abbrev) {
581  Record.push_back(N->isDistinct());
582  Record.push_back(N->getLine());
583  Record.push_back(N->getColumn());
584  Record.push_back(VE.getMetadataID(N->getScope()));
585  Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
586
587  Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
588  Record.clear();
589}
590
591static void WriteGenericDebugNode(const GenericDebugNode *,
592                                  const llvm_2_9::ValueEnumerator &, BitstreamWriter &,
593                                  SmallVectorImpl<uint64_t> &, unsigned) {
594  llvm_unreachable("unimplemented");
595}*/
596
597static void WriteModuleMetadata(const Module *M,
598                                const llvm_2_9::ValueEnumerator &VE,
599                                BitstreamWriter &Stream) {
600  const auto &MDs = VE.getMDs();
601  if (MDs.empty() && M->named_metadata_empty())
602    return;
603
604  // RenderScript files *ALWAYS* have metadata!
605  Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
606
607  unsigned MDSAbbrev = 0;
608  if (VE.hasMDString()) {
609    // Abbrev for METADATA_STRING.
610    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
611    Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
612    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
613    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
614    MDSAbbrev = Stream.EmitAbbrev(Abbv);
615  }
616
617  unsigned MDLocationAbbrev = 0;
618  if (VE.hasMDLocation()) {
619    // TODO(srhines): Should be unreachable for RenderScript.
620    // Abbrev for METADATA_LOCATION.
621    //
622    // Assume the column is usually under 128, and always output the inlined-at
623    // location (it's never more expensive than building an array size 1).
624    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
625    Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
626    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
627    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
628    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
629    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
630    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
631    MDLocationAbbrev = Stream.EmitAbbrev(Abbv);
632  }
633
634  unsigned NameAbbrev = 0;
635  if (!M->named_metadata_empty()) {
636    // Abbrev for METADATA_NAME.
637    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
638    Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
639    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
640    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
641    NameAbbrev = Stream.EmitAbbrev(Abbv);
642  }
643
644  unsigned MDTupleAbbrev = 0;
645  //unsigned GenericDebugNodeAbbrev = 0;
646  SmallVector<uint64_t, 64> Record;
647  for (const Metadata *MD : MDs) {
648    if (const MDNode *N = dyn_cast<MDNode>(MD)) {
649      switch (N->getMetadataID()) {
650      default:
651        llvm_unreachable("Invalid MDNode subclass");
652#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)
653#define HANDLE_MDNODE_LEAF(CLASS)                                              \
654  case Metadata::CLASS##Kind:                                                  \
655    Write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev);           \
656    continue;
657#include "llvm/IR/Metadata.def"
658      }
659    }
660    if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
661      WriteValueAsMetadata(MDC, VE, Stream, Record);
662      continue;
663    }
664    const MDString *MDS = cast<MDString>(MD);
665    // Code: [strchar x N]
666    Record.append(MDS->bytes_begin(), MDS->bytes_end());
667
668    // Emit the finished record.
669    Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
670    Record.clear();
671  }
672
673  // Write named metadata.
674  for (const NamedMDNode &NMD : M->named_metadata()) {
675    // Write name.
676    StringRef Str = NMD.getName();
677    Record.append(Str.bytes_begin(), Str.bytes_end());
678    Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
679    Record.clear();
680
681    // Write named metadata operands.
682    for (const MDNode *N : NMD.operands())
683      Record.push_back(VE.getMetadataID(N));
684    Stream.EmitRecord(METADATA_NAMED_NODE_2_7, Record, 0);
685    Record.clear();
686  }
687
688  Stream.ExitBlock();
689}
690
691static void WriteFunctionLocalMetadata(const Function &F,
692                                       const llvm_2_9::ValueEnumerator &VE,
693                                       BitstreamWriter &Stream) {
694  bool StartedMetadataBlock = false;
695  SmallVector<uint64_t, 64> Record;
696  const SmallVectorImpl<const LocalAsMetadata *> &MDs =
697      VE.getFunctionLocalMDs();
698  for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
699    assert(MDs[i] && "Expected valid function-local metadata");
700    if (!StartedMetadataBlock) {
701      Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
702      StartedMetadataBlock = true;
703    }
704    WriteValueAsMetadata(MDs[i], VE, Stream, Record);
705  }
706
707  if (StartedMetadataBlock)
708    Stream.ExitBlock();
709}
710
711static void WriteMetadataAttachment(const Function &F,
712                                    const llvm_2_9::ValueEnumerator &VE,
713                                    BitstreamWriter &Stream) {
714  Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
715
716  SmallVector<uint64_t, 64> Record;
717
718  // Write metadata attachments
719  // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
720  SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
721
722  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
723    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
724         I != E; ++I) {
725      MDs.clear();
726      I->getAllMetadataOtherThanDebugLoc(MDs);
727
728      // If no metadata, ignore instruction.
729      if (MDs.empty()) continue;
730
731      Record.push_back(VE.getInstructionID(I));
732
733      for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
734        Record.push_back(MDs[i].first);
735        Record.push_back(VE.getMetadataID(MDs[i].second));
736      }
737      Stream.EmitRecord(METADATA_ATTACHMENT_2_7, Record, 0);
738      Record.clear();
739    }
740
741  Stream.ExitBlock();
742}
743
744static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
745  SmallVector<uint64_t, 64> Record;
746
747  // Write metadata kinds
748  // METADATA_KIND - [n x [id, name]]
749  SmallVector<StringRef, 4> Names;
750  M->getMDKindNames(Names);
751
752  if (Names.empty()) return;
753
754  Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
755
756  for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
757    Record.push_back(MDKindID);
758    StringRef KName = Names[MDKindID];
759    Record.append(KName.begin(), KName.end());
760
761    Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
762    Record.clear();
763  }
764
765  Stream.ExitBlock();
766}
767
768static void WriteConstants(unsigned FirstVal, unsigned LastVal,
769                           const llvm_2_9::ValueEnumerator &VE,
770                           BitstreamWriter &Stream, bool isGlobal) {
771  if (FirstVal == LastVal) return;
772
773  Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
774
775  unsigned AggregateAbbrev = 0;
776  unsigned String8Abbrev = 0;
777  unsigned CString7Abbrev = 0;
778  unsigned CString6Abbrev = 0;
779  // If this is a constant pool for the module, emit module-specific abbrevs.
780  if (isGlobal) {
781    // Abbrev for CST_CODE_AGGREGATE.
782    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
783    Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
784    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
785    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
786    AggregateAbbrev = Stream.EmitAbbrev(Abbv);
787
788    // Abbrev for CST_CODE_STRING.
789    Abbv = new BitCodeAbbrev();
790    Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
791    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
792    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
793    String8Abbrev = Stream.EmitAbbrev(Abbv);
794    // Abbrev for CST_CODE_CSTRING.
795    Abbv = new BitCodeAbbrev();
796    Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
797    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
798    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
799    CString7Abbrev = Stream.EmitAbbrev(Abbv);
800    // Abbrev for CST_CODE_CSTRING.
801    Abbv = new BitCodeAbbrev();
802    Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
803    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
804    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
805    CString6Abbrev = Stream.EmitAbbrev(Abbv);
806  }
807
808  SmallVector<uint64_t, 64> Record;
809
810  const llvm_2_9::ValueEnumerator::ValueList &Vals = VE.getValues();
811  Type *LastTy = nullptr;
812  for (unsigned i = FirstVal; i != LastVal; ++i) {
813    const Value *V = Vals[i].first;
814    // If we need to switch types, do so now.
815    if (V->getType() != LastTy) {
816      LastTy = V->getType();
817      Record.push_back(VE.getTypeID(LastTy));
818      Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
819                        CONSTANTS_SETTYPE_ABBREV);
820      Record.clear();
821    }
822
823    if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
824      Record.push_back(unsigned(IA->hasSideEffects()) |
825                       unsigned(IA->isAlignStack()) << 1);
826
827      // Add the asm string.
828      const std::string &AsmStr = IA->getAsmString();
829      Record.push_back(AsmStr.size());
830      for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
831        Record.push_back(AsmStr[i]);
832
833      // Add the constraint string.
834      const std::string &ConstraintStr = IA->getConstraintString();
835      Record.push_back(ConstraintStr.size());
836      for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
837        Record.push_back(ConstraintStr[i]);
838      Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
839      Record.clear();
840      continue;
841    }
842    const Constant *C = cast<Constant>(V);
843    unsigned Code = -1U;
844    unsigned AbbrevToUse = 0;
845    if (C->isNullValue()) {
846      Code = bitc::CST_CODE_NULL;
847    } else if (isa<UndefValue>(C)) {
848      Code = bitc::CST_CODE_UNDEF;
849    } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
850      if (IV->getBitWidth() <= 64) {
851        uint64_t V = IV->getSExtValue();
852        if ((int64_t)V >= 0)
853          Record.push_back(V << 1);
854        else
855          Record.push_back((-V << 1) | 1);
856        Code = bitc::CST_CODE_INTEGER;
857        AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
858      } else {                             // Wide integers, > 64 bits in size.
859        // We have an arbitrary precision integer value to write whose
860        // bit width is > 64. However, in canonical unsigned integer
861        // format it is likely that the high bits are going to be zero.
862        // So, we only write the number of active words.
863        unsigned NWords = IV->getValue().getActiveWords();
864        const uint64_t *RawWords = IV->getValue().getRawData();
865        for (unsigned i = 0; i != NWords; ++i) {
866          int64_t V = RawWords[i];
867          if (V >= 0)
868            Record.push_back(V << 1);
869          else
870            Record.push_back((-V << 1) | 1);
871        }
872        Code = bitc::CST_CODE_WIDE_INTEGER;
873      }
874    } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
875      Code = bitc::CST_CODE_FLOAT;
876      Type *Ty = CFP->getType();
877      if (Ty->isFloatTy() || Ty->isDoubleTy()) {
878        Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
879      } else if (Ty->isX86_FP80Ty()) {
880        // api needed to prevent premature destruction
881        // bits are not in the same order as a normal i80 APInt, compensate.
882        APInt api = CFP->getValueAPF().bitcastToAPInt();
883        const uint64_t *p = api.getRawData();
884        Record.push_back((p[1] << 48) | (p[0] >> 16));
885        Record.push_back(p[0] & 0xffffLL);
886      } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
887        APInt api = CFP->getValueAPF().bitcastToAPInt();
888        const uint64_t *p = api.getRawData();
889        Record.push_back(p[0]);
890        Record.push_back(p[1]);
891      } else {
892        assert (0 && "Unknown FP type!");
893      }
894    } else if (isa<ConstantDataSequential>(C) &&
895               cast<ConstantDataSequential>(C)->isString()) {
896      const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
897      // Emit constant strings specially.
898      unsigned NumElts = Str->getNumElements();
899      // If this is a null-terminated string, use the denser CSTRING encoding.
900      if (Str->isCString()) {
901        Code = bitc::CST_CODE_CSTRING;
902        --NumElts;  // Don't encode the null, which isn't allowed by char6.
903      } else {
904        Code = bitc::CST_CODE_STRING;
905        AbbrevToUse = String8Abbrev;
906      }
907      bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
908      bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
909      for (unsigned i = 0; i != NumElts; ++i) {
910        unsigned char V = Str->getElementAsInteger(i);
911        Record.push_back(V);
912        isCStr7 &= (V & 128) == 0;
913        if (isCStrChar6)
914          isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
915      }
916
917      if (isCStrChar6)
918        AbbrevToUse = CString6Abbrev;
919      else if (isCStr7)
920        AbbrevToUse = CString7Abbrev;
921    } else if (const ConstantDataSequential *CDS =
922                  dyn_cast<ConstantDataSequential>(C)) {
923      // We must replace ConstantDataSequential's representation with the
924      // legacy ConstantArray/ConstantVector/ConstantStruct version.
925      // ValueEnumerator is similarly modified to mark the appropriate
926      // Constants as used (so they are emitted).
927      Code = bitc::CST_CODE_AGGREGATE;
928      for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
929        Record.push_back(VE.getValueID(CDS->getElementAsConstant(i)));
930      AbbrevToUse = AggregateAbbrev;
931    } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
932               isa<ConstantVector>(C)) {
933      Code = bitc::CST_CODE_AGGREGATE;
934      for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
935        Record.push_back(VE.getValueID(C->getOperand(i)));
936      AbbrevToUse = AggregateAbbrev;
937    } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
938      switch (CE->getOpcode()) {
939      default:
940        if (Instruction::isCast(CE->getOpcode())) {
941          Code = bitc::CST_CODE_CE_CAST;
942          Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
943          Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
944          Record.push_back(VE.getValueID(C->getOperand(0)));
945          AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
946        } else {
947          assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
948          Code = bitc::CST_CODE_CE_BINOP;
949          Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
950          Record.push_back(VE.getValueID(C->getOperand(0)));
951          Record.push_back(VE.getValueID(C->getOperand(1)));
952          uint64_t Flags = GetOptimizationFlags(CE);
953          if (Flags != 0)
954            Record.push_back(Flags);
955        }
956        break;
957      case Instruction::GetElementPtr:
958        Code = bitc::CST_CODE_CE_GEP;
959        if (cast<GEPOperator>(C)->isInBounds())
960          Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
961        for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
962          Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
963          Record.push_back(VE.getValueID(C->getOperand(i)));
964        }
965        break;
966      case Instruction::Select:
967        Code = bitc::CST_CODE_CE_SELECT;
968        Record.push_back(VE.getValueID(C->getOperand(0)));
969        Record.push_back(VE.getValueID(C->getOperand(1)));
970        Record.push_back(VE.getValueID(C->getOperand(2)));
971        break;
972      case Instruction::ExtractElement:
973        Code = bitc::CST_CODE_CE_EXTRACTELT;
974        Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
975        Record.push_back(VE.getValueID(C->getOperand(0)));
976        Record.push_back(VE.getValueID(C->getOperand(1)));
977        break;
978      case Instruction::InsertElement:
979        Code = bitc::CST_CODE_CE_INSERTELT;
980        Record.push_back(VE.getValueID(C->getOperand(0)));
981        Record.push_back(VE.getValueID(C->getOperand(1)));
982        Record.push_back(VE.getValueID(C->getOperand(2)));
983        break;
984      case Instruction::ShuffleVector:
985        // If the return type and argument types are the same, this is a
986        // standard shufflevector instruction.  If the types are different,
987        // then the shuffle is widening or truncating the input vectors, and
988        // the argument type must also be encoded.
989        if (C->getType() == C->getOperand(0)->getType()) {
990          Code = bitc::CST_CODE_CE_SHUFFLEVEC;
991        } else {
992          Code = bitc::CST_CODE_CE_SHUFVEC_EX;
993          Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
994        }
995        Record.push_back(VE.getValueID(C->getOperand(0)));
996        Record.push_back(VE.getValueID(C->getOperand(1)));
997        Record.push_back(VE.getValueID(C->getOperand(2)));
998        break;
999      case Instruction::ICmp:
1000      case Instruction::FCmp:
1001        Code = bitc::CST_CODE_CE_CMP;
1002        Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
1003        Record.push_back(VE.getValueID(C->getOperand(0)));
1004        Record.push_back(VE.getValueID(C->getOperand(1)));
1005        Record.push_back(CE->getPredicate());
1006        break;
1007      }
1008    } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
1009      Code = bitc::CST_CODE_BLOCKADDRESS;
1010      Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
1011      Record.push_back(VE.getValueID(BA->getFunction()));
1012      Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
1013    } else {
1014#ifndef NDEBUG
1015      C->dump();
1016#endif
1017      llvm_unreachable("Unknown constant!");
1018    }
1019    Stream.EmitRecord(Code, Record, AbbrevToUse);
1020    Record.clear();
1021  }
1022
1023  Stream.ExitBlock();
1024}
1025
1026static void WriteModuleConstants(const llvm_2_9::ValueEnumerator &VE,
1027                                 BitstreamWriter &Stream) {
1028  const llvm_2_9::ValueEnumerator::ValueList &Vals = VE.getValues();
1029
1030  // Find the first constant to emit, which is the first non-globalvalue value.
1031  // We know globalvalues have been emitted by WriteModuleInfo.
1032  for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1033    if (!isa<GlobalValue>(Vals[i].first)) {
1034      WriteConstants(i, Vals.size(), VE, Stream, true);
1035      return;
1036    }
1037  }
1038}
1039
1040/// PushValueAndType - The file has to encode both the value and type id for
1041/// many values, because we need to know what type to create for forward
1042/// references.  However, most operands are not forward references, so this type
1043/// field is not needed.
1044///
1045/// This function adds V's value ID to Vals.  If the value ID is higher than the
1046/// instruction ID, then it is a forward reference, and it also includes the
1047/// type ID.
1048static bool PushValueAndType(const Value *V, unsigned InstID,
1049                             SmallVector<unsigned, 64> &Vals,
1050                             llvm_2_9::ValueEnumerator &VE) {
1051  unsigned ValID = VE.getValueID(V);
1052  Vals.push_back(ValID);
1053  if (ValID >= InstID) {
1054    Vals.push_back(VE.getTypeID(V->getType()));
1055    return true;
1056  }
1057  return false;
1058}
1059
1060/// WriteInstruction - Emit an instruction to the specified stream.
1061static void WriteInstruction(const Instruction &I, unsigned InstID,
1062                             llvm_2_9::ValueEnumerator &VE,
1063                             BitstreamWriter &Stream,
1064                             SmallVector<unsigned, 64> &Vals) {
1065  unsigned Code = 0;
1066  unsigned AbbrevToUse = 0;
1067  VE.setInstructionID(&I);
1068  switch (I.getOpcode()) {
1069  default:
1070    if (Instruction::isCast(I.getOpcode())) {
1071      Code = bitc::FUNC_CODE_INST_CAST;
1072      if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1073        AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
1074      Vals.push_back(VE.getTypeID(I.getType()));
1075      Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
1076    } else {
1077      assert(isa<BinaryOperator>(I) && "Unknown instruction!");
1078      Code = bitc::FUNC_CODE_INST_BINOP;
1079      if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1080        AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
1081      Vals.push_back(VE.getValueID(I.getOperand(1)));
1082      Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
1083      uint64_t Flags = GetOptimizationFlags(&I);
1084      if (Flags != 0) {
1085        if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
1086          AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
1087        Vals.push_back(Flags);
1088      }
1089    }
1090    break;
1091
1092  case Instruction::GetElementPtr:
1093    Code = bitc::FUNC_CODE_INST_GEP_OLD;
1094    if (cast<GEPOperator>(&I)->isInBounds())
1095      Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
1096    for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1097      PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1098    break;
1099  case Instruction::ExtractValue: {
1100    Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
1101    PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1102    const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
1103    for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
1104      Vals.push_back(*i);
1105    break;
1106  }
1107  case Instruction::InsertValue: {
1108    Code = bitc::FUNC_CODE_INST_INSERTVAL;
1109    PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1110    PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1111    const InsertValueInst *IVI = cast<InsertValueInst>(&I);
1112    for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
1113      Vals.push_back(*i);
1114    break;
1115  }
1116  case Instruction::Select:
1117    Code = bitc::FUNC_CODE_INST_VSELECT;
1118    PushValueAndType(I.getOperand(1), InstID, Vals, VE);
1119    Vals.push_back(VE.getValueID(I.getOperand(2)));
1120    PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1121    break;
1122  case Instruction::ExtractElement:
1123    Code = bitc::FUNC_CODE_INST_EXTRACTELT;
1124    PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1125    Vals.push_back(VE.getValueID(I.getOperand(1)));
1126    break;
1127  case Instruction::InsertElement:
1128    Code = bitc::FUNC_CODE_INST_INSERTELT;
1129    PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1130    Vals.push_back(VE.getValueID(I.getOperand(1)));
1131    Vals.push_back(VE.getValueID(I.getOperand(2)));
1132    break;
1133  case Instruction::ShuffleVector:
1134    Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
1135    PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1136    Vals.push_back(VE.getValueID(I.getOperand(1)));
1137    Vals.push_back(VE.getValueID(I.getOperand(2)));
1138    break;
1139  case Instruction::ICmp:
1140  case Instruction::FCmp:
1141    // compare returning Int1Ty or vector of Int1Ty
1142    Code = bitc::FUNC_CODE_INST_CMP2;
1143    PushValueAndType(I.getOperand(0), InstID, Vals, VE);
1144    Vals.push_back(VE.getValueID(I.getOperand(1)));
1145    Vals.push_back(cast<CmpInst>(I).getPredicate());
1146    break;
1147
1148  case Instruction::Ret:
1149    {
1150      Code = bitc::FUNC_CODE_INST_RET;
1151      unsigned NumOperands = I.getNumOperands();
1152      if (NumOperands == 0)
1153        AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
1154      else if (NumOperands == 1) {
1155        if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
1156          AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
1157      } else {
1158        for (unsigned i = 0, e = NumOperands; i != e; ++i)
1159          PushValueAndType(I.getOperand(i), InstID, Vals, VE);
1160      }
1161    }
1162    break;
1163  case Instruction::Br:
1164    {
1165      Code = bitc::FUNC_CODE_INST_BR;
1166      const BranchInst &II = cast<BranchInst>(I);
1167      Vals.push_back(VE.getValueID(II.getSuccessor(0)));
1168      if (II.isConditional()) {
1169        Vals.push_back(VE.getValueID(II.getSuccessor(1)));
1170        Vals.push_back(VE.getValueID(II.getCondition()));
1171      }
1172    }
1173    break;
1174  case Instruction::Switch:
1175    {
1176      Code = bitc::FUNC_CODE_INST_SWITCH;
1177      const SwitchInst &SI = cast<SwitchInst>(I);
1178      Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
1179      Vals.push_back(VE.getValueID(SI.getCondition()));
1180      Vals.push_back(VE.getValueID(SI.getDefaultDest()));
1181      for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
1182           i != e; ++i) {
1183        Vals.push_back(VE.getValueID(i.getCaseValue()));
1184        Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
1185      }
1186    }
1187    break;
1188  case Instruction::IndirectBr:
1189    Code = bitc::FUNC_CODE_INST_INDIRECTBR;
1190    Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1191    for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
1192      Vals.push_back(VE.getValueID(I.getOperand(i)));
1193    break;
1194
1195  case Instruction::Invoke: {
1196    const InvokeInst *II = cast<InvokeInst>(&I);
1197    const Value *Callee(II->getCalledValue());
1198    PointerType *PTy = cast<PointerType>(Callee->getType());
1199    FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1200    Code = bitc::FUNC_CODE_INST_INVOKE;
1201
1202    Vals.push_back(VE.getAttributeID(II->getAttributes()));
1203    Vals.push_back(II->getCallingConv());
1204    Vals.push_back(VE.getValueID(II->getNormalDest()));
1205    Vals.push_back(VE.getValueID(II->getUnwindDest()));
1206    PushValueAndType(Callee, InstID, Vals, VE);
1207
1208    // Emit value #'s for the fixed parameters.
1209    for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1210      Vals.push_back(VE.getValueID(I.getOperand(i)));  // fixed param.
1211
1212    // Emit type/value pairs for varargs params.
1213    if (FTy->isVarArg()) {
1214      for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
1215           i != e; ++i)
1216        PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
1217    }
1218    break;
1219  }
1220  case Instruction::Unreachable:
1221    Code = bitc::FUNC_CODE_INST_UNREACHABLE;
1222    AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
1223    break;
1224
1225  case Instruction::PHI: {
1226    const PHINode &PN = cast<PHINode>(I);
1227    Code = bitc::FUNC_CODE_INST_PHI;
1228    Vals.push_back(VE.getTypeID(PN.getType()));
1229    for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1230      Vals.push_back(VE.getValueID(PN.getIncomingValue(i)));
1231      Vals.push_back(VE.getValueID(PN.getIncomingBlock(i)));
1232    }
1233    break;
1234  }
1235
1236  case Instruction::Alloca:
1237    Code = bitc::FUNC_CODE_INST_ALLOCA;
1238    Vals.push_back(VE.getTypeID(I.getType()));
1239    Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
1240    Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
1241    Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
1242    break;
1243
1244  case Instruction::Load:
1245    Code = bitc::FUNC_CODE_INST_LOAD;
1246    if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
1247      AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
1248
1249    Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
1250    Vals.push_back(cast<LoadInst>(I).isVolatile());
1251    break;
1252  case Instruction::Store:
1253    Code = bitc::FUNC_CODE_INST_STORE;
1254    PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
1255    Vals.push_back(VE.getValueID(I.getOperand(0)));       // val.
1256    Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
1257    Vals.push_back(cast<StoreInst>(I).isVolatile());
1258    break;
1259  case Instruction::Call: {
1260    const CallInst &CI = cast<CallInst>(I);
1261    PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
1262    FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1263
1264    Code = FUNC_CODE_INST_CALL_2_7;
1265
1266    Vals.push_back(VE.getAttributeID(CI.getAttributes()));
1267    Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
1268    PushValueAndType(CI.getCalledValue(), InstID, Vals, VE);  // Callee
1269
1270    // Emit value #'s for the fixed parameters.
1271    for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
1272      Vals.push_back(VE.getValueID(CI.getArgOperand(i)));  // fixed param.
1273
1274    // Emit type/value pairs for varargs params.
1275    if (FTy->isVarArg()) {
1276      for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
1277           i != e; ++i)
1278        PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE);  // varargs
1279    }
1280    break;
1281  }
1282  case Instruction::VAArg:
1283    Code = bitc::FUNC_CODE_INST_VAARG;
1284    Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
1285    Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
1286    Vals.push_back(VE.getTypeID(I.getType())); // restype.
1287    break;
1288  }
1289
1290  Stream.EmitRecord(Code, Vals, AbbrevToUse);
1291  Vals.clear();
1292}
1293
1294// Emit names for globals/functions etc.
1295static void WriteValueSymbolTable(const ValueSymbolTable &VST,
1296                                  const llvm_2_9::ValueEnumerator &VE,
1297                                  BitstreamWriter &Stream) {
1298  if (VST.empty()) return;
1299  Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
1300
1301  // FIXME: Set up the abbrev, we know how many values there are!
1302  // FIXME: We know if the type names can use 7-bit ascii.
1303  SmallVector<unsigned, 64> NameVals;
1304
1305  for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
1306       SI != SE; ++SI) {
1307
1308    const ValueName &Name = *SI;
1309
1310    // Figure out the encoding to use for the name.
1311    bool is7Bit = true;
1312    bool isChar6 = true;
1313    for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
1314         C != E; ++C) {
1315      if (isChar6)
1316        isChar6 = BitCodeAbbrevOp::isChar6(*C);
1317      if ((unsigned char)*C & 128) {
1318        is7Bit = false;
1319        break;  // don't bother scanning the rest.
1320      }
1321    }
1322
1323    unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
1324
1325    // VST_ENTRY:   [valueid, namechar x N]
1326    // VST_BBENTRY: [bbid, namechar x N]
1327    unsigned Code;
1328    if (isa<BasicBlock>(SI->getValue())) {
1329      Code = bitc::VST_CODE_BBENTRY;
1330      if (isChar6)
1331        AbbrevToUse = VST_BBENTRY_6_ABBREV;
1332    } else {
1333      Code = bitc::VST_CODE_ENTRY;
1334      if (isChar6)
1335        AbbrevToUse = VST_ENTRY_6_ABBREV;
1336      else if (is7Bit)
1337        AbbrevToUse = VST_ENTRY_7_ABBREV;
1338    }
1339
1340    NameVals.push_back(VE.getValueID(SI->getValue()));
1341    for (const char *P = Name.getKeyData(),
1342         *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
1343      NameVals.push_back((unsigned char)*P);
1344
1345    // Emit the finished record.
1346    Stream.EmitRecord(Code, NameVals, AbbrevToUse);
1347    NameVals.clear();
1348  }
1349  Stream.ExitBlock();
1350}
1351
1352/// WriteFunction - Emit a function body to the module stream.
1353static void WriteFunction(const Function &F, llvm_2_9::ValueEnumerator &VE,
1354                          BitstreamWriter &Stream) {
1355  Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
1356  VE.incorporateFunction(F);
1357
1358  SmallVector<unsigned, 64> Vals;
1359
1360  // Emit the number of basic blocks, so the reader can create them ahead of
1361  // time.
1362  Vals.push_back(VE.getBasicBlocks().size());
1363  Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
1364  Vals.clear();
1365
1366  // If there are function-local constants, emit them now.
1367  unsigned CstStart, CstEnd;
1368  VE.getFunctionConstantRange(CstStart, CstEnd);
1369  WriteConstants(CstStart, CstEnd, VE, Stream, false);
1370
1371  // If there is function-local metadata, emit it now.
1372  WriteFunctionLocalMetadata(F, VE, Stream);
1373
1374  // Keep a running idea of what the instruction ID is.
1375  unsigned InstID = CstEnd;
1376
1377  bool NeedsMetadataAttachment = false;
1378
1379  DebugLoc LastDL;
1380
1381  // Finally, emit all the instructions, in order.
1382  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1383    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
1384         I != E; ++I) {
1385      WriteInstruction(*I, InstID, VE, Stream, Vals);
1386
1387      if (!I->getType()->isVoidTy())
1388        ++InstID;
1389
1390      // If the instruction has metadata, write a metadata attachment later.
1391      NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
1392
1393      // If the instruction has a debug location, emit it.
1394      DebugLoc DL = I->getDebugLoc();
1395      if (DL.isUnknown()) {
1396        // nothing todo.
1397      } else if (DL == LastDL) {
1398        // Just repeat the same debug loc as last time.
1399        Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
1400      } else {
1401        MDNode *Scope, *IA;
1402        DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
1403
1404        Vals.push_back(DL.getLine());
1405        Vals.push_back(DL.getCol());
1406        Vals.push_back(VE.getMetadataOrNullID(Scope));
1407        Vals.push_back(VE.getMetadataOrNullID(IA));
1408        Stream.EmitRecord(FUNC_CODE_DEBUG_LOC_2_7, Vals);
1409        Vals.clear();
1410
1411        LastDL = DL;
1412      }
1413    }
1414
1415  // Emit names for all the instructions etc.
1416  WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
1417
1418  if (NeedsMetadataAttachment)
1419    WriteMetadataAttachment(F, VE, Stream);
1420  VE.purgeFunction();
1421  Stream.ExitBlock();
1422}
1423
1424// Emit blockinfo, which defines the standard abbreviations etc.
1425static void WriteBlockInfo(const llvm_2_9::ValueEnumerator &VE,
1426                           BitstreamWriter &Stream) {
1427  // We only want to emit block info records for blocks that have multiple
1428  // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.  Other
1429  // blocks can defined their abbrevs inline.
1430  Stream.EnterBlockInfoBlock(2);
1431
1432  { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
1433    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1434    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
1435    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1436    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1437    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
1438    if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1439                                   Abbv) != VST_ENTRY_8_ABBREV)
1440      llvm_unreachable("Unexpected abbrev ordering!");
1441  }
1442
1443  { // 7-bit fixed width VST_ENTRY strings.
1444    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1445    Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1446    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1447    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1448    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
1449    if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1450                                   Abbv) != VST_ENTRY_7_ABBREV)
1451      llvm_unreachable("Unexpected abbrev ordering!");
1452  }
1453  { // 6-bit char6 VST_ENTRY strings.
1454    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1455    Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
1456    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1457    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1458    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1459    if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1460                                   Abbv) != VST_ENTRY_6_ABBREV)
1461      llvm_unreachable("Unexpected abbrev ordering!");
1462  }
1463  { // 6-bit char6 VST_BBENTRY strings.
1464    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1465    Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
1466    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1467    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1468    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
1469    if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
1470                                   Abbv) != VST_BBENTRY_6_ABBREV)
1471      llvm_unreachable("Unexpected abbrev ordering!");
1472  }
1473
1474
1475
1476  { // SETTYPE abbrev for CONSTANTS_BLOCK.
1477    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1478    Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
1479    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
1480                              Log2_32_Ceil(VE.getTypes().size()+1)));
1481    if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1482                                   Abbv) != CONSTANTS_SETTYPE_ABBREV)
1483      llvm_unreachable("Unexpected abbrev ordering!");
1484  }
1485
1486  { // INTEGER abbrev for CONSTANTS_BLOCK.
1487    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1488    Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
1489    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1490    if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1491                                   Abbv) != CONSTANTS_INTEGER_ABBREV)
1492      llvm_unreachable("Unexpected abbrev ordering!");
1493  }
1494
1495  { // CE_CAST abbrev for CONSTANTS_BLOCK.
1496    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1497    Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
1498    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
1499    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
1500                              Log2_32_Ceil(VE.getTypes().size()+1)));
1501    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
1502
1503    if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1504                                   Abbv) != CONSTANTS_CE_CAST_Abbrev)
1505      llvm_unreachable("Unexpected abbrev ordering!");
1506  }
1507  { // NULL abbrev for CONSTANTS_BLOCK.
1508    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1509    Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
1510    if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
1511                                   Abbv) != CONSTANTS_NULL_Abbrev)
1512      llvm_unreachable("Unexpected abbrev ordering!");
1513  }
1514
1515  // FIXME: This should only use space for first class types!
1516
1517  { // INST_LOAD abbrev for FUNCTION_BLOCK.
1518    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1519    Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
1520    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
1521    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
1522    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
1523    if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1524                                   Abbv) != FUNCTION_INST_LOAD_ABBREV)
1525      llvm_unreachable("Unexpected abbrev ordering!");
1526  }
1527  { // INST_BINOP abbrev for FUNCTION_BLOCK.
1528    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1529    Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1530    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1531    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1532    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1533    if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1534                                   Abbv) != FUNCTION_INST_BINOP_ABBREV)
1535      llvm_unreachable("Unexpected abbrev ordering!");
1536  }
1537  { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
1538    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1539    Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
1540    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
1541    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
1542    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
1543    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
1544    if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1545                                   Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
1546      llvm_unreachable("Unexpected abbrev ordering!");
1547  }
1548  { // INST_CAST abbrev for FUNCTION_BLOCK.
1549    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1550    Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
1551    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
1552    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
1553                              Log2_32_Ceil(VE.getTypes().size()+1)));
1554    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
1555    if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1556                                   Abbv) != FUNCTION_INST_CAST_ABBREV)
1557      llvm_unreachable("Unexpected abbrev ordering!");
1558  }
1559
1560  { // INST_RET abbrev for FUNCTION_BLOCK.
1561    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1562    Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1563    if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1564                                   Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
1565      llvm_unreachable("Unexpected abbrev ordering!");
1566  }
1567  { // INST_RET abbrev for FUNCTION_BLOCK.
1568    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1569    Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
1570    Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
1571    if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1572                                   Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
1573      llvm_unreachable("Unexpected abbrev ordering!");
1574  }
1575  { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
1576    BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1577    Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
1578    if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
1579                                   Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
1580      llvm_unreachable("Unexpected abbrev ordering!");
1581  }
1582
1583  Stream.ExitBlock();
1584}
1585
1586/// WriteModule - Emit the specified module to the bitstream.
1587static void WriteModule(const Module *M, BitstreamWriter &Stream) {
1588  Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
1589
1590  // Emit the version number if it is non-zero.
1591  if (CurVersion) {
1592    SmallVector<unsigned, 1> Vals;
1593    Vals.push_back(CurVersion);
1594    Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
1595  }
1596
1597  // Analyze the module, enumerating globals, functions, etc.
1598  llvm_2_9::ValueEnumerator VE(*M);
1599
1600  // Emit blockinfo, which defines the standard abbreviations etc.
1601  WriteBlockInfo(VE, Stream);
1602
1603  // Emit information about parameter attributes.
1604  WriteAttributeTable(VE, Stream);
1605
1606  // Emit information describing all of the types in the module.
1607  WriteTypeTable(VE, Stream);
1608
1609  // Emit top-level description of module, including target triple, inline asm,
1610  // descriptors for global variables, and function prototype info.
1611  WriteModuleInfo(M, VE, Stream);
1612
1613  // Emit constants.
1614  WriteModuleConstants(VE, Stream);
1615
1616  // Emit metadata.
1617  WriteModuleMetadata(M, VE, Stream);
1618
1619  // Emit function bodies.
1620  for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
1621    if (!F->isDeclaration())
1622      WriteFunction(*F, VE, Stream);
1623
1624  // Emit metadata.
1625  WriteModuleMetadataStore(M, Stream);
1626
1627  // Emit names for globals/functions etc.
1628  WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
1629
1630  Stream.ExitBlock();
1631}
1632
1633/// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
1634/// header and trailer to make it compatible with the system archiver.  To do
1635/// this we emit the following header, and then emit a trailer that pads the
1636/// file out to be a multiple of 16 bytes.
1637///
1638/// struct bc_header {
1639///   uint32_t Magic;         // 0x0B17C0DE
1640///   uint32_t Version;       // Version, currently always 0.
1641///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1642///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
1643///   uint32_t CPUType;       // CPU specifier.
1644///   ... potentially more later ...
1645/// };
1646enum {
1647  DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
1648  DarwinBCHeaderSize = 5*4
1649};
1650
1651static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
1652                               uint32_t &Position) {
1653  Buffer[Position + 0] = (unsigned char) (Value >>  0);
1654  Buffer[Position + 1] = (unsigned char) (Value >>  8);
1655  Buffer[Position + 2] = (unsigned char) (Value >> 16);
1656  Buffer[Position + 3] = (unsigned char) (Value >> 24);
1657  Position += 4;
1658}
1659
1660static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
1661                                         const Triple &TT) {
1662  unsigned CPUType = ~0U;
1663
1664  // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
1665  // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
1666  // number from /usr/include/mach/machine.h.  It is ok to reproduce the
1667  // specific constants here because they are implicitly part of the Darwin ABI.
1668  enum {
1669    DARWIN_CPU_ARCH_ABI64      = 0x01000000,
1670    DARWIN_CPU_TYPE_X86        = 7,
1671    DARWIN_CPU_TYPE_ARM        = 12,
1672    DARWIN_CPU_TYPE_POWERPC    = 18
1673  };
1674
1675  Triple::ArchType Arch = TT.getArch();
1676  if (Arch == Triple::x86_64)
1677    CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
1678  else if (Arch == Triple::x86)
1679    CPUType = DARWIN_CPU_TYPE_X86;
1680  else if (Arch == Triple::ppc)
1681    CPUType = DARWIN_CPU_TYPE_POWERPC;
1682  else if (Arch == Triple::ppc64)
1683    CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
1684  else if (Arch == Triple::arm || Arch == Triple::thumb)
1685    CPUType = DARWIN_CPU_TYPE_ARM;
1686
1687  // Traditional Bitcode starts after header.
1688  assert(Buffer.size() >= DarwinBCHeaderSize &&
1689         "Expected header size to be reserved");
1690  unsigned BCOffset = DarwinBCHeaderSize;
1691  unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
1692
1693  // Write the magic and version.
1694  unsigned Position = 0;
1695  WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
1696  WriteInt32ToBuffer(0          , Buffer, Position); // Version.
1697  WriteInt32ToBuffer(BCOffset   , Buffer, Position);
1698  WriteInt32ToBuffer(BCSize     , Buffer, Position);
1699  WriteInt32ToBuffer(CPUType    , Buffer, Position);
1700
1701  // If the file is not a multiple of 16 bytes, insert dummy padding.
1702  while (Buffer.size() & 15)
1703    Buffer.push_back(0);
1704}
1705
1706/// WriteBitcodeToFile - Write the specified module to the specified output
1707/// stream.
1708void llvm_2_9::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
1709  SmallVector<char, 1024> Buffer;
1710  Buffer.reserve(256*1024);
1711
1712  // If this is darwin or another generic macho target, reserve space for the
1713  // header.
1714  Triple TT(M->getTargetTriple());
1715  if (TT.isOSDarwin())
1716    Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
1717
1718  // Emit the module into the buffer.
1719  {
1720    BitstreamWriter Stream(Buffer);
1721
1722    // Emit the file header.
1723    Stream.Emit((unsigned)'B', 8);
1724    Stream.Emit((unsigned)'C', 8);
1725    Stream.Emit(0x0, 4);
1726    Stream.Emit(0xC, 4);
1727    Stream.Emit(0xE, 4);
1728    Stream.Emit(0xD, 4);
1729
1730    // Emit the module.
1731    WriteModule(M, Stream);
1732  }
1733
1734  if (TT.isOSDarwin())
1735    EmitDarwinBCHeaderAndTrailer(Buffer, TT);
1736
1737  // Write the generated bitstream to "Out".
1738  Out.write((char*)&Buffer.front(), Buffer.size());
1739}
1740