LLVM  mainline
BitcodeWriter.cpp
Go to the documentation of this file.
00001 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Bitcode writer implementation.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Bitcode/ReaderWriter.h"
00015 #include "ValueEnumerator.h"
00016 #include "llvm/ADT/Triple.h"
00017 #include "llvm/Bitcode/BitstreamWriter.h"
00018 #include "llvm/Bitcode/LLVMBitCodes.h"
00019 #include "llvm/IR/Constants.h"
00020 #include "llvm/IR/DebugInfoMetadata.h"
00021 #include "llvm/IR/DerivedTypes.h"
00022 #include "llvm/IR/InlineAsm.h"
00023 #include "llvm/IR/Instructions.h"
00024 #include "llvm/IR/Module.h"
00025 #include "llvm/IR/Operator.h"
00026 #include "llvm/IR/UseListOrder.h"
00027 #include "llvm/IR/ValueSymbolTable.h"
00028 #include "llvm/Support/CommandLine.h"
00029 #include "llvm/Support/ErrorHandling.h"
00030 #include "llvm/Support/MathExtras.h"
00031 #include "llvm/Support/Program.h"
00032 #include "llvm/Support/raw_ostream.h"
00033 #include <cctype>
00034 #include <map>
00035 using namespace llvm;
00036 
00037 /// These are manifest constants used by the bitcode writer. They do not need to
00038 /// be kept in sync with the reader, but need to be consistent within this file.
00039 enum {
00040   // VALUE_SYMTAB_BLOCK abbrev id's.
00041   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
00042   VST_ENTRY_7_ABBREV,
00043   VST_ENTRY_6_ABBREV,
00044   VST_BBENTRY_6_ABBREV,
00045 
00046   // CONSTANTS_BLOCK abbrev id's.
00047   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
00048   CONSTANTS_INTEGER_ABBREV,
00049   CONSTANTS_CE_CAST_Abbrev,
00050   CONSTANTS_NULL_Abbrev,
00051 
00052   // FUNCTION_BLOCK abbrev id's.
00053   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
00054   FUNCTION_INST_BINOP_ABBREV,
00055   FUNCTION_INST_BINOP_FLAGS_ABBREV,
00056   FUNCTION_INST_CAST_ABBREV,
00057   FUNCTION_INST_RET_VOID_ABBREV,
00058   FUNCTION_INST_RET_VAL_ABBREV,
00059   FUNCTION_INST_UNREACHABLE_ABBREV,
00060   FUNCTION_INST_GEP_ABBREV,
00061 };
00062 
00063 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
00064   switch (Opcode) {
00065   default: llvm_unreachable("Unknown cast instruction!");
00066   case Instruction::Trunc   : return bitc::CAST_TRUNC;
00067   case Instruction::ZExt    : return bitc::CAST_ZEXT;
00068   case Instruction::SExt    : return bitc::CAST_SEXT;
00069   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
00070   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
00071   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
00072   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
00073   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
00074   case Instruction::FPExt   : return bitc::CAST_FPEXT;
00075   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
00076   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
00077   case Instruction::BitCast : return bitc::CAST_BITCAST;
00078   case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
00079   }
00080 }
00081 
00082 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
00083   switch (Opcode) {
00084   default: llvm_unreachable("Unknown binary instruction!");
00085   case Instruction::Add:
00086   case Instruction::FAdd: return bitc::BINOP_ADD;
00087   case Instruction::Sub:
00088   case Instruction::FSub: return bitc::BINOP_SUB;
00089   case Instruction::Mul:
00090   case Instruction::FMul: return bitc::BINOP_MUL;
00091   case Instruction::UDiv: return bitc::BINOP_UDIV;
00092   case Instruction::FDiv:
00093   case Instruction::SDiv: return bitc::BINOP_SDIV;
00094   case Instruction::URem: return bitc::BINOP_UREM;
00095   case Instruction::FRem:
00096   case Instruction::SRem: return bitc::BINOP_SREM;
00097   case Instruction::Shl:  return bitc::BINOP_SHL;
00098   case Instruction::LShr: return bitc::BINOP_LSHR;
00099   case Instruction::AShr: return bitc::BINOP_ASHR;
00100   case Instruction::And:  return bitc::BINOP_AND;
00101   case Instruction::Or:   return bitc::BINOP_OR;
00102   case Instruction::Xor:  return bitc::BINOP_XOR;
00103   }
00104 }
00105 
00106 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
00107   switch (Op) {
00108   default: llvm_unreachable("Unknown RMW operation!");
00109   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
00110   case AtomicRMWInst::Add: return bitc::RMW_ADD;
00111   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
00112   case AtomicRMWInst::And: return bitc::RMW_AND;
00113   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
00114   case AtomicRMWInst::Or: return bitc::RMW_OR;
00115   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
00116   case AtomicRMWInst::Max: return bitc::RMW_MAX;
00117   case AtomicRMWInst::Min: return bitc::RMW_MIN;
00118   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
00119   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
00120   }
00121 }
00122 
00123 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
00124   switch (Ordering) {
00125   case NotAtomic: return bitc::ORDERING_NOTATOMIC;
00126   case Unordered: return bitc::ORDERING_UNORDERED;
00127   case Monotonic: return bitc::ORDERING_MONOTONIC;
00128   case Acquire: return bitc::ORDERING_ACQUIRE;
00129   case Release: return bitc::ORDERING_RELEASE;
00130   case AcquireRelease: return bitc::ORDERING_ACQREL;
00131   case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
00132   }
00133   llvm_unreachable("Invalid ordering");
00134 }
00135 
00136 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
00137   switch (SynchScope) {
00138   case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
00139   case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
00140   }
00141   llvm_unreachable("Invalid synch scope");
00142 }
00143 
00144 static void WriteStringRecord(unsigned Code, StringRef Str,
00145                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
00146   SmallVector<unsigned, 64> Vals;
00147 
00148   // Code: [strchar x N]
00149   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
00150     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
00151       AbbrevToUse = 0;
00152     Vals.push_back(Str[i]);
00153   }
00154 
00155   // Emit the finished record.
00156   Stream.EmitRecord(Code, Vals, AbbrevToUse);
00157 }
00158 
00159 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
00160   switch (Kind) {
00161   case Attribute::Alignment:
00162     return bitc::ATTR_KIND_ALIGNMENT;
00163   case Attribute::AlwaysInline:
00164     return bitc::ATTR_KIND_ALWAYS_INLINE;
00165   case Attribute::Builtin:
00166     return bitc::ATTR_KIND_BUILTIN;
00167   case Attribute::ByVal:
00168     return bitc::ATTR_KIND_BY_VAL;
00169   case Attribute::Convergent:
00170     return bitc::ATTR_KIND_CONVERGENT;
00171   case Attribute::InAlloca:
00172     return bitc::ATTR_KIND_IN_ALLOCA;
00173   case Attribute::Cold:
00174     return bitc::ATTR_KIND_COLD;
00175   case Attribute::InlineHint:
00176     return bitc::ATTR_KIND_INLINE_HINT;
00177   case Attribute::InReg:
00178     return bitc::ATTR_KIND_IN_REG;
00179   case Attribute::JumpTable:
00180     return bitc::ATTR_KIND_JUMP_TABLE;
00181   case Attribute::MinSize:
00182     return bitc::ATTR_KIND_MIN_SIZE;
00183   case Attribute::Naked:
00184     return bitc::ATTR_KIND_NAKED;
00185   case Attribute::Nest:
00186     return bitc::ATTR_KIND_NEST;
00187   case Attribute::NoAlias:
00188     return bitc::ATTR_KIND_NO_ALIAS;
00189   case Attribute::NoBuiltin:
00190     return bitc::ATTR_KIND_NO_BUILTIN;
00191   case Attribute::NoCapture:
00192     return bitc::ATTR_KIND_NO_CAPTURE;
00193   case Attribute::NoDuplicate:
00194     return bitc::ATTR_KIND_NO_DUPLICATE;
00195   case Attribute::NoImplicitFloat:
00196     return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
00197   case Attribute::NoInline:
00198     return bitc::ATTR_KIND_NO_INLINE;
00199   case Attribute::NonLazyBind:
00200     return bitc::ATTR_KIND_NON_LAZY_BIND;
00201   case Attribute::NonNull:
00202     return bitc::ATTR_KIND_NON_NULL;
00203   case Attribute::Dereferenceable:
00204     return bitc::ATTR_KIND_DEREFERENCEABLE;
00205   case Attribute::DereferenceableOrNull:
00206     return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
00207   case Attribute::NoRedZone:
00208     return bitc::ATTR_KIND_NO_RED_ZONE;
00209   case Attribute::NoReturn:
00210     return bitc::ATTR_KIND_NO_RETURN;
00211   case Attribute::NoUnwind:
00212     return bitc::ATTR_KIND_NO_UNWIND;
00213   case Attribute::OptimizeForSize:
00214     return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
00215   case Attribute::OptimizeNone:
00216     return bitc::ATTR_KIND_OPTIMIZE_NONE;
00217   case Attribute::ReadNone:
00218     return bitc::ATTR_KIND_READ_NONE;
00219   case Attribute::ReadOnly:
00220     return bitc::ATTR_KIND_READ_ONLY;
00221   case Attribute::Returned:
00222     return bitc::ATTR_KIND_RETURNED;
00223   case Attribute::ReturnsTwice:
00224     return bitc::ATTR_KIND_RETURNS_TWICE;
00225   case Attribute::SExt:
00226     return bitc::ATTR_KIND_S_EXT;
00227   case Attribute::StackAlignment:
00228     return bitc::ATTR_KIND_STACK_ALIGNMENT;
00229   case Attribute::StackProtect:
00230     return bitc::ATTR_KIND_STACK_PROTECT;
00231   case Attribute::StackProtectReq:
00232     return bitc::ATTR_KIND_STACK_PROTECT_REQ;
00233   case Attribute::StackProtectStrong:
00234     return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
00235   case Attribute::StructRet:
00236     return bitc::ATTR_KIND_STRUCT_RET;
00237   case Attribute::SanitizeAddress:
00238     return bitc::ATTR_KIND_SANITIZE_ADDRESS;
00239   case Attribute::SanitizeThread:
00240     return bitc::ATTR_KIND_SANITIZE_THREAD;
00241   case Attribute::SanitizeMemory:
00242     return bitc::ATTR_KIND_SANITIZE_MEMORY;
00243   case Attribute::UWTable:
00244     return bitc::ATTR_KIND_UW_TABLE;
00245   case Attribute::ZExt:
00246     return bitc::ATTR_KIND_Z_EXT;
00247   case Attribute::EndAttrKinds:
00248     llvm_unreachable("Can not encode end-attribute kinds marker.");
00249   case Attribute::None:
00250     llvm_unreachable("Can not encode none-attribute.");
00251   }
00252 
00253   llvm_unreachable("Trying to encode unknown attribute");
00254 }
00255 
00256 static void WriteAttributeGroupTable(const ValueEnumerator &VE,
00257                                      BitstreamWriter &Stream) {
00258   const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
00259   if (AttrGrps.empty()) return;
00260 
00261   Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
00262 
00263   SmallVector<uint64_t, 64> Record;
00264   for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
00265     AttributeSet AS = AttrGrps[i];
00266     for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
00267       AttributeSet A = AS.getSlotAttributes(i);
00268 
00269       Record.push_back(VE.getAttributeGroupID(A));
00270       Record.push_back(AS.getSlotIndex(i));
00271 
00272       for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
00273            I != E; ++I) {
00274         Attribute Attr = *I;
00275         if (Attr.isEnumAttribute()) {
00276           Record.push_back(0);
00277           Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
00278         } else if (Attr.isIntAttribute()) {
00279           Record.push_back(1);
00280           Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
00281           Record.push_back(Attr.getValueAsInt());
00282         } else {
00283           StringRef Kind = Attr.getKindAsString();
00284           StringRef Val = Attr.getValueAsString();
00285 
00286           Record.push_back(Val.empty() ? 3 : 4);
00287           Record.append(Kind.begin(), Kind.end());
00288           Record.push_back(0);
00289           if (!Val.empty()) {
00290             Record.append(Val.begin(), Val.end());
00291             Record.push_back(0);
00292           }
00293         }
00294       }
00295 
00296       Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
00297       Record.clear();
00298     }
00299   }
00300 
00301   Stream.ExitBlock();
00302 }
00303 
00304 static void WriteAttributeTable(const ValueEnumerator &VE,
00305                                 BitstreamWriter &Stream) {
00306   const std::vector<AttributeSet> &Attrs = VE.getAttributes();
00307   if (Attrs.empty()) return;
00308 
00309   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
00310 
00311   SmallVector<uint64_t, 64> Record;
00312   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
00313     const AttributeSet &A = Attrs[i];
00314     for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
00315       Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
00316 
00317     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
00318     Record.clear();
00319   }
00320 
00321   Stream.ExitBlock();
00322 }
00323 
00324 /// WriteTypeTable - Write out the type table for a module.
00325 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
00326   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
00327 
00328   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
00329   SmallVector<uint64_t, 64> TypeVals;
00330 
00331   uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
00332 
00333   // Abbrev for TYPE_CODE_POINTER.
00334   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
00335   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
00336   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
00337   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
00338   unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
00339 
00340   // Abbrev for TYPE_CODE_FUNCTION.
00341   Abbv = new BitCodeAbbrev();
00342   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
00343   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
00344   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00345   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
00346 
00347   unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
00348 
00349   // Abbrev for TYPE_CODE_STRUCT_ANON.
00350   Abbv = new BitCodeAbbrev();
00351   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
00352   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
00353   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00354   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
00355 
00356   unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
00357 
00358   // Abbrev for TYPE_CODE_STRUCT_NAME.
00359   Abbv = new BitCodeAbbrev();
00360   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
00361   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00362   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
00363   unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
00364 
00365   // Abbrev for TYPE_CODE_STRUCT_NAMED.
00366   Abbv = new BitCodeAbbrev();
00367   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
00368   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
00369   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00370   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
00371 
00372   unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
00373 
00374   // Abbrev for TYPE_CODE_ARRAY.
00375   Abbv = new BitCodeAbbrev();
00376   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
00377   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
00378   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
00379 
00380   unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
00381 
00382   // Emit an entry count so the reader can reserve space.
00383   TypeVals.push_back(TypeList.size());
00384   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
00385   TypeVals.clear();
00386 
00387   // Loop over all of the types, emitting each in turn.
00388   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
00389     Type *T = TypeList[i];
00390     int AbbrevToUse = 0;
00391     unsigned Code = 0;
00392 
00393     switch (T->getTypeID()) {
00394     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;      break;
00395     case Type::HalfTyID:      Code = bitc::TYPE_CODE_HALF;      break;
00396     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;     break;
00397     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE;    break;
00398     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80;  break;
00399     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128;     break;
00400     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
00401     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;     break;
00402     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA;  break;
00403     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX;   break;
00404     case Type::IntegerTyID:
00405       // INTEGER: [width]
00406       Code = bitc::TYPE_CODE_INTEGER;
00407       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
00408       break;
00409     case Type::PointerTyID: {
00410       PointerType *PTy = cast<PointerType>(T);
00411       // POINTER: [pointee type, address space]
00412       Code = bitc::TYPE_CODE_POINTER;
00413       TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
00414       unsigned AddressSpace = PTy->getAddressSpace();
00415       TypeVals.push_back(AddressSpace);
00416       if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
00417       break;
00418     }
00419     case Type::FunctionTyID: {
00420       FunctionType *FT = cast<FunctionType>(T);
00421       // FUNCTION: [isvararg, retty, paramty x N]
00422       Code = bitc::TYPE_CODE_FUNCTION;
00423       TypeVals.push_back(FT->isVarArg());
00424       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
00425       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
00426         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
00427       AbbrevToUse = FunctionAbbrev;
00428       break;
00429     }
00430     case Type::StructTyID: {
00431       StructType *ST = cast<StructType>(T);
00432       // STRUCT: [ispacked, eltty x N]
00433       TypeVals.push_back(ST->isPacked());
00434       // Output all of the element types.
00435       for (StructType::element_iterator I = ST->element_begin(),
00436            E = ST->element_end(); I != E; ++I)
00437         TypeVals.push_back(VE.getTypeID(*I));
00438 
00439       if (ST->isLiteral()) {
00440         Code = bitc::TYPE_CODE_STRUCT_ANON;
00441         AbbrevToUse = StructAnonAbbrev;
00442       } else {
00443         if (ST->isOpaque()) {
00444           Code = bitc::TYPE_CODE_OPAQUE;
00445         } else {
00446           Code = bitc::TYPE_CODE_STRUCT_NAMED;
00447           AbbrevToUse = StructNamedAbbrev;
00448         }
00449 
00450         // Emit the name if it is present.
00451         if (!ST->getName().empty())
00452           WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
00453                             StructNameAbbrev, Stream);
00454       }
00455       break;
00456     }
00457     case Type::ArrayTyID: {
00458       ArrayType *AT = cast<ArrayType>(T);
00459       // ARRAY: [numelts, eltty]
00460       Code = bitc::TYPE_CODE_ARRAY;
00461       TypeVals.push_back(AT->getNumElements());
00462       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
00463       AbbrevToUse = ArrayAbbrev;
00464       break;
00465     }
00466     case Type::VectorTyID: {
00467       VectorType *VT = cast<VectorType>(T);
00468       // VECTOR [numelts, eltty]
00469       Code = bitc::TYPE_CODE_VECTOR;
00470       TypeVals.push_back(VT->getNumElements());
00471       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
00472       break;
00473     }
00474     }
00475 
00476     // Emit the finished record.
00477     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
00478     TypeVals.clear();
00479   }
00480 
00481   Stream.ExitBlock();
00482 }
00483 
00484 static unsigned getEncodedLinkage(const GlobalValue &GV) {
00485   switch (GV.getLinkage()) {
00486   case GlobalValue::ExternalLinkage:
00487     return 0;
00488   case GlobalValue::WeakAnyLinkage:
00489     return 16;
00490   case GlobalValue::AppendingLinkage:
00491     return 2;
00492   case GlobalValue::InternalLinkage:
00493     return 3;
00494   case GlobalValue::LinkOnceAnyLinkage:
00495     return 18;
00496   case GlobalValue::ExternalWeakLinkage:
00497     return 7;
00498   case GlobalValue::CommonLinkage:
00499     return 8;
00500   case GlobalValue::PrivateLinkage:
00501     return 9;
00502   case GlobalValue::WeakODRLinkage:
00503     return 17;
00504   case GlobalValue::LinkOnceODRLinkage:
00505     return 19;
00506   case GlobalValue::AvailableExternallyLinkage:
00507     return 12;
00508   }
00509   llvm_unreachable("Invalid linkage");
00510 }
00511 
00512 static unsigned getEncodedVisibility(const GlobalValue &GV) {
00513   switch (GV.getVisibility()) {
00514   case GlobalValue::DefaultVisibility:   return 0;
00515   case GlobalValue::HiddenVisibility:    return 1;
00516   case GlobalValue::ProtectedVisibility: return 2;
00517   }
00518   llvm_unreachable("Invalid visibility");
00519 }
00520 
00521 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
00522   switch (GV.getDLLStorageClass()) {
00523   case GlobalValue::DefaultStorageClass:   return 0;
00524   case GlobalValue::DLLImportStorageClass: return 1;
00525   case GlobalValue::DLLExportStorageClass: return 2;
00526   }
00527   llvm_unreachable("Invalid DLL storage class");
00528 }
00529 
00530 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
00531   switch (GV.getThreadLocalMode()) {
00532     case GlobalVariable::NotThreadLocal:         return 0;
00533     case GlobalVariable::GeneralDynamicTLSModel: return 1;
00534     case GlobalVariable::LocalDynamicTLSModel:   return 2;
00535     case GlobalVariable::InitialExecTLSModel:    return 3;
00536     case GlobalVariable::LocalExecTLSModel:      return 4;
00537   }
00538   llvm_unreachable("Invalid TLS model");
00539 }
00540 
00541 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
00542   switch (C.getSelectionKind()) {
00543   case Comdat::Any:
00544     return bitc::COMDAT_SELECTION_KIND_ANY;
00545   case Comdat::ExactMatch:
00546     return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
00547   case Comdat::Largest:
00548     return bitc::COMDAT_SELECTION_KIND_LARGEST;
00549   case Comdat::NoDuplicates:
00550     return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
00551   case Comdat::SameSize:
00552     return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
00553   }
00554   llvm_unreachable("Invalid selection kind");
00555 }
00556 
00557 static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) {
00558   SmallVector<uint16_t, 64> Vals;
00559   for (const Comdat *C : VE.getComdats()) {
00560     // COMDAT: [selection_kind, name]
00561     Vals.push_back(getEncodedComdatSelectionKind(*C));
00562     size_t Size = C->getName().size();
00563     assert(isUInt<16>(Size));
00564     Vals.push_back(Size);
00565     for (char Chr : C->getName())
00566       Vals.push_back((unsigned char)Chr);
00567     Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
00568     Vals.clear();
00569   }
00570 }
00571 
00572 // Emit top-level description of module, including target triple, inline asm,
00573 // descriptors for global variables, and function prototype info.
00574 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
00575                             BitstreamWriter &Stream) {
00576   // Emit various pieces of data attached to a module.
00577   if (!M->getTargetTriple().empty())
00578     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
00579                       0/*TODO*/, Stream);
00580   const std::string &DL = M->getDataLayoutStr();
00581   if (!DL.empty())
00582     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream);
00583   if (!M->getModuleInlineAsm().empty())
00584     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
00585                       0/*TODO*/, Stream);
00586 
00587   // Emit information about sections and GC, computing how many there are. Also
00588   // compute the maximum alignment value.
00589   std::map<std::string, unsigned> SectionMap;
00590   std::map<std::string, unsigned> GCMap;
00591   unsigned MaxAlignment = 0;
00592   unsigned MaxGlobalType = 0;
00593   for (const GlobalValue &GV : M->globals()) {
00594     MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
00595     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
00596     if (GV.hasSection()) {
00597       // Give section names unique ID's.
00598       unsigned &Entry = SectionMap[GV.getSection()];
00599       if (!Entry) {
00600         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
00601                           0/*TODO*/, Stream);
00602         Entry = SectionMap.size();
00603       }
00604     }
00605   }
00606   for (const Function &F : *M) {
00607     MaxAlignment = std::max(MaxAlignment, F.getAlignment());
00608     if (F.hasSection()) {
00609       // Give section names unique ID's.
00610       unsigned &Entry = SectionMap[F.getSection()];
00611       if (!Entry) {
00612         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
00613                           0/*TODO*/, Stream);
00614         Entry = SectionMap.size();
00615       }
00616     }
00617     if (F.hasGC()) {
00618       // Same for GC names.
00619       unsigned &Entry = GCMap[F.getGC()];
00620       if (!Entry) {
00621         WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(),
00622                           0/*TODO*/, Stream);
00623         Entry = GCMap.size();
00624       }
00625     }
00626   }
00627 
00628   // Emit abbrev for globals, now that we know # sections and max alignment.
00629   unsigned SimpleGVarAbbrev = 0;
00630   if (!M->global_empty()) {
00631     // Add an abbrev for common globals with no visibility or thread localness.
00632     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
00633     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
00634     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00635                               Log2_32_Ceil(MaxGlobalType+1)));
00636     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // AddrSpace << 2
00637                                                            //| explicitType << 1
00638                                                            //| constant
00639     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Initializer.
00640     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
00641     if (MaxAlignment == 0)                                 // Alignment.
00642       Abbv->Add(BitCodeAbbrevOp(0));
00643     else {
00644       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
00645       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00646                                Log2_32_Ceil(MaxEncAlignment+1)));
00647     }
00648     if (SectionMap.empty())                                    // Section.
00649       Abbv->Add(BitCodeAbbrevOp(0));
00650     else
00651       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00652                                Log2_32_Ceil(SectionMap.size()+1)));
00653     // Don't bother emitting vis + thread local.
00654     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
00655   }
00656 
00657   // Emit the global variable information.
00658   SmallVector<unsigned, 64> Vals;
00659   for (const GlobalVariable &GV : M->globals()) {
00660     unsigned AbbrevToUse = 0;
00661 
00662     // GLOBALVAR: [type, isconst, initid,
00663     //             linkage, alignment, section, visibility, threadlocal,
00664     //             unnamed_addr, externally_initialized, dllstorageclass,
00665     //             comdat]
00666     Vals.push_back(VE.getTypeID(GV.getValueType()));
00667     Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
00668     Vals.push_back(GV.isDeclaration() ? 0 :
00669                    (VE.getValueID(GV.getInitializer()) + 1));
00670     Vals.push_back(getEncodedLinkage(GV));
00671     Vals.push_back(Log2_32(GV.getAlignment())+1);
00672     Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
00673     if (GV.isThreadLocal() ||
00674         GV.getVisibility() != GlobalValue::DefaultVisibility ||
00675         GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
00676         GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
00677         GV.hasComdat()) {
00678       Vals.push_back(getEncodedVisibility(GV));
00679       Vals.push_back(getEncodedThreadLocalMode(GV));
00680       Vals.push_back(GV.hasUnnamedAddr());
00681       Vals.push_back(GV.isExternallyInitialized());
00682       Vals.push_back(getEncodedDLLStorageClass(GV));
00683       Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
00684     } else {
00685       AbbrevToUse = SimpleGVarAbbrev;
00686     }
00687 
00688     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
00689     Vals.clear();
00690   }
00691 
00692   // Emit the function proto information.
00693   for (const Function &F : *M) {
00694     // FUNCTION:  [type, callingconv, isproto, linkage, paramattrs, alignment,
00695     //             section, visibility, gc, unnamed_addr, prologuedata,
00696     //             dllstorageclass, comdat, prefixdata]
00697     Vals.push_back(VE.getTypeID(F.getFunctionType()));
00698     Vals.push_back(F.getCallingConv());
00699     Vals.push_back(F.isDeclaration());
00700     Vals.push_back(getEncodedLinkage(F));
00701     Vals.push_back(VE.getAttributeID(F.getAttributes()));
00702     Vals.push_back(Log2_32(F.getAlignment())+1);
00703     Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
00704     Vals.push_back(getEncodedVisibility(F));
00705     Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
00706     Vals.push_back(F.hasUnnamedAddr());
00707     Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
00708                                        : 0);
00709     Vals.push_back(getEncodedDLLStorageClass(F));
00710     Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
00711     Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
00712                                      : 0);
00713 
00714     unsigned AbbrevToUse = 0;
00715     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
00716     Vals.clear();
00717   }
00718 
00719   // Emit the alias information.
00720   for (const GlobalAlias &A : M->aliases()) {
00721     // ALIAS: [alias type, aliasee val#, linkage, visibility]
00722     Vals.push_back(VE.getTypeID(A.getType()));
00723     Vals.push_back(VE.getValueID(A.getAliasee()));
00724     Vals.push_back(getEncodedLinkage(A));
00725     Vals.push_back(getEncodedVisibility(A));
00726     Vals.push_back(getEncodedDLLStorageClass(A));
00727     Vals.push_back(getEncodedThreadLocalMode(A));
00728     Vals.push_back(A.hasUnnamedAddr());
00729     unsigned AbbrevToUse = 0;
00730     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
00731     Vals.clear();
00732   }
00733 }
00734 
00735 static uint64_t GetOptimizationFlags(const Value *V) {
00736   uint64_t Flags = 0;
00737 
00738   if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
00739     if (OBO->hasNoSignedWrap())
00740       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
00741     if (OBO->hasNoUnsignedWrap())
00742       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
00743   } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
00744     if (PEO->isExact())
00745       Flags |= 1 << bitc::PEO_EXACT;
00746   } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
00747     if (FPMO->hasUnsafeAlgebra())
00748       Flags |= FastMathFlags::UnsafeAlgebra;
00749     if (FPMO->hasNoNaNs())
00750       Flags |= FastMathFlags::NoNaNs;
00751     if (FPMO->hasNoInfs())
00752       Flags |= FastMathFlags::NoInfs;
00753     if (FPMO->hasNoSignedZeros())
00754       Flags |= FastMathFlags::NoSignedZeros;
00755     if (FPMO->hasAllowReciprocal())
00756       Flags |= FastMathFlags::AllowReciprocal;
00757   }
00758 
00759   return Flags;
00760 }
00761 
00762 static void WriteValueAsMetadata(const ValueAsMetadata *MD,
00763                                  const ValueEnumerator &VE,
00764                                  BitstreamWriter &Stream,
00765                                  SmallVectorImpl<uint64_t> &Record) {
00766   // Mimic an MDNode with a value as one operand.
00767   Value *V = MD->getValue();
00768   Record.push_back(VE.getTypeID(V->getType()));
00769   Record.push_back(VE.getValueID(V));
00770   Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
00771   Record.clear();
00772 }
00773 
00774 static void WriteMDTuple(const MDTuple *N, const ValueEnumerator &VE,
00775                          BitstreamWriter &Stream,
00776                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
00777   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
00778     Metadata *MD = N->getOperand(i);
00779     assert(!(MD && isa<LocalAsMetadata>(MD)) &&
00780            "Unexpected function-local metadata");
00781     Record.push_back(VE.getMetadataOrNullID(MD));
00782   }
00783   Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
00784                                     : bitc::METADATA_NODE,
00785                     Record, Abbrev);
00786   Record.clear();
00787 }
00788 
00789 static void WriteDILocation(const DILocation *N, const ValueEnumerator &VE,
00790                             BitstreamWriter &Stream,
00791                             SmallVectorImpl<uint64_t> &Record,
00792                             unsigned Abbrev) {
00793   Record.push_back(N->isDistinct());
00794   Record.push_back(N->getLine());
00795   Record.push_back(N->getColumn());
00796   Record.push_back(VE.getMetadataID(N->getScope()));
00797   Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
00798 
00799   Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
00800   Record.clear();
00801 }
00802 
00803 static void WriteGenericDINode(const GenericDINode *N,
00804                                const ValueEnumerator &VE,
00805                                BitstreamWriter &Stream,
00806                                SmallVectorImpl<uint64_t> &Record,
00807                                unsigned Abbrev) {
00808   Record.push_back(N->isDistinct());
00809   Record.push_back(N->getTag());
00810   Record.push_back(0); // Per-tag version field; unused for now.
00811 
00812   for (auto &I : N->operands())
00813     Record.push_back(VE.getMetadataOrNullID(I));
00814 
00815   Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
00816   Record.clear();
00817 }
00818 
00819 static uint64_t rotateSign(int64_t I) {
00820   uint64_t U = I;
00821   return I < 0 ? ~(U << 1) : U << 1;
00822 }
00823 
00824 static void WriteDISubrange(const DISubrange *N, const ValueEnumerator &,
00825                             BitstreamWriter &Stream,
00826                             SmallVectorImpl<uint64_t> &Record,
00827                             unsigned Abbrev) {
00828   Record.push_back(N->isDistinct());
00829   Record.push_back(N->getCount());
00830   Record.push_back(rotateSign(N->getLowerBound()));
00831 
00832   Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
00833   Record.clear();
00834 }
00835 
00836 static void WriteDIEnumerator(const DIEnumerator *N, const ValueEnumerator &VE,
00837                               BitstreamWriter &Stream,
00838                               SmallVectorImpl<uint64_t> &Record,
00839                               unsigned Abbrev) {
00840   Record.push_back(N->isDistinct());
00841   Record.push_back(rotateSign(N->getValue()));
00842   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
00843 
00844   Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
00845   Record.clear();
00846 }
00847 
00848 static void WriteDIBasicType(const DIBasicType *N, const ValueEnumerator &VE,
00849                              BitstreamWriter &Stream,
00850                              SmallVectorImpl<uint64_t> &Record,
00851                              unsigned Abbrev) {
00852   Record.push_back(N->isDistinct());
00853   Record.push_back(N->getTag());
00854   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
00855   Record.push_back(N->getSizeInBits());
00856   Record.push_back(N->getAlignInBits());
00857   Record.push_back(N->getEncoding());
00858 
00859   Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
00860   Record.clear();
00861 }
00862 
00863 static void WriteDIDerivedType(const DIDerivedType *N,
00864                                const ValueEnumerator &VE,
00865                                BitstreamWriter &Stream,
00866                                SmallVectorImpl<uint64_t> &Record,
00867                                unsigned Abbrev) {
00868   Record.push_back(N->isDistinct());
00869   Record.push_back(N->getTag());
00870   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
00871   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
00872   Record.push_back(N->getLine());
00873   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
00874   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
00875   Record.push_back(N->getSizeInBits());
00876   Record.push_back(N->getAlignInBits());
00877   Record.push_back(N->getOffsetInBits());
00878   Record.push_back(N->getFlags());
00879   Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
00880 
00881   Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
00882   Record.clear();
00883 }
00884 
00885 static void WriteDICompositeType(const DICompositeType *N,
00886                                  const ValueEnumerator &VE,
00887                                  BitstreamWriter &Stream,
00888                                  SmallVectorImpl<uint64_t> &Record,
00889                                  unsigned Abbrev) {
00890   Record.push_back(N->isDistinct());
00891   Record.push_back(N->getTag());
00892   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
00893   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
00894   Record.push_back(N->getLine());
00895   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
00896   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
00897   Record.push_back(N->getSizeInBits());
00898   Record.push_back(N->getAlignInBits());
00899   Record.push_back(N->getOffsetInBits());
00900   Record.push_back(N->getFlags());
00901   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
00902   Record.push_back(N->getRuntimeLang());
00903   Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
00904   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
00905   Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
00906 
00907   Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
00908   Record.clear();
00909 }
00910 
00911 static void WriteDISubroutineType(const DISubroutineType *N,
00912                                   const ValueEnumerator &VE,
00913                                   BitstreamWriter &Stream,
00914                                   SmallVectorImpl<uint64_t> &Record,
00915                                   unsigned Abbrev) {
00916   Record.push_back(N->isDistinct());
00917   Record.push_back(N->getFlags());
00918   Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
00919 
00920   Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
00921   Record.clear();
00922 }
00923 
00924 static void WriteDIFile(const DIFile *N, const ValueEnumerator &VE,
00925                         BitstreamWriter &Stream,
00926                         SmallVectorImpl<uint64_t> &Record, unsigned Abbrev) {
00927   Record.push_back(N->isDistinct());
00928   Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
00929   Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
00930 
00931   Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
00932   Record.clear();
00933 }
00934 
00935 static void WriteDICompileUnit(const DICompileUnit *N,
00936                                const ValueEnumerator &VE,
00937                                BitstreamWriter &Stream,
00938                                SmallVectorImpl<uint64_t> &Record,
00939                                unsigned Abbrev) {
00940   Record.push_back(N->isDistinct());
00941   Record.push_back(N->getSourceLanguage());
00942   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
00943   Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
00944   Record.push_back(N->isOptimized());
00945   Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
00946   Record.push_back(N->getRuntimeVersion());
00947   Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
00948   Record.push_back(N->getEmissionKind());
00949   Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
00950   Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
00951   Record.push_back(VE.getMetadataOrNullID(N->getSubprograms().get()));
00952   Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
00953   Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
00954   Record.push_back(N->getDWOId());
00955 
00956   Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
00957   Record.clear();
00958 }
00959 
00960 static void WriteDISubprogram(const DISubprogram *N, const ValueEnumerator &VE,
00961                               BitstreamWriter &Stream,
00962                               SmallVectorImpl<uint64_t> &Record,
00963                               unsigned Abbrev) {
00964   Record.push_back(N->isDistinct());
00965   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
00966   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
00967   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
00968   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
00969   Record.push_back(N->getLine());
00970   Record.push_back(VE.getMetadataOrNullID(N->getType()));
00971   Record.push_back(N->isLocalToUnit());
00972   Record.push_back(N->isDefinition());
00973   Record.push_back(N->getScopeLine());
00974   Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
00975   Record.push_back(N->getVirtuality());
00976   Record.push_back(N->getVirtualIndex());
00977   Record.push_back(N->getFlags());
00978   Record.push_back(N->isOptimized());
00979   Record.push_back(VE.getMetadataOrNullID(N->getRawFunction()));
00980   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
00981   Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
00982   Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
00983 
00984   Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
00985   Record.clear();
00986 }
00987 
00988 static void WriteDILexicalBlock(const DILexicalBlock *N,
00989                                 const ValueEnumerator &VE,
00990                                 BitstreamWriter &Stream,
00991                                 SmallVectorImpl<uint64_t> &Record,
00992                                 unsigned Abbrev) {
00993   Record.push_back(N->isDistinct());
00994   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
00995   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
00996   Record.push_back(N->getLine());
00997   Record.push_back(N->getColumn());
00998 
00999   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
01000   Record.clear();
01001 }
01002 
01003 static void WriteDILexicalBlockFile(const DILexicalBlockFile *N,
01004                                     const ValueEnumerator &VE,
01005                                     BitstreamWriter &Stream,
01006                                     SmallVectorImpl<uint64_t> &Record,
01007                                     unsigned Abbrev) {
01008   Record.push_back(N->isDistinct());
01009   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
01010   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
01011   Record.push_back(N->getDiscriminator());
01012 
01013   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
01014   Record.clear();
01015 }
01016 
01017 static void WriteDINamespace(const DINamespace *N, const ValueEnumerator &VE,
01018                              BitstreamWriter &Stream,
01019                              SmallVectorImpl<uint64_t> &Record,
01020                              unsigned Abbrev) {
01021   Record.push_back(N->isDistinct());
01022   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
01023   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
01024   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
01025   Record.push_back(N->getLine());
01026 
01027   Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
01028   Record.clear();
01029 }
01030 
01031 static void WriteDITemplateTypeParameter(const DITemplateTypeParameter *N,
01032                                          const ValueEnumerator &VE,
01033                                          BitstreamWriter &Stream,
01034                                          SmallVectorImpl<uint64_t> &Record,
01035                                          unsigned Abbrev) {
01036   Record.push_back(N->isDistinct());
01037   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
01038   Record.push_back(VE.getMetadataOrNullID(N->getType()));
01039 
01040   Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
01041   Record.clear();
01042 }
01043 
01044 static void WriteDITemplateValueParameter(const DITemplateValueParameter *N,
01045                                           const ValueEnumerator &VE,
01046                                           BitstreamWriter &Stream,
01047                                           SmallVectorImpl<uint64_t> &Record,
01048                                           unsigned Abbrev) {
01049   Record.push_back(N->isDistinct());
01050   Record.push_back(N->getTag());
01051   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
01052   Record.push_back(VE.getMetadataOrNullID(N->getType()));
01053   Record.push_back(VE.getMetadataOrNullID(N->getValue()));
01054 
01055   Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
01056   Record.clear();
01057 }
01058 
01059 static void WriteDIGlobalVariable(const DIGlobalVariable *N,
01060                                   const ValueEnumerator &VE,
01061                                   BitstreamWriter &Stream,
01062                                   SmallVectorImpl<uint64_t> &Record,
01063                                   unsigned Abbrev) {
01064   Record.push_back(N->isDistinct());
01065   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
01066   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
01067   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
01068   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
01069   Record.push_back(N->getLine());
01070   Record.push_back(VE.getMetadataOrNullID(N->getType()));
01071   Record.push_back(N->isLocalToUnit());
01072   Record.push_back(N->isDefinition());
01073   Record.push_back(VE.getMetadataOrNullID(N->getRawVariable()));
01074   Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
01075 
01076   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
01077   Record.clear();
01078 }
01079 
01080 static void WriteDILocalVariable(const DILocalVariable *N,
01081                                  const ValueEnumerator &VE,
01082                                  BitstreamWriter &Stream,
01083                                  SmallVectorImpl<uint64_t> &Record,
01084                                  unsigned Abbrev) {
01085   Record.push_back(N->isDistinct());
01086   Record.push_back(N->getTag());
01087   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
01088   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
01089   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
01090   Record.push_back(N->getLine());
01091   Record.push_back(VE.getMetadataOrNullID(N->getType()));
01092   Record.push_back(N->getArg());
01093   Record.push_back(N->getFlags());
01094 
01095   Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
01096   Record.clear();
01097 }
01098 
01099 static void WriteDIExpression(const DIExpression *N, const ValueEnumerator &,
01100                               BitstreamWriter &Stream,
01101                               SmallVectorImpl<uint64_t> &Record,
01102                               unsigned Abbrev) {
01103   Record.reserve(N->getElements().size() + 1);
01104 
01105   Record.push_back(N->isDistinct());
01106   Record.append(N->elements_begin(), N->elements_end());
01107 
01108   Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
01109   Record.clear();
01110 }
01111 
01112 static void WriteDIObjCProperty(const DIObjCProperty *N,
01113                                 const ValueEnumerator &VE,
01114                                 BitstreamWriter &Stream,
01115                                 SmallVectorImpl<uint64_t> &Record,
01116                                 unsigned Abbrev) {
01117   Record.push_back(N->isDistinct());
01118   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
01119   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
01120   Record.push_back(N->getLine());
01121   Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
01122   Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
01123   Record.push_back(N->getAttributes());
01124   Record.push_back(VE.getMetadataOrNullID(N->getType()));
01125 
01126   Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
01127   Record.clear();
01128 }
01129 
01130 static void WriteDIImportedEntity(const DIImportedEntity *N,
01131                                   const ValueEnumerator &VE,
01132                                   BitstreamWriter &Stream,
01133                                   SmallVectorImpl<uint64_t> &Record,
01134                                   unsigned Abbrev) {
01135   Record.push_back(N->isDistinct());
01136   Record.push_back(N->getTag());
01137   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
01138   Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
01139   Record.push_back(N->getLine());
01140   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
01141 
01142   Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
01143   Record.clear();
01144 }
01145 
01146 static void WriteModuleMetadata(const Module *M,
01147                                 const ValueEnumerator &VE,
01148                                 BitstreamWriter &Stream) {
01149   const auto &MDs = VE.getMDs();
01150   if (MDs.empty() && M->named_metadata_empty())
01151     return;
01152 
01153   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
01154 
01155   unsigned MDSAbbrev = 0;
01156   if (VE.hasMDString()) {
01157     // Abbrev for METADATA_STRING.
01158     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01159     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
01160     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01161     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
01162     MDSAbbrev = Stream.EmitAbbrev(Abbv);
01163   }
01164 
01165   // Initialize MDNode abbreviations.
01166 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
01167 #include "llvm/IR/Metadata.def"
01168 
01169   if (VE.hasDILocation()) {
01170     // Abbrev for METADATA_LOCATION.
01171     //
01172     // Assume the column is usually under 128, and always output the inlined-at
01173     // location (it's never more expensive than building an array size 1).
01174     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01175     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
01176     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
01177     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
01178     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01179     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
01180     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
01181     DILocationAbbrev = Stream.EmitAbbrev(Abbv);
01182   }
01183 
01184   if (VE.hasGenericDINode()) {
01185     // Abbrev for METADATA_GENERIC_DEBUG.
01186     //
01187     // Assume the column is usually under 128, and always output the inlined-at
01188     // location (it's never more expensive than building an array size 1).
01189     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01190     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
01191     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
01192     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
01193     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
01194     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
01195     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01196     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
01197     GenericDINodeAbbrev = Stream.EmitAbbrev(Abbv);
01198   }
01199 
01200   unsigned NameAbbrev = 0;
01201   if (!M->named_metadata_empty()) {
01202     // Abbrev for METADATA_NAME.
01203     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01204     Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
01205     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01206     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
01207     NameAbbrev = Stream.EmitAbbrev(Abbv);
01208   }
01209 
01210   SmallVector<uint64_t, 64> Record;
01211   for (const Metadata *MD : MDs) {
01212     if (const MDNode *N = dyn_cast<MDNode>(MD)) {
01213       assert(N->isResolved() && "Expected forward references to be resolved");
01214 
01215       switch (N->getMetadataID()) {
01216       default:
01217         llvm_unreachable("Invalid MDNode subclass");
01218 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
01219   case Metadata::CLASS##Kind:                                                  \
01220     Write##CLASS(cast<CLASS>(N), VE, Stream, Record, CLASS##Abbrev);           \
01221     continue;
01222 #include "llvm/IR/Metadata.def"
01223       }
01224     }
01225     if (const auto *MDC = dyn_cast<ConstantAsMetadata>(MD)) {
01226       WriteValueAsMetadata(MDC, VE, Stream, Record);
01227       continue;
01228     }
01229     const MDString *MDS = cast<MDString>(MD);
01230     // Code: [strchar x N]
01231     Record.append(MDS->bytes_begin(), MDS->bytes_end());
01232 
01233     // Emit the finished record.
01234     Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
01235     Record.clear();
01236   }
01237 
01238   // Write named metadata.
01239   for (const NamedMDNode &NMD : M->named_metadata()) {
01240     // Write name.
01241     StringRef Str = NMD.getName();
01242     Record.append(Str.bytes_begin(), Str.bytes_end());
01243     Stream.EmitRecord(bitc::METADATA_NAME, Record, NameAbbrev);
01244     Record.clear();
01245 
01246     // Write named metadata operands.
01247     for (const MDNode *N : NMD.operands())
01248       Record.push_back(VE.getMetadataID(N));
01249     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
01250     Record.clear();
01251   }
01252 
01253   Stream.ExitBlock();
01254 }
01255 
01256 static void WriteFunctionLocalMetadata(const Function &F,
01257                                        const ValueEnumerator &VE,
01258                                        BitstreamWriter &Stream) {
01259   bool StartedMetadataBlock = false;
01260   SmallVector<uint64_t, 64> Record;
01261   const SmallVectorImpl<const LocalAsMetadata *> &MDs =
01262       VE.getFunctionLocalMDs();
01263   for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
01264     assert(MDs[i] && "Expected valid function-local metadata");
01265     if (!StartedMetadataBlock) {
01266       Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
01267       StartedMetadataBlock = true;
01268     }
01269     WriteValueAsMetadata(MDs[i], VE, Stream, Record);
01270   }
01271 
01272   if (StartedMetadataBlock)
01273     Stream.ExitBlock();
01274 }
01275 
01276 static void WriteMetadataAttachment(const Function &F,
01277                                     const ValueEnumerator &VE,
01278                                     BitstreamWriter &Stream) {
01279   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
01280 
01281   SmallVector<uint64_t, 64> Record;
01282 
01283   // Write metadata attachments
01284   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
01285   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
01286   F.getAllMetadata(MDs);
01287   if (!MDs.empty()) {
01288     for (const auto &I : MDs) {
01289       Record.push_back(I.first);
01290       Record.push_back(VE.getMetadataID(I.second));
01291     }
01292     Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
01293     Record.clear();
01294   }
01295 
01296   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
01297     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
01298          I != E; ++I) {
01299       MDs.clear();
01300       I->getAllMetadataOtherThanDebugLoc(MDs);
01301 
01302       // If no metadata, ignore instruction.
01303       if (MDs.empty()) continue;
01304 
01305       Record.push_back(VE.getInstructionID(I));
01306 
01307       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
01308         Record.push_back(MDs[i].first);
01309         Record.push_back(VE.getMetadataID(MDs[i].second));
01310       }
01311       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
01312       Record.clear();
01313     }
01314 
01315   Stream.ExitBlock();
01316 }
01317 
01318 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
01319   SmallVector<uint64_t, 64> Record;
01320 
01321   // Write metadata kinds
01322   // METADATA_KIND - [n x [id, name]]
01323   SmallVector<StringRef, 8> Names;
01324   M->getMDKindNames(Names);
01325 
01326   if (Names.empty()) return;
01327 
01328   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
01329 
01330   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
01331     Record.push_back(MDKindID);
01332     StringRef KName = Names[MDKindID];
01333     Record.append(KName.begin(), KName.end());
01334 
01335     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
01336     Record.clear();
01337   }
01338 
01339   Stream.ExitBlock();
01340 }
01341 
01342 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
01343   if ((int64_t)V >= 0)
01344     Vals.push_back(V << 1);
01345   else
01346     Vals.push_back((-V << 1) | 1);
01347 }
01348 
01349 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
01350                            const ValueEnumerator &VE,
01351                            BitstreamWriter &Stream, bool isGlobal) {
01352   if (FirstVal == LastVal) return;
01353 
01354   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
01355 
01356   unsigned AggregateAbbrev = 0;
01357   unsigned String8Abbrev = 0;
01358   unsigned CString7Abbrev = 0;
01359   unsigned CString6Abbrev = 0;
01360   // If this is a constant pool for the module, emit module-specific abbrevs.
01361   if (isGlobal) {
01362     // Abbrev for CST_CODE_AGGREGATE.
01363     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01364     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
01365     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01366     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
01367     AggregateAbbrev = Stream.EmitAbbrev(Abbv);
01368 
01369     // Abbrev for CST_CODE_STRING.
01370     Abbv = new BitCodeAbbrev();
01371     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
01372     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01373     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
01374     String8Abbrev = Stream.EmitAbbrev(Abbv);
01375     // Abbrev for CST_CODE_CSTRING.
01376     Abbv = new BitCodeAbbrev();
01377     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
01378     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01379     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
01380     CString7Abbrev = Stream.EmitAbbrev(Abbv);
01381     // Abbrev for CST_CODE_CSTRING.
01382     Abbv = new BitCodeAbbrev();
01383     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
01384     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01385     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
01386     CString6Abbrev = Stream.EmitAbbrev(Abbv);
01387   }
01388 
01389   SmallVector<uint64_t, 64> Record;
01390 
01391   const ValueEnumerator::ValueList &Vals = VE.getValues();
01392   Type *LastTy = nullptr;
01393   for (unsigned i = FirstVal; i != LastVal; ++i) {
01394     const Value *V = Vals[i].first;
01395     // If we need to switch types, do so now.
01396     if (V->getType() != LastTy) {
01397       LastTy = V->getType();
01398       Record.push_back(VE.getTypeID(LastTy));
01399       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
01400                         CONSTANTS_SETTYPE_ABBREV);
01401       Record.clear();
01402     }
01403 
01404     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
01405       Record.push_back(unsigned(IA->hasSideEffects()) |
01406                        unsigned(IA->isAlignStack()) << 1 |
01407                        unsigned(IA->getDialect()&1) << 2);
01408 
01409       // Add the asm string.
01410       const std::string &AsmStr = IA->getAsmString();
01411       Record.push_back(AsmStr.size());
01412       Record.append(AsmStr.begin(), AsmStr.end());
01413 
01414       // Add the constraint string.
01415       const std::string &ConstraintStr = IA->getConstraintString();
01416       Record.push_back(ConstraintStr.size());
01417       Record.append(ConstraintStr.begin(), ConstraintStr.end());
01418       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
01419       Record.clear();
01420       continue;
01421     }
01422     const Constant *C = cast<Constant>(V);
01423     unsigned Code = -1U;
01424     unsigned AbbrevToUse = 0;
01425     if (C->isNullValue()) {
01426       Code = bitc::CST_CODE_NULL;
01427     } else if (isa<UndefValue>(C)) {
01428       Code = bitc::CST_CODE_UNDEF;
01429     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
01430       if (IV->getBitWidth() <= 64) {
01431         uint64_t V = IV->getSExtValue();
01432         emitSignedInt64(Record, V);
01433         Code = bitc::CST_CODE_INTEGER;
01434         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
01435       } else {                             // Wide integers, > 64 bits in size.
01436         // We have an arbitrary precision integer value to write whose
01437         // bit width is > 64. However, in canonical unsigned integer
01438         // format it is likely that the high bits are going to be zero.
01439         // So, we only write the number of active words.
01440         unsigned NWords = IV->getValue().getActiveWords();
01441         const uint64_t *RawWords = IV->getValue().getRawData();
01442         for (unsigned i = 0; i != NWords; ++i) {
01443           emitSignedInt64(Record, RawWords[i]);
01444         }
01445         Code = bitc::CST_CODE_WIDE_INTEGER;
01446       }
01447     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
01448       Code = bitc::CST_CODE_FLOAT;
01449       Type *Ty = CFP->getType();
01450       if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
01451         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
01452       } else if (Ty->isX86_FP80Ty()) {
01453         // api needed to prevent premature destruction
01454         // bits are not in the same order as a normal i80 APInt, compensate.
01455         APInt api = CFP->getValueAPF().bitcastToAPInt();
01456         const uint64_t *p = api.getRawData();
01457         Record.push_back((p[1] << 48) | (p[0] >> 16));
01458         Record.push_back(p[0] & 0xffffLL);
01459       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
01460         APInt api = CFP->getValueAPF().bitcastToAPInt();
01461         const uint64_t *p = api.getRawData();
01462         Record.push_back(p[0]);
01463         Record.push_back(p[1]);
01464       } else {
01465         assert (0 && "Unknown FP type!");
01466       }
01467     } else if (isa<ConstantDataSequential>(C) &&
01468                cast<ConstantDataSequential>(C)->isString()) {
01469       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
01470       // Emit constant strings specially.
01471       unsigned NumElts = Str->getNumElements();
01472       // If this is a null-terminated string, use the denser CSTRING encoding.
01473       if (Str->isCString()) {
01474         Code = bitc::CST_CODE_CSTRING;
01475         --NumElts;  // Don't encode the null, which isn't allowed by char6.
01476       } else {
01477         Code = bitc::CST_CODE_STRING;
01478         AbbrevToUse = String8Abbrev;
01479       }
01480       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
01481       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
01482       for (unsigned i = 0; i != NumElts; ++i) {
01483         unsigned char V = Str->getElementAsInteger(i);
01484         Record.push_back(V);
01485         isCStr7 &= (V & 128) == 0;
01486         if (isCStrChar6)
01487           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
01488       }
01489 
01490       if (isCStrChar6)
01491         AbbrevToUse = CString6Abbrev;
01492       else if (isCStr7)
01493         AbbrevToUse = CString7Abbrev;
01494     } else if (const ConstantDataSequential *CDS =
01495                   dyn_cast<ConstantDataSequential>(C)) {
01496       Code = bitc::CST_CODE_DATA;
01497       Type *EltTy = CDS->getType()->getElementType();
01498       if (isa<IntegerType>(EltTy)) {
01499         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
01500           Record.push_back(CDS->getElementAsInteger(i));
01501       } else if (EltTy->isFloatTy()) {
01502         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
01503           union { float F; uint32_t I; };
01504           F = CDS->getElementAsFloat(i);
01505           Record.push_back(I);
01506         }
01507       } else {
01508         assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
01509         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
01510           union { double F; uint64_t I; };
01511           F = CDS->getElementAsDouble(i);
01512           Record.push_back(I);
01513         }
01514       }
01515     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
01516                isa<ConstantVector>(C)) {
01517       Code = bitc::CST_CODE_AGGREGATE;
01518       for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
01519         Record.push_back(VE.getValueID(C->getOperand(i)));
01520       AbbrevToUse = AggregateAbbrev;
01521     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
01522       switch (CE->getOpcode()) {
01523       default:
01524         if (Instruction::isCast(CE->getOpcode())) {
01525           Code = bitc::CST_CODE_CE_CAST;
01526           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
01527           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
01528           Record.push_back(VE.getValueID(C->getOperand(0)));
01529           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
01530         } else {
01531           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
01532           Code = bitc::CST_CODE_CE_BINOP;
01533           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
01534           Record.push_back(VE.getValueID(C->getOperand(0)));
01535           Record.push_back(VE.getValueID(C->getOperand(1)));
01536           uint64_t Flags = GetOptimizationFlags(CE);
01537           if (Flags != 0)
01538             Record.push_back(Flags);
01539         }
01540         break;
01541       case Instruction::GetElementPtr: {
01542         Code = bitc::CST_CODE_CE_GEP;
01543         const auto *GO = cast<GEPOperator>(C);
01544         if (GO->isInBounds())
01545           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
01546         Record.push_back(VE.getTypeID(GO->getSourceElementType()));
01547         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
01548           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
01549           Record.push_back(VE.getValueID(C->getOperand(i)));
01550         }
01551         break;
01552       }
01553       case Instruction::Select:
01554         Code = bitc::CST_CODE_CE_SELECT;
01555         Record.push_back(VE.getValueID(C->getOperand(0)));
01556         Record.push_back(VE.getValueID(C->getOperand(1)));
01557         Record.push_back(VE.getValueID(C->getOperand(2)));
01558         break;
01559       case Instruction::ExtractElement:
01560         Code = bitc::CST_CODE_CE_EXTRACTELT;
01561         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
01562         Record.push_back(VE.getValueID(C->getOperand(0)));
01563         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
01564         Record.push_back(VE.getValueID(C->getOperand(1)));
01565         break;
01566       case Instruction::InsertElement:
01567         Code = bitc::CST_CODE_CE_INSERTELT;
01568         Record.push_back(VE.getValueID(C->getOperand(0)));
01569         Record.push_back(VE.getValueID(C->getOperand(1)));
01570         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
01571         Record.push_back(VE.getValueID(C->getOperand(2)));
01572         break;
01573       case Instruction::ShuffleVector:
01574         // If the return type and argument types are the same, this is a
01575         // standard shufflevector instruction.  If the types are different,
01576         // then the shuffle is widening or truncating the input vectors, and
01577         // the argument type must also be encoded.
01578         if (C->getType() == C->getOperand(0)->getType()) {
01579           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
01580         } else {
01581           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
01582           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
01583         }
01584         Record.push_back(VE.getValueID(C->getOperand(0)));
01585         Record.push_back(VE.getValueID(C->getOperand(1)));
01586         Record.push_back(VE.getValueID(C->getOperand(2)));
01587         break;
01588       case Instruction::ICmp:
01589       case Instruction::FCmp:
01590         Code = bitc::CST_CODE_CE_CMP;
01591         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
01592         Record.push_back(VE.getValueID(C->getOperand(0)));
01593         Record.push_back(VE.getValueID(C->getOperand(1)));
01594         Record.push_back(CE->getPredicate());
01595         break;
01596       }
01597     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
01598       Code = bitc::CST_CODE_BLOCKADDRESS;
01599       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
01600       Record.push_back(VE.getValueID(BA->getFunction()));
01601       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
01602     } else {
01603 #ifndef NDEBUG
01604       C->dump();
01605 #endif
01606       llvm_unreachable("Unknown constant!");
01607     }
01608     Stream.EmitRecord(Code, Record, AbbrevToUse);
01609     Record.clear();
01610   }
01611 
01612   Stream.ExitBlock();
01613 }
01614 
01615 static void WriteModuleConstants(const ValueEnumerator &VE,
01616                                  BitstreamWriter &Stream) {
01617   const ValueEnumerator::ValueList &Vals = VE.getValues();
01618 
01619   // Find the first constant to emit, which is the first non-globalvalue value.
01620   // We know globalvalues have been emitted by WriteModuleInfo.
01621   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
01622     if (!isa<GlobalValue>(Vals[i].first)) {
01623       WriteConstants(i, Vals.size(), VE, Stream, true);
01624       return;
01625     }
01626   }
01627 }
01628 
01629 /// PushValueAndType - The file has to encode both the value and type id for
01630 /// many values, because we need to know what type to create for forward
01631 /// references.  However, most operands are not forward references, so this type
01632 /// field is not needed.
01633 ///
01634 /// This function adds V's value ID to Vals.  If the value ID is higher than the
01635 /// instruction ID, then it is a forward reference, and it also includes the
01636 /// type ID.  The value ID that is written is encoded relative to the InstID.
01637 static bool PushValueAndType(const Value *V, unsigned InstID,
01638                              SmallVectorImpl<unsigned> &Vals,
01639                              ValueEnumerator &VE) {
01640   unsigned ValID = VE.getValueID(V);
01641   // Make encoding relative to the InstID.
01642   Vals.push_back(InstID - ValID);
01643   if (ValID >= InstID) {
01644     Vals.push_back(VE.getTypeID(V->getType()));
01645     return true;
01646   }
01647   return false;
01648 }
01649 
01650 /// pushValue - Like PushValueAndType, but where the type of the value is
01651 /// omitted (perhaps it was already encoded in an earlier operand).
01652 static void pushValue(const Value *V, unsigned InstID,
01653                       SmallVectorImpl<unsigned> &Vals,
01654                       ValueEnumerator &VE) {
01655   unsigned ValID = VE.getValueID(V);
01656   Vals.push_back(InstID - ValID);
01657 }
01658 
01659 static void pushValueSigned(const Value *V, unsigned InstID,
01660                             SmallVectorImpl<uint64_t> &Vals,
01661                             ValueEnumerator &VE) {
01662   unsigned ValID = VE.getValueID(V);
01663   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
01664   emitSignedInt64(Vals, diff);
01665 }
01666 
01667 /// WriteInstruction - Emit an instruction to the specified stream.
01668 static void WriteInstruction(const Instruction &I, unsigned InstID,
01669                              ValueEnumerator &VE, BitstreamWriter &Stream,
01670                              SmallVectorImpl<unsigned> &Vals) {
01671   unsigned Code = 0;
01672   unsigned AbbrevToUse = 0;
01673   VE.setInstructionID(&I);
01674   switch (I.getOpcode()) {
01675   default:
01676     if (Instruction::isCast(I.getOpcode())) {
01677       Code = bitc::FUNC_CODE_INST_CAST;
01678       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
01679         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
01680       Vals.push_back(VE.getTypeID(I.getType()));
01681       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
01682     } else {
01683       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
01684       Code = bitc::FUNC_CODE_INST_BINOP;
01685       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
01686         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
01687       pushValue(I.getOperand(1), InstID, Vals, VE);
01688       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
01689       uint64_t Flags = GetOptimizationFlags(&I);
01690       if (Flags != 0) {
01691         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
01692           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
01693         Vals.push_back(Flags);
01694       }
01695     }
01696     break;
01697 
01698   case Instruction::GetElementPtr: {
01699     Code = bitc::FUNC_CODE_INST_GEP;
01700     AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
01701     auto &GEPInst = cast<GetElementPtrInst>(I);
01702     Vals.push_back(GEPInst.isInBounds());
01703     Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
01704     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
01705       PushValueAndType(I.getOperand(i), InstID, Vals, VE);
01706     break;
01707   }
01708   case Instruction::ExtractValue: {
01709     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
01710     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01711     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
01712     Vals.append(EVI->idx_begin(), EVI->idx_end());
01713     break;
01714   }
01715   case Instruction::InsertValue: {
01716     Code = bitc::FUNC_CODE_INST_INSERTVAL;
01717     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01718     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
01719     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
01720     Vals.append(IVI->idx_begin(), IVI->idx_end());
01721     break;
01722   }
01723   case Instruction::Select:
01724     Code = bitc::FUNC_CODE_INST_VSELECT;
01725     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
01726     pushValue(I.getOperand(2), InstID, Vals, VE);
01727     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01728     break;
01729   case Instruction::ExtractElement:
01730     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
01731     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01732     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
01733     break;
01734   case Instruction::InsertElement:
01735     Code = bitc::FUNC_CODE_INST_INSERTELT;
01736     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01737     pushValue(I.getOperand(1), InstID, Vals, VE);
01738     PushValueAndType(I.getOperand(2), InstID, Vals, VE);
01739     break;
01740   case Instruction::ShuffleVector:
01741     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
01742     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01743     pushValue(I.getOperand(1), InstID, Vals, VE);
01744     pushValue(I.getOperand(2), InstID, Vals, VE);
01745     break;
01746   case Instruction::ICmp:
01747   case Instruction::FCmp:
01748     // compare returning Int1Ty or vector of Int1Ty
01749     Code = bitc::FUNC_CODE_INST_CMP2;
01750     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01751     pushValue(I.getOperand(1), InstID, Vals, VE);
01752     Vals.push_back(cast<CmpInst>(I).getPredicate());
01753     break;
01754 
01755   case Instruction::Ret:
01756     {
01757       Code = bitc::FUNC_CODE_INST_RET;
01758       unsigned NumOperands = I.getNumOperands();
01759       if (NumOperands == 0)
01760         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
01761       else if (NumOperands == 1) {
01762         if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
01763           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
01764       } else {
01765         for (unsigned i = 0, e = NumOperands; i != e; ++i)
01766           PushValueAndType(I.getOperand(i), InstID, Vals, VE);
01767       }
01768     }
01769     break;
01770   case Instruction::Br:
01771     {
01772       Code = bitc::FUNC_CODE_INST_BR;
01773       const BranchInst &II = cast<BranchInst>(I);
01774       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
01775       if (II.isConditional()) {
01776         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
01777         pushValue(II.getCondition(), InstID, Vals, VE);
01778       }
01779     }
01780     break;
01781   case Instruction::Switch:
01782     {
01783       Code = bitc::FUNC_CODE_INST_SWITCH;
01784       const SwitchInst &SI = cast<SwitchInst>(I);
01785       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
01786       pushValue(SI.getCondition(), InstID, Vals, VE);
01787       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
01788       for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
01789            i != e; ++i) {
01790         Vals.push_back(VE.getValueID(i.getCaseValue()));
01791         Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
01792       }
01793     }
01794     break;
01795   case Instruction::IndirectBr:
01796     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
01797     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
01798     // Encode the address operand as relative, but not the basic blocks.
01799     pushValue(I.getOperand(0), InstID, Vals, VE);
01800     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
01801       Vals.push_back(VE.getValueID(I.getOperand(i)));
01802     break;
01803 
01804   case Instruction::Invoke: {
01805     const InvokeInst *II = cast<InvokeInst>(&I);
01806     const Value *Callee = II->getCalledValue();
01807     FunctionType *FTy = II->getFunctionType();
01808     Code = bitc::FUNC_CODE_INST_INVOKE;
01809 
01810     Vals.push_back(VE.getAttributeID(II->getAttributes()));
01811     Vals.push_back(II->getCallingConv() | 1 << 13);
01812     Vals.push_back(VE.getValueID(II->getNormalDest()));
01813     Vals.push_back(VE.getValueID(II->getUnwindDest()));
01814     Vals.push_back(VE.getTypeID(FTy));
01815     PushValueAndType(Callee, InstID, Vals, VE);
01816 
01817     // Emit value #'s for the fixed parameters.
01818     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
01819       pushValue(I.getOperand(i), InstID, Vals, VE);  // fixed param.
01820 
01821     // Emit type/value pairs for varargs params.
01822     if (FTy->isVarArg()) {
01823       for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
01824            i != e; ++i)
01825         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
01826     }
01827     break;
01828   }
01829   case Instruction::Resume:
01830     Code = bitc::FUNC_CODE_INST_RESUME;
01831     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01832     break;
01833   case Instruction::Unreachable:
01834     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
01835     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
01836     break;
01837 
01838   case Instruction::PHI: {
01839     const PHINode &PN = cast<PHINode>(I);
01840     Code = bitc::FUNC_CODE_INST_PHI;
01841     // With the newer instruction encoding, forward references could give
01842     // negative valued IDs.  This is most common for PHIs, so we use
01843     // signed VBRs.
01844     SmallVector<uint64_t, 128> Vals64;
01845     Vals64.push_back(VE.getTypeID(PN.getType()));
01846     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
01847       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
01848       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
01849     }
01850     // Emit a Vals64 vector and exit.
01851     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
01852     Vals64.clear();
01853     return;
01854   }
01855 
01856   case Instruction::LandingPad: {
01857     const LandingPadInst &LP = cast<LandingPadInst>(I);
01858     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
01859     Vals.push_back(VE.getTypeID(LP.getType()));
01860     PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
01861     Vals.push_back(LP.isCleanup());
01862     Vals.push_back(LP.getNumClauses());
01863     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
01864       if (LP.isCatch(I))
01865         Vals.push_back(LandingPadInst::Catch);
01866       else
01867         Vals.push_back(LandingPadInst::Filter);
01868       PushValueAndType(LP.getClause(I), InstID, Vals, VE);
01869     }
01870     break;
01871   }
01872 
01873   case Instruction::Alloca: {
01874     Code = bitc::FUNC_CODE_INST_ALLOCA;
01875     const AllocaInst &AI = cast<AllocaInst>(I);
01876     Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
01877     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
01878     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
01879     unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
01880     assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
01881            "not enough bits for maximum alignment");
01882     assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
01883     AlignRecord |= AI.isUsedWithInAlloca() << 5;
01884     AlignRecord |= 1 << 6;
01885     Vals.push_back(AlignRecord);
01886     break;
01887   }
01888 
01889   case Instruction::Load:
01890     if (cast<LoadInst>(I).isAtomic()) {
01891       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
01892       PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01893     } else {
01894       Code = bitc::FUNC_CODE_INST_LOAD;
01895       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
01896         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
01897     }
01898     Vals.push_back(VE.getTypeID(I.getType()));
01899     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
01900     Vals.push_back(cast<LoadInst>(I).isVolatile());
01901     if (cast<LoadInst>(I).isAtomic()) {
01902       Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
01903       Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
01904     }
01905     break;
01906   case Instruction::Store:
01907     if (cast<StoreInst>(I).isAtomic())
01908       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
01909     else
01910       Code = bitc::FUNC_CODE_INST_STORE;
01911     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
01912     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // valty + val
01913     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
01914     Vals.push_back(cast<StoreInst>(I).isVolatile());
01915     if (cast<StoreInst>(I).isAtomic()) {
01916       Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
01917       Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
01918     }
01919     break;
01920   case Instruction::AtomicCmpXchg:
01921     Code = bitc::FUNC_CODE_INST_CMPXCHG;
01922     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
01923     PushValueAndType(I.getOperand(1), InstID, Vals, VE);         // cmp.
01924     pushValue(I.getOperand(2), InstID, Vals, VE);         // newval.
01925     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
01926     Vals.push_back(GetEncodedOrdering(
01927                      cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
01928     Vals.push_back(GetEncodedSynchScope(
01929                      cast<AtomicCmpXchgInst>(I).getSynchScope()));
01930     Vals.push_back(GetEncodedOrdering(
01931                      cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
01932     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
01933     break;
01934   case Instruction::AtomicRMW:
01935     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
01936     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
01937     pushValue(I.getOperand(1), InstID, Vals, VE);         // val.
01938     Vals.push_back(GetEncodedRMWOperation(
01939                      cast<AtomicRMWInst>(I).getOperation()));
01940     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
01941     Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
01942     Vals.push_back(GetEncodedSynchScope(
01943                      cast<AtomicRMWInst>(I).getSynchScope()));
01944     break;
01945   case Instruction::Fence:
01946     Code = bitc::FUNC_CODE_INST_FENCE;
01947     Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
01948     Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
01949     break;
01950   case Instruction::Call: {
01951     const CallInst &CI = cast<CallInst>(I);
01952     FunctionType *FTy = CI.getFunctionType();
01953 
01954     Code = bitc::FUNC_CODE_INST_CALL;
01955 
01956     Vals.push_back(VE.getAttributeID(CI.getAttributes()));
01957     Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) |
01958                    unsigned(CI.isMustTailCall()) << 14 | 1 << 15);
01959     Vals.push_back(VE.getTypeID(FTy));
01960     PushValueAndType(CI.getCalledValue(), InstID, Vals, VE);  // Callee
01961 
01962     // Emit value #'s for the fixed parameters.
01963     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
01964       // Check for labels (can happen with asm labels).
01965       if (FTy->getParamType(i)->isLabelTy())
01966         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
01967       else
01968         pushValue(CI.getArgOperand(i), InstID, Vals, VE);  // fixed param.
01969     }
01970 
01971     // Emit type/value pairs for varargs params.
01972     if (FTy->isVarArg()) {
01973       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
01974            i != e; ++i)
01975         PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE);  // varargs
01976     }
01977     break;
01978   }
01979   case Instruction::VAArg:
01980     Code = bitc::FUNC_CODE_INST_VAARG;
01981     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
01982     pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
01983     Vals.push_back(VE.getTypeID(I.getType())); // restype.
01984     break;
01985   }
01986 
01987   Stream.EmitRecord(Code, Vals, AbbrevToUse);
01988   Vals.clear();
01989 }
01990 
01991 // Emit names for globals/functions etc.
01992 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
01993                                   const ValueEnumerator &VE,
01994                                   BitstreamWriter &Stream) {
01995   if (VST.empty()) return;
01996   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
01997 
01998   // FIXME: Set up the abbrev, we know how many values there are!
01999   // FIXME: We know if the type names can use 7-bit ascii.
02000   SmallVector<unsigned, 64> NameVals;
02001 
02002   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
02003        SI != SE; ++SI) {
02004 
02005     const ValueName &Name = *SI;
02006 
02007     // Figure out the encoding to use for the name.
02008     bool is7Bit = true;
02009     bool isChar6 = true;
02010     for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
02011          C != E; ++C) {
02012       if (isChar6)
02013         isChar6 = BitCodeAbbrevOp::isChar6(*C);
02014       if ((unsigned char)*C & 128) {
02015         is7Bit = false;
02016         break;  // don't bother scanning the rest.
02017       }
02018     }
02019 
02020     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
02021 
02022     // VST_ENTRY:   [valueid, namechar x N]
02023     // VST_BBENTRY: [bbid, namechar x N]
02024     unsigned Code;
02025     if (isa<BasicBlock>(SI->getValue())) {
02026       Code = bitc::VST_CODE_BBENTRY;
02027       if (isChar6)
02028         AbbrevToUse = VST_BBENTRY_6_ABBREV;
02029     } else {
02030       Code = bitc::VST_CODE_ENTRY;
02031       if (isChar6)
02032         AbbrevToUse = VST_ENTRY_6_ABBREV;
02033       else if (is7Bit)
02034         AbbrevToUse = VST_ENTRY_7_ABBREV;
02035     }
02036 
02037     NameVals.push_back(VE.getValueID(SI->getValue()));
02038     for (const char *P = Name.getKeyData(),
02039          *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
02040       NameVals.push_back((unsigned char)*P);
02041 
02042     // Emit the finished record.
02043     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
02044     NameVals.clear();
02045   }
02046   Stream.ExitBlock();
02047 }
02048 
02049 static void WriteUseList(ValueEnumerator &VE, UseListOrder &&Order,
02050                          BitstreamWriter &Stream) {
02051   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
02052   unsigned Code;
02053   if (isa<BasicBlock>(Order.V))
02054     Code = bitc::USELIST_CODE_BB;
02055   else
02056     Code = bitc::USELIST_CODE_DEFAULT;
02057 
02058   SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
02059   Record.push_back(VE.getValueID(Order.V));
02060   Stream.EmitRecord(Code, Record);
02061 }
02062 
02063 static void WriteUseListBlock(const Function *F, ValueEnumerator &VE,
02064                               BitstreamWriter &Stream) {
02065   assert(VE.shouldPreserveUseListOrder() &&
02066          "Expected to be preserving use-list order");
02067 
02068   auto hasMore = [&]() {
02069     return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
02070   };
02071   if (!hasMore())
02072     // Nothing to do.
02073     return;
02074 
02075   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
02076   while (hasMore()) {
02077     WriteUseList(VE, std::move(VE.UseListOrders.back()), Stream);
02078     VE.UseListOrders.pop_back();
02079   }
02080   Stream.ExitBlock();
02081 }
02082 
02083 /// WriteFunction - Emit a function body to the module stream.
02084 static void WriteFunction(const Function &F, ValueEnumerator &VE,
02085                           BitstreamWriter &Stream) {
02086   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
02087   VE.incorporateFunction(F);
02088 
02089   SmallVector<unsigned, 64> Vals;
02090 
02091   // Emit the number of basic blocks, so the reader can create them ahead of
02092   // time.
02093   Vals.push_back(VE.getBasicBlocks().size());
02094   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
02095   Vals.clear();
02096 
02097   // If there are function-local constants, emit them now.
02098   unsigned CstStart, CstEnd;
02099   VE.getFunctionConstantRange(CstStart, CstEnd);
02100   WriteConstants(CstStart, CstEnd, VE, Stream, false);
02101 
02102   // If there is function-local metadata, emit it now.
02103   WriteFunctionLocalMetadata(F, VE, Stream);
02104 
02105   // Keep a running idea of what the instruction ID is.
02106   unsigned InstID = CstEnd;
02107 
02108   bool NeedsMetadataAttachment = F.hasMetadata();
02109 
02110   DILocation *LastDL = nullptr;
02111 
02112   // Finally, emit all the instructions, in order.
02113   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
02114     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
02115          I != E; ++I) {
02116       WriteInstruction(*I, InstID, VE, Stream, Vals);
02117 
02118       if (!I->getType()->isVoidTy())
02119         ++InstID;
02120 
02121       // If the instruction has metadata, write a metadata attachment later.
02122       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
02123 
02124       // If the instruction has a debug location, emit it.
02125       DILocation *DL = I->getDebugLoc();
02126       if (!DL)
02127         continue;
02128 
02129       if (DL == LastDL) {
02130         // Just repeat the same debug loc as last time.
02131         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
02132         continue;
02133       }
02134 
02135       Vals.push_back(DL->getLine());
02136       Vals.push_back(DL->getColumn());
02137       Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
02138       Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
02139       Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
02140       Vals.clear();
02141 
02142       LastDL = DL;
02143     }
02144 
02145   // Emit names for all the instructions etc.
02146   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
02147 
02148   if (NeedsMetadataAttachment)
02149     WriteMetadataAttachment(F, VE, Stream);
02150   if (VE.shouldPreserveUseListOrder())
02151     WriteUseListBlock(&F, VE, Stream);
02152   VE.purgeFunction();
02153   Stream.ExitBlock();
02154 }
02155 
02156 // Emit blockinfo, which defines the standard abbreviations etc.
02157 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
02158   // We only want to emit block info records for blocks that have multiple
02159   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
02160   // Other blocks can define their abbrevs inline.
02161   Stream.EnterBlockInfoBlock(2);
02162 
02163   { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
02164     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
02165     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
02166     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
02167     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
02168     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
02169     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
02170                                    Abbv) != VST_ENTRY_8_ABBREV)
02171       llvm_unreachable("Unexpected abbrev ordering!");
02172   }
02173 
02174   { // 7-bit fixed width VST_ENTRY strings.
02175     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
02176     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
02177     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
02178     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
02179     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
02180     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
02181                                    Abbv) != VST_ENTRY_7_ABBREV)
02182       llvm_unreachable("Unexpected abbrev ordering!");
02183   }
02184   { // 6-bit char6 VST_ENTRY strings.
02185     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
02186     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
02187     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
02188     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
02189     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
02190     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
02191                                    Abbv) != VST_ENTRY_6_ABBREV)
02192       llvm_unreachable("Unexpected abbrev ordering!");
02193   }
02194   { // 6-bit char6 VST_BBENTRY strings.
02195     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
02196     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
02197     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
02198     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
02199     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
02200     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
02201                                    Abbv) != VST_BBENTRY_6_ABBREV)
02202       llvm_unreachable("Unexpected abbrev ordering!");
02203   }
02204 
02205 
02206 
02207   { // SETTYPE abbrev for CONSTANTS_BLOCK.
02208     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
02209     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
02210     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
02211                               VE.computeBitsRequiredForTypeIndicies()));
02212     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
02213                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
02214       llvm_unreachable("Unexpected abbrev ordering!");
02215   }
02216 
02217   { // INTEGER abbrev for CONSTANTS_BLOCK.
02218     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
02219     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
02220     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
02221     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
02222                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
02223       llvm_unreachable("Unexpected abbrev ordering!");
02224   }
02225 
02226   { // CE_CAST abbrev for CONSTANTS_BLOCK.
02227     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
02228     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
02229     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
02230     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
02231                               VE.computeBitsRequiredForTypeIndicies()));
02232     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
02233 
02234     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
02235                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
02236       llvm_unreachable("Unexpected abbrev ordering!");
02237   }
02238   { // NULL abbrev for CONSTANTS_BLOCK.
02239     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
02240     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
02241     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
02242                                    Abbv) != CONSTANTS_NULL_Abbrev)
02243       llvm_unreachable("Unexpected abbrev ordering!");
02244   }
02245 
02246   // FIXME: This should only use space for first class types!
02247 
02248   { // INST_LOAD abbrev for FUNCTION_BLOCK.
02249     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
02250     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
02251     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
02252     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
02253                               VE.computeBitsRequiredForTypeIndicies()));
02254     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
02255     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
02256     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
02257                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
02258       llvm_unreachable("Unexpected abbrev ordering!");
02259   }
02260   { // INST_BINOP abbrev for FUNCTION_BLOCK.
02261     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
02262     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
02263     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
02264     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
02265     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
02266     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
02267                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
02268       llvm_unreachable("Unexpected abbrev ordering!");
02269   }
02270   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
02271     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
02272     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
02273     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
02274     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
02275     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
02276     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
02277     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
02278                                    Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
02279       llvm_unreachable("Unexpected abbrev ordering!");
02280   }
02281   { // INST_CAST abbrev for FUNCTION_BLOCK.
02282     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
02283     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
02284     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
02285     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
02286                               VE.computeBitsRequiredForTypeIndicies()));
02287     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
02288     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
02289                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
02290       llvm_unreachable("Unexpected abbrev ordering!");
02291   }
02292 
02293   { // INST_RET abbrev for FUNCTION_BLOCK.
02294     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
02295     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
02296     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
02297                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
02298       llvm_unreachable("Unexpected abbrev ordering!");
02299   }
02300   { // INST_RET abbrev for FUNCTION_BLOCK.
02301     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
02302     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
02303     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
02304     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
02305                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
02306       llvm_unreachable("Unexpected abbrev ordering!");
02307   }
02308   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
02309     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
02310     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
02311     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
02312                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
02313       llvm_unreachable("Unexpected abbrev ordering!");
02314   }
02315   {
02316     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
02317     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
02318     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
02319     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
02320                               Log2_32_Ceil(VE.getTypes().size() + 1)));
02321     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
02322     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
02323     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
02324         FUNCTION_INST_GEP_ABBREV)
02325       llvm_unreachable("Unexpected abbrev ordering!");
02326   }
02327 
02328   Stream.ExitBlock();
02329 }
02330 
02331 /// WriteModule - Emit the specified module to the bitstream.
02332 static void WriteModule(const Module *M, BitstreamWriter &Stream,
02333                         bool ShouldPreserveUseListOrder) {
02334   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
02335 
02336   SmallVector<unsigned, 1> Vals;
02337   unsigned CurVersion = 1;
02338   Vals.push_back(CurVersion);
02339   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
02340 
02341   // Analyze the module, enumerating globals, functions, etc.
02342   ValueEnumerator VE(*M, ShouldPreserveUseListOrder);
02343 
02344   // Emit blockinfo, which defines the standard abbreviations etc.
02345   WriteBlockInfo(VE, Stream);
02346 
02347   // Emit information about attribute groups.
02348   WriteAttributeGroupTable(VE, Stream);
02349 
02350   // Emit information about parameter attributes.
02351   WriteAttributeTable(VE, Stream);
02352 
02353   // Emit information describing all of the types in the module.
02354   WriteTypeTable(VE, Stream);
02355 
02356   writeComdats(VE, Stream);
02357 
02358   // Emit top-level description of module, including target triple, inline asm,
02359   // descriptors for global variables, and function prototype info.
02360   WriteModuleInfo(M, VE, Stream);
02361 
02362   // Emit constants.
02363   WriteModuleConstants(VE, Stream);
02364 
02365   // Emit metadata.
02366   WriteModuleMetadata(M, VE, Stream);
02367 
02368   // Emit metadata.
02369   WriteModuleMetadataStore(M, Stream);
02370 
02371   // Emit names for globals/functions etc.
02372   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
02373 
02374   // Emit module-level use-lists.
02375   if (VE.shouldPreserveUseListOrder())
02376     WriteUseListBlock(nullptr, VE, Stream);
02377 
02378   // Emit function bodies.
02379   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
02380     if (!F->isDeclaration())
02381       WriteFunction(*F, VE, Stream);
02382 
02383   Stream.ExitBlock();
02384 }
02385 
02386 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
02387 /// header and trailer to make it compatible with the system archiver.  To do
02388 /// this we emit the following header, and then emit a trailer that pads the
02389 /// file out to be a multiple of 16 bytes.
02390 ///
02391 /// struct bc_header {
02392 ///   uint32_t Magic;         // 0x0B17C0DE
02393 ///   uint32_t Version;       // Version, currently always 0.
02394 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
02395 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
02396 ///   uint32_t CPUType;       // CPU specifier.
02397 ///   ... potentially more later ...
02398 /// };
02399 enum {
02400   DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
02401   DarwinBCHeaderSize = 5*4
02402 };
02403 
02404 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
02405                                uint32_t &Position) {
02406   Buffer[Position + 0] = (unsigned char) (Value >>  0);
02407   Buffer[Position + 1] = (unsigned char) (Value >>  8);
02408   Buffer[Position + 2] = (unsigned char) (Value >> 16);
02409   Buffer[Position + 3] = (unsigned char) (Value >> 24);
02410   Position += 4;
02411 }
02412 
02413 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
02414                                          const Triple &TT) {
02415   unsigned CPUType = ~0U;
02416 
02417   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
02418   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
02419   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
02420   // specific constants here because they are implicitly part of the Darwin ABI.
02421   enum {
02422     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
02423     DARWIN_CPU_TYPE_X86        = 7,
02424     DARWIN_CPU_TYPE_ARM        = 12,
02425     DARWIN_CPU_TYPE_POWERPC    = 18
02426   };
02427 
02428   Triple::ArchType Arch = TT.getArch();
02429   if (Arch == Triple::x86_64)
02430     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
02431   else if (Arch == Triple::x86)
02432     CPUType = DARWIN_CPU_TYPE_X86;
02433   else if (Arch == Triple::ppc)
02434     CPUType = DARWIN_CPU_TYPE_POWERPC;
02435   else if (Arch == Triple::ppc64)
02436     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
02437   else if (Arch == Triple::arm || Arch == Triple::thumb)
02438     CPUType = DARWIN_CPU_TYPE_ARM;
02439 
02440   // Traditional Bitcode starts after header.
02441   assert(Buffer.size() >= DarwinBCHeaderSize &&
02442          "Expected header size to be reserved");
02443   unsigned BCOffset = DarwinBCHeaderSize;
02444   unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
02445 
02446   // Write the magic and version.
02447   unsigned Position = 0;
02448   WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
02449   WriteInt32ToBuffer(0          , Buffer, Position); // Version.
02450   WriteInt32ToBuffer(BCOffset   , Buffer, Position);
02451   WriteInt32ToBuffer(BCSize     , Buffer, Position);
02452   WriteInt32ToBuffer(CPUType    , Buffer, Position);
02453 
02454   // If the file is not a multiple of 16 bytes, insert dummy padding.
02455   while (Buffer.size() & 15)
02456     Buffer.push_back(0);
02457 }
02458 
02459 /// WriteBitcodeToFile - Write the specified module to the specified output
02460 /// stream.
02461 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
02462                               bool ShouldPreserveUseListOrder) {
02463   SmallVector<char, 0> Buffer;
02464   Buffer.reserve(256*1024);
02465 
02466   // If this is darwin or another generic macho target, reserve space for the
02467   // header.
02468   Triple TT(M->getTargetTriple());
02469   if (TT.isOSDarwin())
02470     Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
02471 
02472   // Emit the module into the buffer.
02473   {
02474     BitstreamWriter Stream(Buffer);
02475 
02476     // Emit the file header.
02477     Stream.Emit((unsigned)'B', 8);
02478     Stream.Emit((unsigned)'C', 8);
02479     Stream.Emit(0x0, 4);
02480     Stream.Emit(0xC, 4);
02481     Stream.Emit(0xE, 4);
02482     Stream.Emit(0xD, 4);
02483 
02484     // Emit the module.
02485     WriteModule(M, Stream, ShouldPreserveUseListOrder);
02486   }
02487 
02488   if (TT.isOSDarwin())
02489     EmitDarwinBCHeaderAndTrailer(Buffer, TT);
02490 
02491   // Write the generated bitstream to "Out".
02492   Out.write((char*)&Buffer.front(), Buffer.size());
02493 }