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