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