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