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