LCOV - code coverage report
Current view: top level - lib/Bitcode/Writer - BitcodeWriter.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 2318 2393 96.9 %
Date: 2017-09-14 15:23:50 Functions: 108 108 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ------------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // Bitcode writer implementation.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : #include "llvm/Bitcode/BitcodeWriter.h"
      15             : #include "ValueEnumerator.h"
      16             : #include "llvm/ADT/APFloat.h"
      17             : #include "llvm/ADT/APInt.h"
      18             : #include "llvm/ADT/ArrayRef.h"
      19             : #include "llvm/ADT/DenseMap.h"
      20             : #include "llvm/ADT/None.h"
      21             : #include "llvm/ADT/Optional.h"
      22             : #include "llvm/ADT/STLExtras.h"
      23             : #include "llvm/ADT/SmallString.h"
      24             : #include "llvm/ADT/SmallVector.h"
      25             : #include "llvm/ADT/StringMap.h"
      26             : #include "llvm/ADT/StringRef.h"
      27             : #include "llvm/ADT/Triple.h"
      28             : #include "llvm/Bitcode/BitCodes.h"
      29             : #include "llvm/Bitcode/BitstreamWriter.h"
      30             : #include "llvm/Bitcode/LLVMBitCodes.h"
      31             : #include "llvm/IR/Attributes.h"
      32             : #include "llvm/IR/BasicBlock.h"
      33             : #include "llvm/IR/CallSite.h"
      34             : #include "llvm/IR/Comdat.h"
      35             : #include "llvm/IR/Constant.h"
      36             : #include "llvm/IR/Constants.h"
      37             : #include "llvm/IR/DebugInfoMetadata.h"
      38             : #include "llvm/IR/DebugLoc.h"
      39             : #include "llvm/IR/DerivedTypes.h"
      40             : #include "llvm/IR/Function.h"
      41             : #include "llvm/IR/GlobalAlias.h"
      42             : #include "llvm/IR/GlobalIFunc.h"
      43             : #include "llvm/IR/GlobalObject.h"
      44             : #include "llvm/IR/GlobalValue.h"
      45             : #include "llvm/IR/GlobalVariable.h"
      46             : #include "llvm/IR/InlineAsm.h"
      47             : #include "llvm/IR/InstrTypes.h"
      48             : #include "llvm/IR/Instruction.h"
      49             : #include "llvm/IR/Instructions.h"
      50             : #include "llvm/IR/LLVMContext.h"
      51             : #include "llvm/IR/Metadata.h"
      52             : #include "llvm/IR/Module.h"
      53             : #include "llvm/IR/ModuleSummaryIndex.h"
      54             : #include "llvm/IR/Operator.h"
      55             : #include "llvm/IR/Type.h"
      56             : #include "llvm/IR/UseListOrder.h"
      57             : #include "llvm/IR/Value.h"
      58             : #include "llvm/IR/ValueSymbolTable.h"
      59             : #include "llvm/MC/StringTableBuilder.h"
      60             : #include "llvm/Object/IRSymtab.h"
      61             : #include "llvm/Support/AtomicOrdering.h"
      62             : #include "llvm/Support/Casting.h"
      63             : #include "llvm/Support/CommandLine.h"
      64             : #include "llvm/Support/Endian.h"
      65             : #include "llvm/Support/Error.h"
      66             : #include "llvm/Support/ErrorHandling.h"
      67             : #include "llvm/Support/MathExtras.h"
      68             : #include "llvm/Support/SHA1.h"
      69             : #include "llvm/Support/TargetRegistry.h"
      70             : #include "llvm/Support/raw_ostream.h"
      71             : #include <algorithm>
      72             : #include <cassert>
      73             : #include <cstddef>
      74             : #include <cstdint>
      75             : #include <iterator>
      76             : #include <map>
      77             : #include <memory>
      78             : #include <string>
      79             : #include <utility>
      80             : #include <vector>
      81             : 
      82             : using namespace llvm;
      83             : 
      84             : static cl::opt<unsigned>
      85      289224 :     IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
      86      216918 :                    cl::desc("Number of metadatas above which we emit an index "
      87       72306 :                             "to enable lazy-loading"));
      88             : 
      89             : namespace {
      90             : 
      91             : /// These are manifest constants used by the bitcode writer. They do not need to
      92             : /// be kept in sync with the reader, but need to be consistent within this file.
      93             : enum {
      94             :   // VALUE_SYMTAB_BLOCK abbrev id's.
      95             :   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
      96             :   VST_ENTRY_7_ABBREV,
      97             :   VST_ENTRY_6_ABBREV,
      98             :   VST_BBENTRY_6_ABBREV,
      99             : 
     100             :   // CONSTANTS_BLOCK abbrev id's.
     101             :   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
     102             :   CONSTANTS_INTEGER_ABBREV,
     103             :   CONSTANTS_CE_CAST_Abbrev,
     104             :   CONSTANTS_NULL_Abbrev,
     105             : 
     106             :   // FUNCTION_BLOCK abbrev id's.
     107             :   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
     108             :   FUNCTION_INST_BINOP_ABBREV,
     109             :   FUNCTION_INST_BINOP_FLAGS_ABBREV,
     110             :   FUNCTION_INST_CAST_ABBREV,
     111             :   FUNCTION_INST_RET_VOID_ABBREV,
     112             :   FUNCTION_INST_RET_VAL_ABBREV,
     113             :   FUNCTION_INST_UNREACHABLE_ABBREV,
     114             :   FUNCTION_INST_GEP_ABBREV,
     115             : };
     116             : 
     117             : /// Abstract class to manage the bitcode writing, subclassed for each bitcode
     118             : /// file type.
     119             : class BitcodeWriterBase {
     120             : protected:
     121             :   /// The stream created and owned by the client.
     122             :   BitstreamWriter &Stream;
     123             : 
     124             :   StringTableBuilder &StrtabBuilder;
     125             : 
     126             : public:
     127             :   /// Constructs a BitcodeWriterBase object that writes to the provided
     128             :   /// \p Stream.
     129             :   BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
     130        3767 :       : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
     131             : 
     132             : protected:
     133             :   void writeBitcodeHeader();
     134             :   void writeModuleVersion();
     135             : };
     136             : 
     137             : void BitcodeWriterBase::writeModuleVersion() {
     138             :   // VERSION: [version#]
     139        7534 :   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
     140             : }
     141             : 
     142             : /// Base class to manage the module bitcode writing, currently subclassed for
     143             : /// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
     144        7274 : class ModuleBitcodeWriterBase : public BitcodeWriterBase {
     145             : protected:
     146             :   /// The Module to write to bitcode.
     147             :   const Module &M;
     148             : 
     149             :   /// Enumerates ids for all values in the module.
     150             :   ValueEnumerator VE;
     151             : 
     152             :   /// Optional per-module index to write for ThinLTO.
     153             :   const ModuleSummaryIndex *Index;
     154             : 
     155             :   /// Map that holds the correspondence between GUIDs in the summary index,
     156             :   /// that came from indirect call profiles, and a value id generated by this
     157             :   /// class to use in the VST and summary block records.
     158             :   std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
     159             : 
     160             :   /// Tracks the last value id recorded in the GUIDToValueMap.
     161             :   unsigned GlobalValueId;
     162             : 
     163             :   /// Saves the offset of the VSTOffset record that must eventually be
     164             :   /// backpatched with the offset of the actual VST.
     165             :   uint64_t VSTOffsetPlaceholder = 0;
     166             : 
     167             : public:
     168             :   /// Constructs a ModuleBitcodeWriterBase object for the given Module,
     169             :   /// writing to the provided \p Buffer.
     170        3637 :   ModuleBitcodeWriterBase(const Module *M, StringTableBuilder &StrtabBuilder,
     171             :                           BitstreamWriter &Stream,
     172             :                           bool ShouldPreserveUseListOrder,
     173             :                           const ModuleSummaryIndex *Index)
     174        3637 :       : BitcodeWriterBase(Stream, StrtabBuilder), M(*M),
     175       10911 :         VE(*M, ShouldPreserveUseListOrder), Index(Index) {
     176             :     // Assign ValueIds to any callee values in the index that came from
     177             :     // indirect call profiles and were recorded as a GUID not a Value*
     178             :     // (which would have been assigned an ID by the ValueEnumerator).
     179             :     // The starting ValueId is just after the number of values in the
     180             :     // ValueEnumerator, so that they can be emitted in the VST.
     181        7274 :     GlobalValueId = VE.getValues().size();
     182        3637 :     if (!Index)
     183             :       return;
     184        1847 :     for (const auto &GUIDSummaryLists : *Index)
     185             :       // Examine all summaries for this GUID.
     186        4542 :       for (auto &Summary : GUIDSummaryLists.second.SummaryList)
     187        1166 :         if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
     188             :           // For each call in the function summary, see if the call
     189             :           // is to a GUID (which means it is for an indirect call,
     190             :           // otherwise we would have a Value for it). If so, synthesize
     191             :           // a value id.
     192        1230 :           for (auto &CallEdge : FS->calls())
     193         524 :             if (!CallEdge.first.getValue())
     194          12 :               assignValueId(CallEdge.first.getGUID());
     195             :   }
     196             : 
     197             : protected:
     198             :   void writePerModuleGlobalValueSummary();
     199             : 
     200             : private:
     201             :   void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
     202             :                                            GlobalValueSummary *Summary,
     203             :                                            unsigned ValueID,
     204             :                                            unsigned FSCallsAbbrev,
     205             :                                            unsigned FSCallsProfileAbbrev,
     206             :                                            const Function &F);
     207             :   void writeModuleLevelReferences(const GlobalVariable &V,
     208             :                                   SmallVector<uint64_t, 64> &NameVals,
     209             :                                   unsigned FSModRefsAbbrev);
     210             : 
     211             :   void assignValueId(GlobalValue::GUID ValGUID) {
     212           6 :     GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
     213             :   }
     214             : 
     215             :   unsigned getValueId(GlobalValue::GUID ValGUID) {
     216          12 :     const auto &VMI = GUIDToValueIdMap.find(ValGUID);
     217             :     // Expect that any GUID value had a value Id assigned by an
     218             :     // earlier call to assignValueId.
     219             :     assert(VMI != GUIDToValueIdMap.end() &&
     220             :            "GUID does not have assigned value Id");
     221           6 :     return VMI->second;
     222             :   }
     223             : 
     224             :   // Helper to get the valueId for the type of value recorded in VI.
     225         262 :   unsigned getValueId(ValueInfo VI) {
     226         262 :     if (!VI.getValue())
     227          12 :       return getValueId(VI.getGUID());
     228         256 :     return VE.getValueID(VI.getValue());
     229             :   }
     230             : 
     231             :   std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
     232             : };
     233             : 
     234             : /// Class to manage the bitcode writing for a module.
     235        7258 : class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
     236             :   /// Pointer to the buffer allocated by caller for bitcode writing.
     237             :   const SmallVectorImpl<char> &Buffer;
     238             : 
     239             :   /// True if a module hash record should be written.
     240             :   bool GenerateHash;
     241             : 
     242             :   /// If non-null, when GenerateHash is true, the resulting hash is written
     243             :   /// into ModHash.
     244             :   ModuleHash *ModHash;
     245             : 
     246             :   SHA1 Hasher;
     247             : 
     248             :   /// The start bit of the identification block.
     249             :   uint64_t BitcodeStartBit;
     250             : 
     251             : public:
     252             :   /// Constructs a ModuleBitcodeWriter object for the given Module,
     253             :   /// writing to the provided \p Buffer.
     254        3629 :   ModuleBitcodeWriter(const Module *M, SmallVectorImpl<char> &Buffer,
     255             :                       StringTableBuilder &StrtabBuilder,
     256             :                       BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
     257             :                       const ModuleSummaryIndex *Index, bool GenerateHash,
     258             :                       ModuleHash *ModHash = nullptr)
     259        3629 :       : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
     260             :                                 ShouldPreserveUseListOrder, Index),
     261             :         Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash),
     262       10887 :         BitcodeStartBit(Stream.GetCurrentBitNo()) {}
     263             : 
     264             :   /// Emit the current module to the bitstream.
     265             :   void write();
     266             : 
     267             : private:
     268             :   uint64_t bitcodeStartBit() { return BitcodeStartBit; }
     269             : 
     270             :   size_t addToStrtab(StringRef Str);
     271             : 
     272             :   void writeAttributeGroupTable();
     273             :   void writeAttributeTable();
     274             :   void writeTypeTable();
     275             :   void writeComdats();
     276             :   void writeValueSymbolTableForwardDecl();
     277             :   void writeModuleInfo();
     278             :   void writeValueAsMetadata(const ValueAsMetadata *MD,
     279             :                             SmallVectorImpl<uint64_t> &Record);
     280             :   void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
     281             :                     unsigned Abbrev);
     282             :   unsigned createDILocationAbbrev();
     283             :   void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
     284             :                        unsigned &Abbrev);
     285             :   unsigned createGenericDINodeAbbrev();
     286             :   void writeGenericDINode(const GenericDINode *N,
     287             :                           SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
     288             :   void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
     289             :                        unsigned Abbrev);
     290             :   void writeDIEnumerator(const DIEnumerator *N,
     291             :                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
     292             :   void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
     293             :                         unsigned Abbrev);
     294             :   void writeDIDerivedType(const DIDerivedType *N,
     295             :                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
     296             :   void writeDICompositeType(const DICompositeType *N,
     297             :                             SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
     298             :   void writeDISubroutineType(const DISubroutineType *N,
     299             :                              SmallVectorImpl<uint64_t> &Record,
     300             :                              unsigned Abbrev);
     301             :   void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
     302             :                    unsigned Abbrev);
     303             :   void writeDICompileUnit(const DICompileUnit *N,
     304             :                           SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
     305             :   void writeDISubprogram(const DISubprogram *N,
     306             :                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
     307             :   void writeDILexicalBlock(const DILexicalBlock *N,
     308             :                            SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
     309             :   void writeDILexicalBlockFile(const DILexicalBlockFile *N,
     310             :                                SmallVectorImpl<uint64_t> &Record,
     311             :                                unsigned Abbrev);
     312             :   void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
     313             :                         unsigned Abbrev);
     314             :   void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
     315             :                     unsigned Abbrev);
     316             :   void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
     317             :                         unsigned Abbrev);
     318             :   void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
     319             :                      unsigned Abbrev);
     320             :   void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
     321             :                                     SmallVectorImpl<uint64_t> &Record,
     322             :                                     unsigned Abbrev);
     323             :   void writeDITemplateValueParameter(const DITemplateValueParameter *N,
     324             :                                      SmallVectorImpl<uint64_t> &Record,
     325             :                                      unsigned Abbrev);
     326             :   void writeDIGlobalVariable(const DIGlobalVariable *N,
     327             :                              SmallVectorImpl<uint64_t> &Record,
     328             :                              unsigned Abbrev);
     329             :   void writeDILocalVariable(const DILocalVariable *N,
     330             :                             SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
     331             :   void writeDIExpression(const DIExpression *N,
     332             :                          SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
     333             :   void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
     334             :                                        SmallVectorImpl<uint64_t> &Record,
     335             :                                        unsigned Abbrev);
     336             :   void writeDIObjCProperty(const DIObjCProperty *N,
     337             :                            SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
     338             :   void writeDIImportedEntity(const DIImportedEntity *N,
     339             :                              SmallVectorImpl<uint64_t> &Record,
     340             :                              unsigned Abbrev);
     341             :   unsigned createNamedMetadataAbbrev();
     342             :   void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
     343             :   unsigned createMetadataStringsAbbrev();
     344             :   void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
     345             :                             SmallVectorImpl<uint64_t> &Record);
     346             :   void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
     347             :                             SmallVectorImpl<uint64_t> &Record,
     348             :                             std::vector<unsigned> *MDAbbrevs = nullptr,
     349             :                             std::vector<uint64_t> *IndexPos = nullptr);
     350             :   void writeModuleMetadata();
     351             :   void writeFunctionMetadata(const Function &F);
     352             :   void writeFunctionMetadataAttachment(const Function &F);
     353             :   void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
     354             :   void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
     355             :                                     const GlobalObject &GO);
     356             :   void writeModuleMetadataKinds();
     357             :   void writeOperandBundleTags();
     358             :   void writeSyncScopeNames();
     359             :   void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
     360             :   void writeModuleConstants();
     361             :   bool pushValueAndType(const Value *V, unsigned InstID,
     362             :                         SmallVectorImpl<unsigned> &Vals);
     363             :   void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
     364             :   void pushValue(const Value *V, unsigned InstID,
     365             :                  SmallVectorImpl<unsigned> &Vals);
     366             :   void pushValueSigned(const Value *V, unsigned InstID,
     367             :                        SmallVectorImpl<uint64_t> &Vals);
     368             :   void writeInstruction(const Instruction &I, unsigned InstID,
     369             :                         SmallVectorImpl<unsigned> &Vals);
     370             :   void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
     371             :   void writeGlobalValueSymbolTable(
     372             :       DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
     373             :   void writeUseList(UseListOrder &&Order);
     374             :   void writeUseListBlock(const Function *F);
     375             :   void
     376             :   writeFunction(const Function &F,
     377             :                 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
     378             :   void writeBlockInfo();
     379             :   void writeModuleHash(size_t BlockStartPos);
     380             : 
     381             :   unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
     382         453 :     return unsigned(SSID);
     383             :   }
     384             : };
     385             : 
     386             : /// Class to manage the bitcode writing for a combined index.
     387         260 : class IndexBitcodeWriter : public BitcodeWriterBase {
     388             :   /// The combined index to write to bitcode.
     389             :   const ModuleSummaryIndex &Index;
     390             : 
     391             :   /// When writing a subset of the index for distributed backends, client
     392             :   /// provides a map of modules to the corresponding GUIDs/summaries to write.
     393             :   const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
     394             : 
     395             :   /// Map that holds the correspondence between the GUID used in the combined
     396             :   /// index and a value id generated by this class to use in references.
     397             :   std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
     398             : 
     399             :   /// Tracks the last value id recorded in the GUIDToValueMap.
     400             :   unsigned GlobalValueId = 0;
     401             : 
     402             : public:
     403             :   /// Constructs a IndexBitcodeWriter object for the given combined index,
     404             :   /// writing to the provided \p Buffer. When writing a subset of the index
     405             :   /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
     406             :   IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
     407             :                      const ModuleSummaryIndex &Index,
     408             :                      const std::map<std::string, GVSummaryMapTy>
     409             :                          *ModuleToSummariesForIndex = nullptr)
     410         130 :       : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
     411         390 :         ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
     412             :     // Assign unique value ids to all summaries to be written, for use
     413             :     // in writing out the call graph edges. Save the mapping from GUID
     414             :     // to the new global value id to use when writing those edges, which
     415             :     // are currently saved in the index in terms of GUID.
     416         130 :     forEachSummary([&](GVInfo I) {
     417         548 :       GUIDToValueIdMap[I.first] = ++GlobalValueId;
     418             :     });
     419             :   }
     420             : 
     421             :   /// The below iterator returns the GUID and associated summary.
     422             :   using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
     423             : 
     424             :   /// Calls the callback for each value GUID and summary to be written to
     425             :   /// bitcode. This hides the details of whether they are being pulled from the
     426             :   /// entire index or just those in a provided ModuleToSummariesForIndex map.
     427             :   template<typename Functor>
     428         260 :   void forEachSummary(Functor Callback) {
     429         260 :     if (ModuleToSummariesForIndex) {
     430         190 :       for (auto &M : *ModuleToSummariesForIndex)
     431         116 :         for (auto &Summary : M.second)
     432          58 :           Callback(Summary);
     433             :     } else {
     434        1716 :       for (auto &Summaries : Index)
     435        5310 :         for (auto &Summary : Summaries.second.SummaryList)
     436        3633 :           Callback({Summaries.first, Summary.get()});
     437             :     }
     438         260 :   }
     439             : 
     440             :   /// Calls the callback for each entry in the modulePaths StringMap that
     441             :   /// should be written to the module path string table. This hides the details
     442             :   /// of whether they are being pulled from the entire index or just those in a
     443             :   /// provided ModuleToSummariesForIndex map.
     444         130 :   template <typename Functor> void forEachModule(Functor Callback) {
     445         130 :     if (ModuleToSummariesForIndex) {
     446          95 :       for (const auto &M : *ModuleToSummariesForIndex) {
     447          87 :         const auto &MPI = Index.modulePaths().find(M.first);
     448          58 :         if (MPI == Index.modulePaths().end()) {
     449             :           // This should only happen if the bitcode file was empty, in which
     450             :           // case we shouldn't be importing (the ModuleToSummariesForIndex
     451             :           // would only include the module we are writing and index for).
     452             :           assert(ModuleToSummariesForIndex->size() == 1);
     453             :           continue;
     454             :         }
     455          27 :         Callback(*MPI);
     456             :       }
     457             :     } else {
     458         806 :       for (const auto &MPSE : Index.modulePaths())
     459         187 :         Callback(MPSE);
     460             :     }
     461         130 :   }
     462             : 
     463             :   /// Main entry point for writing a combined index to bitcode.
     464             :   void write();
     465             : 
     466             : private:
     467             :   void writeModStrings();
     468             :   void writeCombinedGlobalValueSummary();
     469             : 
     470             :   Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
     471        1705 :     auto VMI = GUIDToValueIdMap.find(ValGUID);
     472        1708 :     if (VMI == GUIDToValueIdMap.end())
     473             :       return None;
     474         829 :     return VMI->second;
     475             :   }
     476             : 
     477             :   std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
     478             : };
     479             : 
     480             : } // end anonymous namespace
     481             : 
     482        4667 : static unsigned getEncodedCastOpcode(unsigned Opcode) {
     483        4667 :   switch (Opcode) {
     484           0 :   default: llvm_unreachable("Unknown cast instruction!");
     485             :   case Instruction::Trunc   : return bitc::CAST_TRUNC;
     486          92 :   case Instruction::ZExt    : return bitc::CAST_ZEXT;
     487         488 :   case Instruction::SExt    : return bitc::CAST_SEXT;
     488          10 :   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
     489          42 :   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
     490          10 :   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
     491          70 :   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
     492          31 :   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
     493          49 :   case Instruction::FPExt   : return bitc::CAST_FPEXT;
     494         233 :   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
     495          39 :   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
     496        3295 :   case Instruction::BitCast : return bitc::CAST_BITCAST;
     497          32 :   case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
     498             :   }
     499             : }
     500             : 
     501        3922 : static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
     502        3922 :   switch (Opcode) {
     503           0 :   default: llvm_unreachable("Unknown binary instruction!");
     504             :   case Instruction::Add:
     505             :   case Instruction::FAdd: return bitc::BINOP_ADD;
     506         297 :   case Instruction::Sub:
     507         297 :   case Instruction::FSub: return bitc::BINOP_SUB;
     508         601 :   case Instruction::Mul:
     509         601 :   case Instruction::FMul: return bitc::BINOP_MUL;
     510          29 :   case Instruction::UDiv: return bitc::BINOP_UDIV;
     511         110 :   case Instruction::FDiv:
     512         110 :   case Instruction::SDiv: return bitc::BINOP_SDIV;
     513          12 :   case Instruction::URem: return bitc::BINOP_UREM;
     514          74 :   case Instruction::FRem:
     515          74 :   case Instruction::SRem: return bitc::BINOP_SREM;
     516          89 :   case Instruction::Shl:  return bitc::BINOP_SHL;
     517         227 :   case Instruction::LShr: return bitc::BINOP_LSHR;
     518          45 :   case Instruction::AShr: return bitc::BINOP_ASHR;
     519         273 :   case Instruction::And:  return bitc::BINOP_AND;
     520         138 :   case Instruction::Or:   return bitc::BINOP_OR;
     521          53 :   case Instruction::Xor:  return bitc::BINOP_XOR;
     522             :   }
     523             : }
     524             : 
     525          43 : static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
     526          43 :   switch (Op) {
     527           0 :   default: llvm_unreachable("Unknown RMW operation!");
     528             :   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
     529           9 :   case AtomicRMWInst::Add: return bitc::RMW_ADD;
     530           2 :   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
     531           2 :   case AtomicRMWInst::And: return bitc::RMW_AND;
     532           2 :   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
     533           6 :   case AtomicRMWInst::Or: return bitc::RMW_OR;
     534           2 :   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
     535           2 :   case AtomicRMWInst::Max: return bitc::RMW_MAX;
     536           2 :   case AtomicRMWInst::Min: return bitc::RMW_MIN;
     537           2 :   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
     538           2 :   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
     539             :   }
     540             : }
     541             : 
     542             : static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
     543         640 :   switch (Ordering) {
     544             :   case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
     545          37 :   case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
     546         264 :   case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
     547         104 :   case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
     548          55 :   case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
     549          41 :   case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
     550         139 :   case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
     551             :   }
     552           0 :   llvm_unreachable("Invalid ordering");
     553             : }
     554             : 
     555        9052 : static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
     556             :                               StringRef Str, unsigned AbbrevToUse) {
     557       18104 :   SmallVector<unsigned, 64> Vals;
     558             : 
     559             :   // Code: [strchar x N]
     560      209592 :   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
     561      250140 :     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
     562             :       AbbrevToUse = 0;
     563      382976 :     Vals.push_back(Str[i]);
     564             :   }
     565             : 
     566             :   // Emit the finished record.
     567        9052 :   Stream.EmitRecord(Code, Vals, AbbrevToUse);
     568        9052 : }
     569             : 
     570        3644 : static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
     571        3644 :   switch (Kind) {
     572             :   case Attribute::Alignment:
     573             :     return bitc::ATTR_KIND_ALIGNMENT;
     574          10 :   case Attribute::AllocSize:
     575          10 :     return bitc::ATTR_KIND_ALLOC_SIZE;
     576          19 :   case Attribute::AlwaysInline:
     577          19 :     return bitc::ATTR_KIND_ALWAYS_INLINE;
     578          45 :   case Attribute::ArgMemOnly:
     579          45 :     return bitc::ATTR_KIND_ARGMEMONLY;
     580           7 :   case Attribute::Builtin:
     581           7 :     return bitc::ATTR_KIND_BUILTIN;
     582          19 :   case Attribute::ByVal:
     583          19 :     return bitc::ATTR_KIND_BY_VAL;
     584           7 :   case Attribute::Convergent:
     585           7 :     return bitc::ATTR_KIND_CONVERGENT;
     586          13 :   case Attribute::InAlloca:
     587          13 :     return bitc::ATTR_KIND_IN_ALLOCA;
     588           3 :   case Attribute::Cold:
     589           3 :     return bitc::ATTR_KIND_COLD;
     590           7 :   case Attribute::InaccessibleMemOnly:
     591           7 :     return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
     592           9 :   case Attribute::InaccessibleMemOrArgMemOnly:
     593           9 :     return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
     594          17 :   case Attribute::InlineHint:
     595          17 :     return bitc::ATTR_KIND_INLINE_HINT;
     596          27 :   case Attribute::InReg:
     597          27 :     return bitc::ATTR_KIND_IN_REG;
     598           7 :   case Attribute::JumpTable:
     599           7 :     return bitc::ATTR_KIND_JUMP_TABLE;
     600          14 :   case Attribute::MinSize:
     601          14 :     return bitc::ATTR_KIND_MIN_SIZE;
     602          15 :   case Attribute::Naked:
     603          15 :     return bitc::ATTR_KIND_NAKED;
     604          11 :   case Attribute::Nest:
     605          11 :     return bitc::ATTR_KIND_NEST;
     606         136 :   case Attribute::NoAlias:
     607         136 :     return bitc::ATTR_KIND_NO_ALIAS;
     608          26 :   case Attribute::NoBuiltin:
     609          26 :     return bitc::ATTR_KIND_NO_BUILTIN;
     610         178 :   case Attribute::NoCapture:
     611         178 :     return bitc::ATTR_KIND_NO_CAPTURE;
     612           2 :   case Attribute::NoDuplicate:
     613           2 :     return bitc::ATTR_KIND_NO_DUPLICATE;
     614          11 :   case Attribute::NoImplicitFloat:
     615          11 :     return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
     616         197 :   case Attribute::NoInline:
     617         197 :     return bitc::ATTR_KIND_NO_INLINE;
     618         325 :   case Attribute::NoRecurse:
     619         325 :     return bitc::ATTR_KIND_NO_RECURSE;
     620          13 :   case Attribute::NonLazyBind:
     621          13 :     return bitc::ATTR_KIND_NON_LAZY_BIND;
     622          49 :   case Attribute::NonNull:
     623          49 :     return bitc::ATTR_KIND_NON_NULL;
     624         216 :   case Attribute::Dereferenceable:
     625         216 :     return bitc::ATTR_KIND_DEREFERENCEABLE;
     626          18 :   case Attribute::DereferenceableOrNull:
     627          18 :     return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
     628          12 :   case Attribute::NoRedZone:
     629          12 :     return bitc::ATTR_KIND_NO_RED_ZONE;
     630          42 :   case Attribute::NoReturn:
     631          42 :     return bitc::ATTR_KIND_NO_RETURN;
     632        1019 :   case Attribute::NoUnwind:
     633        1019 :     return bitc::ATTR_KIND_NO_UNWIND;
     634          20 :   case Attribute::OptimizeForSize:
     635          20 :     return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
     636         108 :   case Attribute::OptimizeNone:
     637         108 :     return bitc::ATTR_KIND_OPTIMIZE_NONE;
     638         376 :   case Attribute::ReadNone:
     639         376 :     return bitc::ATTR_KIND_READ_NONE;
     640         135 :   case Attribute::ReadOnly:
     641         135 :     return bitc::ATTR_KIND_READ_ONLY;
     642          13 :   case Attribute::Returned:
     643          13 :     return bitc::ATTR_KIND_RETURNED;
     644          11 :   case Attribute::ReturnsTwice:
     645          11 :     return bitc::ATTR_KIND_RETURNS_TWICE;
     646         116 :   case Attribute::SExt:
     647         116 :     return bitc::ATTR_KIND_S_EXT;
     648          66 :   case Attribute::Speculatable:
     649          66 :     return bitc::ATTR_KIND_SPECULATABLE;
     650          15 :   case Attribute::StackAlignment:
     651          15 :     return bitc::ATTR_KIND_STACK_ALIGNMENT;
     652          64 :   case Attribute::StackProtect:
     653          64 :     return bitc::ATTR_KIND_STACK_PROTECT;
     654          11 :   case Attribute::StackProtectReq:
     655          11 :     return bitc::ATTR_KIND_STACK_PROTECT_REQ;
     656          11 :   case Attribute::StackProtectStrong:
     657          11 :     return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
     658           2 :   case Attribute::SafeStack:
     659           2 :     return bitc::ATTR_KIND_SAFESTACK;
     660           2 :   case Attribute::StrictFP:
     661           2 :     return bitc::ATTR_KIND_STRICT_FP;
     662          15 :   case Attribute::StructRet:
     663          15 :     return bitc::ATTR_KIND_STRUCT_RET;
     664          11 :   case Attribute::SanitizeAddress:
     665          11 :     return bitc::ATTR_KIND_SANITIZE_ADDRESS;
     666          11 :   case Attribute::SanitizeThread:
     667          11 :     return bitc::ATTR_KIND_SANITIZE_THREAD;
     668          11 :   case Attribute::SanitizeMemory:
     669          11 :     return bitc::ATTR_KIND_SANITIZE_MEMORY;
     670          11 :   case Attribute::SwiftError:
     671          11 :     return bitc::ATTR_KIND_SWIFT_ERROR;
     672           5 :   case Attribute::SwiftSelf:
     673           5 :     return bitc::ATTR_KIND_SWIFT_SELF;
     674          79 :   case Attribute::UWTable:
     675          79 :     return bitc::ATTR_KIND_UW_TABLE;
     676          23 :   case Attribute::WriteOnly:
     677          23 :     return bitc::ATTR_KIND_WRITEONLY;
     678          33 :   case Attribute::ZExt:
     679          33 :     return bitc::ATTR_KIND_Z_EXT;
     680           0 :   case Attribute::EndAttrKinds:
     681           0 :     llvm_unreachable("Can not encode end-attribute kinds marker.");
     682           0 :   case Attribute::None:
     683           0 :     llvm_unreachable("Can not encode none-attribute.");
     684             :   }
     685             : 
     686           0 :   llvm_unreachable("Trying to encode unknown attribute");
     687             : }
     688             : 
     689        3629 : void ModuleBitcodeWriter::writeAttributeGroupTable() {
     690             :   const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
     691        7258 :       VE.getAttributeGroups();
     692        6358 :   if (AttrGrps.empty()) return;
     693             : 
     694         900 :   Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
     695             : 
     696        1800 :   SmallVector<uint64_t, 64> Record;
     697        6054 :   for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
     698        2454 :     unsigned AttrListIndex = Pair.first;
     699        2454 :     AttributeSet AS = Pair.second;
     700        4908 :     Record.push_back(VE.getAttributeGroupID(Pair));
     701        2454 :     Record.push_back(AttrListIndex);
     702             : 
     703        9217 :     for (Attribute Attr : AS) {
     704        6763 :       if (Attr.isEnumAttribute()) {
     705        3364 :         Record.push_back(0);
     706        3364 :         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
     707        3399 :       } else if (Attr.isIntAttribute()) {
     708         280 :         Record.push_back(1);
     709         280 :         Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
     710         280 :         Record.push_back(Attr.getValueAsInt());
     711             :       } else {
     712        3119 :         StringRef Kind = Attr.getKindAsString();
     713        3119 :         StringRef Val = Attr.getValueAsString();
     714             : 
     715        3119 :         Record.push_back(Val.empty() ? 3 : 4);
     716        3119 :         Record.append(Kind.begin(), Kind.end());
     717        3119 :         Record.push_back(0);
     718        3119 :         if (!Val.empty()) {
     719        3047 :           Record.append(Val.begin(), Val.end());
     720        3047 :           Record.push_back(0);
     721             :         }
     722             :       }
     723             :     }
     724             : 
     725        2454 :     Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
     726        2454 :     Record.clear();
     727             :   }
     728             : 
     729         900 :   Stream.ExitBlock();
     730             : }
     731             : 
     732        3629 : void ModuleBitcodeWriter::writeAttributeTable() {
     733        3629 :   const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
     734        6358 :   if (Attrs.empty()) return;
     735             : 
     736         900 :   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
     737             : 
     738        1800 :   SmallVector<uint64_t, 64> Record;
     739        3945 :   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
     740        4290 :     AttributeList AL = Attrs[i];
     741        8296 :     for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) {
     742        4006 :       AttributeSet AS = AL.getAttributes(i);
     743        4006 :       if (AS.hasAttributes())
     744        8712 :         Record.push_back(VE.getAttributeGroupID({i, AS}));
     745             :     }
     746             : 
     747        2145 :     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
     748        2145 :     Record.clear();
     749             :   }
     750             : 
     751         900 :   Stream.ExitBlock();
     752             : }
     753             : 
     754             : /// WriteTypeTable - Write out the type table for a module.
     755        3629 : void ModuleBitcodeWriter::writeTypeTable() {
     756        3629 :   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
     757             : 
     758        3629 :   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
     759        7258 :   SmallVector<uint64_t, 64> TypeVals;
     760             : 
     761        3629 :   uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
     762             : 
     763             :   // Abbrev for TYPE_CODE_POINTER.
     764        7258 :   auto Abbv = std::make_shared<BitCodeAbbrev>();
     765       10887 :   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
     766       10887 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
     767       10887 :   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
     768       10887 :   unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
     769             : 
     770             :   // Abbrev for TYPE_CODE_FUNCTION.
     771       10887 :   Abbv = std::make_shared<BitCodeAbbrev>();
     772       10887 :   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
     773       10887 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
     774       10887 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
     775       10887 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
     776       10887 :   unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
     777             : 
     778             :   // Abbrev for TYPE_CODE_STRUCT_ANON.
     779       10887 :   Abbv = std::make_shared<BitCodeAbbrev>();
     780       10887 :   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
     781       10887 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
     782       10887 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
     783       10887 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
     784       10887 :   unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
     785             : 
     786             :   // Abbrev for TYPE_CODE_STRUCT_NAME.
     787       10887 :   Abbv = std::make_shared<BitCodeAbbrev>();
     788       10887 :   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
     789       10887 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
     790       10887 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
     791       10887 :   unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
     792             : 
     793             :   // Abbrev for TYPE_CODE_STRUCT_NAMED.
     794       10887 :   Abbv = std::make_shared<BitCodeAbbrev>();
     795       10887 :   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
     796       10887 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
     797       10887 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
     798       10887 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
     799       10887 :   unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
     800             : 
     801             :   // Abbrev for TYPE_CODE_ARRAY.
     802       10887 :   Abbv = std::make_shared<BitCodeAbbrev>();
     803       10887 :   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
     804       10887 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
     805       10887 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
     806       10887 :   unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
     807             : 
     808             :   // Emit an entry count so the reader can reserve space.
     809        3629 :   TypeVals.push_back(TypeList.size());
     810        3629 :   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
     811        3629 :   TypeVals.clear();
     812             : 
     813             :   // Loop over all of the types, emitting each in turn.
     814       42818 :   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
     815       71120 :     Type *T = TypeList[i];
     816       35560 :     int AbbrevToUse = 0;
     817       35560 :     unsigned Code = 0;
     818             : 
     819       35560 :     switch (T->getTypeID()) {
     820        2982 :     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;      break;
     821          25 :     case Type::HalfTyID:      Code = bitc::TYPE_CODE_HALF;      break;
     822         282 :     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;     break;
     823         172 :     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE;    break;
     824          22 :     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80;  break;
     825          11 :     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128;     break;
     826          11 :     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
     827         516 :     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;     break;
     828        3629 :     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA;  break;
     829           9 :     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX;   break;
     830          10 :     case Type::TokenTyID:     Code = bitc::TYPE_CODE_TOKEN;     break;
     831        4867 :     case Type::IntegerTyID:
     832             :       // INTEGER: [width]
     833        4867 :       Code = bitc::TYPE_CODE_INTEGER;
     834        9734 :       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
     835        4867 :       break;
     836       12555 :     case Type::PointerTyID: {
     837       12555 :       PointerType *PTy = cast<PointerType>(T);
     838             :       // POINTER: [pointee type, address space]
     839       12555 :       Code = bitc::TYPE_CODE_POINTER;
     840       25110 :       TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
     841       12555 :       unsigned AddressSpace = PTy->getAddressSpace();
     842       12555 :       TypeVals.push_back(AddressSpace);
     843       12555 :       if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
     844             :       break;
     845             :     }
     846        6136 :     case Type::FunctionTyID: {
     847        6136 :       FunctionType *FT = cast<FunctionType>(T);
     848             :       // FUNCTION: [isvararg, retty, paramty x N]
     849        6136 :       Code = bitc::TYPE_CODE_FUNCTION;
     850        6136 :       TypeVals.push_back(FT->isVarArg());
     851       18408 :       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
     852       18947 :       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
     853       20025 :         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
     854        6136 :       AbbrevToUse = FunctionAbbrev;
     855        6136 :       break;
     856             :     }
     857        2054 :     case Type::StructTyID: {
     858        2054 :       StructType *ST = cast<StructType>(T);
     859             :       // STRUCT: [ispacked, eltty x N]
     860        2054 :       TypeVals.push_back(ST->isPacked());
     861             :       // Output all of the element types.
     862       11882 :       for (StructType::element_iterator I = ST->element_begin(),
     863        2054 :            E = ST->element_end(); I != E; ++I)
     864       19656 :         TypeVals.push_back(VE.getTypeID(*I));
     865             : 
     866        2054 :       if (ST->isLiteral()) {
     867         465 :         Code = bitc::TYPE_CODE_STRUCT_ANON;
     868         465 :         AbbrevToUse = StructAnonAbbrev;
     869             :       } else {
     870        1589 :         if (ST->isOpaque()) {
     871             :           Code = bitc::TYPE_CODE_OPAQUE;
     872             :         } else {
     873        1447 :           Code = bitc::TYPE_CODE_STRUCT_NAMED;
     874        1447 :           AbbrevToUse = StructNamedAbbrev;
     875             :         }
     876             : 
     877             :         // Emit the name if it is present.
     878        3178 :         if (!ST->getName().empty())
     879        1493 :           writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
     880             :                             StructNameAbbrev);
     881             :       }
     882             :       break;
     883             :     }
     884        1768 :     case Type::ArrayTyID: {
     885        1768 :       ArrayType *AT = cast<ArrayType>(T);
     886             :       // ARRAY: [numelts, eltty]
     887        1768 :       Code = bitc::TYPE_CODE_ARRAY;
     888        1768 :       TypeVals.push_back(AT->getNumElements());
     889        3536 :       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
     890        1768 :       AbbrevToUse = ArrayAbbrev;
     891        1768 :       break;
     892             :     }
     893         511 :     case Type::VectorTyID: {
     894         511 :       VectorType *VT = cast<VectorType>(T);
     895             :       // VECTOR [numelts, eltty]
     896         511 :       Code = bitc::TYPE_CODE_VECTOR;
     897         511 :       TypeVals.push_back(VT->getNumElements());
     898        1022 :       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
     899         511 :       break;
     900             :     }
     901             :     }
     902             : 
     903             :     // Emit the finished record.
     904       35560 :     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
     905       35560 :     TypeVals.clear();
     906             :   }
     907             : 
     908        3629 :   Stream.ExitBlock();
     909        3629 : }
     910             : 
     911       15266 : static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
     912       15266 :   switch (Linkage) {
     913             :   case GlobalValue::ExternalLinkage:
     914             :     return 0;
     915         262 :   case GlobalValue::WeakAnyLinkage:
     916         262 :     return 16;
     917         217 :   case GlobalValue::AppendingLinkage:
     918         217 :     return 2;
     919        1706 :   case GlobalValue::InternalLinkage:
     920        1706 :     return 3;
     921         141 :   case GlobalValue::LinkOnceAnyLinkage:
     922         141 :     return 18;
     923          30 :   case GlobalValue::ExternalWeakLinkage:
     924          30 :     return 7;
     925         114 :   case GlobalValue::CommonLinkage:
     926         114 :     return 8;
     927        1102 :   case GlobalValue::PrivateLinkage:
     928        1102 :     return 9;
     929         208 :   case GlobalValue::WeakODRLinkage:
     930         208 :     return 17;
     931         456 :   case GlobalValue::LinkOnceODRLinkage:
     932         456 :     return 19;
     933         109 :   case GlobalValue::AvailableExternallyLinkage:
     934         109 :     return 12;
     935             :   }
     936           0 :   llvm_unreachable("Invalid linkage");
     937             : }
     938             : 
     939             : static unsigned getEncodedLinkage(const GlobalValue &GV) {
     940       15266 :   return getEncodedLinkage(GV.getLinkage());
     941             : }
     942             : 
     943             : static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) {
     944         874 :   uint64_t RawFlags = 0;
     945         874 :   RawFlags |= Flags.ReadNone;
     946         874 :   RawFlags |= (Flags.ReadOnly << 1);
     947         874 :   RawFlags |= (Flags.NoRecurse << 2);
     948         874 :   RawFlags |= (Flags.ReturnDoesNotAlias << 3);
     949             :   return RawFlags;
     950             : }
     951             : 
     952             : // Decode the flags for GlobalValue in the summary
     953             : static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
     954        1230 :   uint64_t RawFlags = 0;
     955             : 
     956        1230 :   RawFlags |= Flags.NotEligibleToImport; // bool
     957        1230 :   RawFlags |= (Flags.Live << 1);
     958             :   // Linkage don't need to be remapped at that time for the summary. Any future
     959             :   // change to the getEncodedLinkage() function will need to be taken into
     960             :   // account here as well.
     961        1230 :   RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
     962             : 
     963             :   return RawFlags;
     964             : }
     965             : 
     966             : static unsigned getEncodedVisibility(const GlobalValue &GV) {
     967       11948 :   switch (GV.getVisibility()) {
     968             :   case GlobalValue::DefaultVisibility:   return 0;
     969         317 :   case GlobalValue::HiddenVisibility:    return 1;
     970          57 :   case GlobalValue::ProtectedVisibility: return 2;
     971             :   }
     972           0 :   llvm_unreachable("Invalid visibility");
     973             : }
     974             : 
     975             : static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
     976       11920 :   switch (GV.getDLLStorageClass()) {
     977             :   case GlobalValue::DefaultStorageClass:   return 0;
     978          17 :   case GlobalValue::DLLImportStorageClass: return 1;
     979          24 :   case GlobalValue::DLLExportStorageClass: return 2;
     980             :   }
     981           0 :   llvm_unreachable("Invalid DLL storage class");
     982             : }
     983             : 
     984             : static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
     985        2293 :   switch (GV.getThreadLocalMode()) {
     986             :     case GlobalVariable::NotThreadLocal:         return 0;
     987          17 :     case GlobalVariable::GeneralDynamicTLSModel: return 1;
     988          15 :     case GlobalVariable::LocalDynamicTLSModel:   return 2;
     989          14 :     case GlobalVariable::InitialExecTLSModel:    return 3;
     990          14 :     case GlobalVariable::LocalExecTLSModel:      return 4;
     991             :   }
     992           0 :   llvm_unreachable("Invalid TLS model");
     993             : }
     994             : 
     995             : static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
     996         494 :   switch (C.getSelectionKind()) {
     997             :   case Comdat::Any:
     998             :     return bitc::COMDAT_SELECTION_KIND_ANY;
     999           4 :   case Comdat::ExactMatch:
    1000             :     return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
    1001           5 :   case Comdat::Largest:
    1002             :     return bitc::COMDAT_SELECTION_KIND_LARGEST;
    1003           4 :   case Comdat::NoDuplicates:
    1004             :     return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
    1005           2 :   case Comdat::SameSize:
    1006             :     return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
    1007             :   }
    1008           0 :   llvm_unreachable("Invalid selection kind");
    1009             : }
    1010             : 
    1011             : static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
    1012       11920 :   switch (GV.getUnnamedAddr()) {
    1013             :   case GlobalValue::UnnamedAddr::None:   return 0;
    1014         720 :   case GlobalValue::UnnamedAddr::Local:  return 2;
    1015        1384 :   case GlobalValue::UnnamedAddr::Global: return 1;
    1016             :   }
    1017           0 :   llvm_unreachable("Invalid unnamed_addr");
    1018             : }
    1019             : 
    1020       15748 : size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
    1021       15748 :   if (GenerateHash)
    1022         212 :     Hasher.update(Str);
    1023       15748 :   return StrtabBuilder.add(Str);
    1024             : }
    1025             : 
    1026        3629 : void ModuleBitcodeWriter::writeComdats() {
    1027        7258 :   SmallVector<unsigned, 64> Vals;
    1028       15010 :   for (const Comdat *C : VE.getComdats()) {
    1029             :     // COMDAT: [strtab offset, strtab size, selection_kind]
    1030         494 :     Vals.push_back(addToStrtab(C->getName()));
    1031         988 :     Vals.push_back(C->getName().size());
    1032         494 :     Vals.push_back(getEncodedComdatSelectionKind(*C));
    1033         494 :     Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
    1034         494 :     Vals.clear();
    1035             :   }
    1036        3629 : }
    1037             : 
    1038             : /// Write a record that will eventually hold the word offset of the
    1039             : /// module-level VST. For now the offset is 0, which will be backpatched
    1040             : /// after the real VST is written. Saves the bit offset to backpatch.
    1041        3629 : void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
    1042             :   // Write a placeholder value in for the offset of the real VST,
    1043             :   // which is written after the function blocks so that it can include
    1044             :   // the offset of each function. The placeholder offset will be
    1045             :   // updated when the real VST is written.
    1046        7258 :   auto Abbv = std::make_shared<BitCodeAbbrev>();
    1047       10887 :   Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
    1048             :   // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
    1049             :   // hold the real VST offset. Must use fixed instead of VBR as we don't
    1050             :   // know how many VBR chunks to reserve ahead of time.
    1051       10887 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
    1052       10887 :   unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
    1053             : 
    1054             :   // Emit the placeholder
    1055        3629 :   uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
    1056        7258 :   Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
    1057             : 
    1058             :   // Compute and save the bit offset to the placeholder, which will be
    1059             :   // patched when the real VST is written. We can simply subtract the 32-bit
    1060             :   // fixed size from the current bit number to get the location to backpatch.
    1061        7258 :   VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
    1062        3629 : }
    1063             : 
    1064             : enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
    1065             : 
    1066             : /// Determine the encoding to use for the given string name and length.
    1067       32912 : static StringEncoding getStringEncoding(StringRef Str) {
    1068       32912 :   bool isChar6 = true;
    1069      536949 :   for (char C : Str) {
    1070      471125 :     if (isChar6)
    1071             :       isChar6 = BitCodeAbbrevOp::isChar6(C);
    1072      471125 :     if ((unsigned char)C & 128)
    1073             :       // don't bother scanning the rest.
    1074             :       return SE_Fixed8;
    1075             :   }
    1076       32912 :   if (isChar6)
    1077             :     return SE_Char6;
    1078        3928 :   return SE_Fixed7;
    1079             : }
    1080             : 
    1081             : /// Emit top-level description of module, including target triple, inline asm,
    1082             : /// descriptors for global variables, and function prototype info.
    1083             : /// Returns the bit offset to backpatch with the location of the real VST.
    1084        3629 : void ModuleBitcodeWriter::writeModuleInfo() {
    1085             :   // Emit various pieces of data attached to a module.
    1086        3629 :   if (!M.getTargetTriple().empty())
    1087        5661 :     writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
    1088             :                       0 /*TODO*/);
    1089        7258 :   const std::string &DL = M.getDataLayoutStr();
    1090        3629 :   if (!DL.empty())
    1091        1714 :     writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
    1092        3629 :   if (!M.getModuleInlineAsm().empty())
    1093         225 :     writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
    1094             :                       0 /*TODO*/);
    1095             : 
    1096             :   // Emit information about sections and GC, computing how many there are. Also
    1097             :   // compute the maximum alignment value.
    1098        7258 :   std::map<std::string, unsigned> SectionMap;
    1099        7258 :   std::map<std::string, unsigned> GCMap;
    1100        3629 :   unsigned MaxAlignment = 0;
    1101        3629 :   unsigned MaxGlobalType = 0;
    1102       12158 :   for (const GlobalValue &GV : M.globals()) {
    1103        9800 :     MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
    1104       14700 :     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
    1105        4900 :     if (GV.hasSection()) {
    1106             :       // Give section names unique ID's.
    1107        1323 :       unsigned &Entry = SectionMap[GV.getSection()];
    1108         441 :       if (!Entry) {
    1109         189 :         writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
    1110             :                           0 /*TODO*/);
    1111         189 :         Entry = SectionMap.size();
    1112             :       }
    1113             :     }
    1114             :   }
    1115       20514 :   for (const Function &F : M) {
    1116       28881 :     MaxAlignment = std::max(MaxAlignment, F.getAlignment());
    1117       19254 :     if (F.hasSection()) {
    1118             :       // Give section names unique ID's.
    1119         284 :       unsigned &Entry = SectionMap[F.getSection()];
    1120          71 :       if (!Entry) {
    1121         102 :         writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
    1122             :                           0 /*TODO*/);
    1123          51 :         Entry = SectionMap.size();
    1124             :       }
    1125             :     }
    1126        9627 :     if (F.hasGC()) {
    1127             :       // Same for GC names.
    1128          16 :       unsigned &Entry = GCMap[F.getGC()];
    1129          16 :       if (!Entry) {
    1130          28 :         writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
    1131             :                           0 /*TODO*/);
    1132          14 :         Entry = GCMap.size();
    1133             :       }
    1134             :     }
    1135             :   }
    1136             : 
    1137             :   // Emit abbrev for globals, now that we know # sections and max alignment.
    1138        3629 :   unsigned SimpleGVarAbbrev = 0;
    1139        7258 :   if (!M.global_empty()) {
    1140             :     // Add an abbrev for common globals with no visibility or thread localness.
    1141        2404 :     auto Abbv = std::make_shared<BitCodeAbbrev>();
    1142        3606 :     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
    1143        3606 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
    1144        3606 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
    1145        4808 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
    1146        2404 :                               Log2_32_Ceil(MaxGlobalType+1)));
    1147        3606 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // AddrSpace << 2
    1148             :                                                            //| explicitType << 1
    1149             :                                                            //| constant
    1150        3606 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Initializer.
    1151        3606 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
    1152        1202 :     if (MaxAlignment == 0)                                 // Alignment.
    1153        2559 :       Abbv->Add(BitCodeAbbrevOp(0));
    1154             :     else {
    1155         698 :       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
    1156        1396 :       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
    1157         698 :                                Log2_32_Ceil(MaxEncAlignment+1)));
    1158             :     }
    1159        1202 :     if (SectionMap.empty())                                    // Section.
    1160        3042 :       Abbv->Add(BitCodeAbbrevOp(0));
    1161             :     else
    1162         752 :       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
    1163         376 :                                Log2_32_Ceil(SectionMap.size()+1)));
    1164             :     // Don't bother emitting vis + thread local.
    1165        3606 :     SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
    1166             :   }
    1167             : 
    1168        7258 :   SmallVector<unsigned, 64> Vals;
    1169             :   // Emit the module's source file name.
    1170             :   {
    1171       10887 :     StringEncoding Bits = getStringEncoding(M.getSourceFileName());
    1172        3629 :     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
    1173        3629 :     if (Bits == SE_Char6)
    1174          50 :       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
    1175        3579 :     else if (Bits == SE_Fixed7)
    1176        3579 :       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
    1177             : 
    1178             :     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
    1179        7258 :     auto Abbv = std::make_shared<BitCodeAbbrev>();
    1180       10887 :     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
    1181       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    1182        7258 :     Abbv->Add(AbbrevOpToUse);
    1183       10887 :     unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
    1184             : 
    1185      217126 :     for (const auto P : M.getSourceFileName())
    1186      202610 :       Vals.push_back((unsigned char)P);
    1187             : 
    1188             :     // Emit the finished record.
    1189        3629 :     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
    1190        3629 :     Vals.clear();
    1191             :   }
    1192             : 
    1193             :   // Emit the global variable information.
    1194       12158 :   for (const GlobalVariable &GV : M.globals()) {
    1195        4900 :     unsigned AbbrevToUse = 0;
    1196             : 
    1197             :     // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
    1198             :     //             linkage, alignment, section, visibility, threadlocal,
    1199             :     //             unnamed_addr, externally_initialized, dllstorageclass,
    1200             :     //             comdat, attributes]
    1201        4900 :     Vals.push_back(addToStrtab(GV.getName()));
    1202        9800 :     Vals.push_back(GV.getName().size());
    1203        9800 :     Vals.push_back(VE.getTypeID(GV.getValueType()));
    1204       19600 :     Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
    1205        8903 :     Vals.push_back(GV.isDeclaration() ? 0 :
    1206        8006 :                    (VE.getValueID(GV.getInitializer()) + 1));
    1207        9800 :     Vals.push_back(getEncodedLinkage(GV));
    1208       14700 :     Vals.push_back(Log2_32(GV.getAlignment())+1);
    1209       15582 :     Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
    1210       14649 :     if (GV.isThreadLocal() ||
    1211       14409 :         GV.getVisibility() != GlobalValue::DefaultVisibility ||
    1212       12893 :         GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
    1213        6934 :         GV.isExternallyInitialized() ||
    1214       10374 :         GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
    1215       15114 :         GV.hasComdat() ||
    1216        3318 :         GV.hasAttributes()) {
    1217        3188 :       Vals.push_back(getEncodedVisibility(GV));
    1218        3188 :       Vals.push_back(getEncodedThreadLocalMode(GV));
    1219        3188 :       Vals.push_back(getEncodedUnnamedAddr(GV));
    1220        1594 :       Vals.push_back(GV.isExternallyInitialized());
    1221        3188 :       Vals.push_back(getEncodedDLLStorageClass(GV));
    1222        3188 :       Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
    1223             : 
    1224        1594 :       auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
    1225        3188 :       Vals.push_back(VE.getAttributeListID(AL));
    1226             :     } else {
    1227             :       AbbrevToUse = SimpleGVarAbbrev;
    1228             :     }
    1229             : 
    1230        4900 :     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
    1231        4900 :     Vals.clear();
    1232             :   }
    1233             : 
    1234             :   // Emit the function proto information.
    1235       20514 :   for (const Function &F : M) {
    1236             :     // FUNCTION:  [strtab offset, strtab size, type, callingconv, isproto,
    1237             :     //             linkage, paramattrs, alignment, section, visibility, gc,
    1238             :     //             unnamed_addr, prologuedata, dllstorageclass, comdat,
    1239             :     //             prefixdata, personalityfn]
    1240        9627 :     Vals.push_back(addToStrtab(F.getName()));
    1241       19254 :     Vals.push_back(F.getName().size());
    1242       28881 :     Vals.push_back(VE.getTypeID(F.getFunctionType()));
    1243        9627 :     Vals.push_back(F.getCallingConv());
    1244        9627 :     Vals.push_back(F.isDeclaration());
    1245       19254 :     Vals.push_back(getEncodedLinkage(F));
    1246       19254 :     Vals.push_back(VE.getAttributeListID(F.getAttributes()));
    1247       28881 :     Vals.push_back(Log2_32(F.getAlignment())+1);
    1248       29023 :     Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
    1249       19254 :     Vals.push_back(getEncodedVisibility(F));
    1250        9627 :     Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
    1251       19254 :     Vals.push_back(getEncodedUnnamedAddr(F));
    1252        9627 :     Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
    1253             :                                        : 0);
    1254       19254 :     Vals.push_back(getEncodedDLLStorageClass(F));
    1255       19254 :     Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
    1256        9627 :     Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
    1257             :                                      : 0);
    1258        9627 :     Vals.push_back(
    1259       19254 :         F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
    1260             : 
    1261        9627 :     unsigned AbbrevToUse = 0;
    1262        9627 :     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
    1263        9627 :     Vals.clear();
    1264             :   }
    1265             : 
    1266             :   // Emit the alias information.
    1267        7957 :   for (const GlobalAlias &A : M.aliases()) {
    1268             :     // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
    1269             :     //         visibility, dllstorageclass, threadlocal, unnamed_addr]
    1270         699 :     Vals.push_back(addToStrtab(A.getName()));
    1271        1398 :     Vals.push_back(A.getName().size());
    1272        1398 :     Vals.push_back(VE.getTypeID(A.getValueType()));
    1273        2097 :     Vals.push_back(A.getType()->getAddressSpace());
    1274        1398 :     Vals.push_back(VE.getValueID(A.getAliasee()));
    1275        1398 :     Vals.push_back(getEncodedLinkage(A));
    1276        1398 :     Vals.push_back(getEncodedVisibility(A));
    1277        1398 :     Vals.push_back(getEncodedDLLStorageClass(A));
    1278        1398 :     Vals.push_back(getEncodedThreadLocalMode(A));
    1279        1398 :     Vals.push_back(getEncodedUnnamedAddr(A));
    1280         699 :     unsigned AbbrevToUse = 0;
    1281         699 :     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
    1282         699 :     Vals.clear();
    1283             :   }
    1284             : 
    1285             :   // Emit the ifunc information.
    1286        7286 :   for (const GlobalIFunc &I : M.ifuncs()) {
    1287             :     // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
    1288             :     //         val#, linkage, visibility]
    1289          28 :     Vals.push_back(addToStrtab(I.getName()));
    1290          56 :     Vals.push_back(I.getName().size());
    1291          56 :     Vals.push_back(VE.getTypeID(I.getValueType()));
    1292          84 :     Vals.push_back(I.getType()->getAddressSpace());
    1293          56 :     Vals.push_back(VE.getValueID(I.getResolver()));
    1294          56 :     Vals.push_back(getEncodedLinkage(I));
    1295          56 :     Vals.push_back(getEncodedVisibility(I));
    1296          28 :     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
    1297          28 :     Vals.clear();
    1298             :   }
    1299             : 
    1300        3629 :   writeValueSymbolTableForwardDecl();
    1301        3629 : }
    1302             : 
    1303       16674 : static uint64_t getOptimizationFlags(const Value *V) {
    1304       16674 :   uint64_t Flags = 0;
    1305             : 
    1306        2447 :   if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
    1307        2447 :     if (OBO->hasNoSignedWrap())
    1308        1289 :       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
    1309        2447 :     if (OBO->hasNoUnsignedWrap())
    1310         437 :       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
    1311         351 :   } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
    1312         351 :     if (PEO->isExact())
    1313          68 :       Flags |= 1 << bitc::PEO_EXACT;
    1314         753 :   } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
    1315         753 :     if (FPMO->hasUnsafeAlgebra())
    1316          20 :       Flags |= FastMathFlags::UnsafeAlgebra;
    1317         753 :     if (FPMO->hasNoNaNs())
    1318         155 :       Flags |= FastMathFlags::NoNaNs;
    1319         753 :     if (FPMO->hasNoInfs())
    1320          54 :       Flags |= FastMathFlags::NoInfs;
    1321         753 :     if (FPMO->hasNoSignedZeros())
    1322          36 :       Flags |= FastMathFlags::NoSignedZeros;
    1323         753 :     if (FPMO->hasAllowReciprocal())
    1324          29 :       Flags |= FastMathFlags::AllowReciprocal;
    1325         753 :     if (FPMO->hasAllowContract())
    1326          37 :       Flags |= FastMathFlags::AllowContract;
    1327             :   }
    1328             : 
    1329       16674 :   return Flags;
    1330             : }
    1331             : 
    1332        3909 : void ModuleBitcodeWriter::writeValueAsMetadata(
    1333             :     const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
    1334             :   // Mimic an MDNode with a value as one operand.
    1335        3909 :   Value *V = MD->getValue();
    1336        7818 :   Record.push_back(VE.getTypeID(V->getType()));
    1337        3909 :   Record.push_back(VE.getValueID(V));
    1338        3909 :   Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
    1339        3909 :   Record.clear();
    1340        3909 : }
    1341             : 
    1342        4556 : void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
    1343             :                                        SmallVectorImpl<uint64_t> &Record,
    1344             :                                        unsigned Abbrev) {
    1345       16604 :   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
    1346       36144 :     Metadata *MD = N->getOperand(i);
    1347             :     assert(!(MD && isa<LocalAsMetadata>(MD)) &&
    1348             :            "Unexpected function-local metadata");
    1349       24096 :     Record.push_back(VE.getMetadataOrNullID(MD));
    1350             :   }
    1351        4556 :   Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
    1352             :                                     : bitc::METADATA_NODE,
    1353             :                     Record, Abbrev);
    1354        4556 :   Record.clear();
    1355        4556 : }
    1356             : 
    1357         860 : unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
    1358             :   // Assume the column is usually under 128, and always output the inlined-at
    1359             :   // location (it's never more expensive than building an array size 1).
    1360        1720 :   auto Abbv = std::make_shared<BitCodeAbbrev>();
    1361        2580 :   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
    1362        2580 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
    1363        2580 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
    1364        2580 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
    1365        2580 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
    1366        2580 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
    1367        3440 :   return Stream.EmitAbbrev(std::move(Abbv));
    1368             : }
    1369             : 
    1370          51 : void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
    1371             :                                           SmallVectorImpl<uint64_t> &Record,
    1372             :                                           unsigned &Abbrev) {
    1373          51 :   if (!Abbrev)
    1374          11 :     Abbrev = createDILocationAbbrev();
    1375             : 
    1376         102 :   Record.push_back(N->isDistinct());
    1377          51 :   Record.push_back(N->getLine());
    1378          51 :   Record.push_back(N->getColumn());
    1379         153 :   Record.push_back(VE.getMetadataID(N->getScope()));
    1380         153 :   Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
    1381             : 
    1382          51 :   Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
    1383          51 :   Record.clear();
    1384          51 : }
    1385             : 
    1386         849 : unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
    1387             :   // Assume the column is usually under 128, and always output the inlined-at
    1388             :   // location (it's never more expensive than building an array size 1).
    1389        1698 :   auto Abbv = std::make_shared<BitCodeAbbrev>();
    1390        2547 :   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
    1391        2547 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
    1392        2547 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
    1393        2547 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
    1394        2547 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
    1395        2547 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    1396        2547 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
    1397        3396 :   return Stream.EmitAbbrev(std::move(Abbv));
    1398             : }
    1399             : 
    1400          20 : void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
    1401             :                                              SmallVectorImpl<uint64_t> &Record,
    1402             :                                              unsigned &Abbrev) {
    1403          20 :   if (!Abbrev)
    1404           0 :     Abbrev = createGenericDINodeAbbrev();
    1405             : 
    1406          40 :   Record.push_back(N->isDistinct());
    1407          20 :   Record.push_back(N->getTag());
    1408          20 :   Record.push_back(0); // Per-tag version field; unused for now.
    1409             : 
    1410          75 :   for (auto &I : N->operands())
    1411         105 :     Record.push_back(VE.getMetadataOrNullID(I));
    1412             : 
    1413          20 :   Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
    1414          20 :   Record.clear();
    1415          20 : }
    1416             : 
    1417             : static uint64_t rotateSign(int64_t I) {
    1418          64 :   uint64_t U = I;
    1419          64 :   return I < 0 ? ~(U << 1) : U << 1;
    1420             : }
    1421             : 
    1422          46 : void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
    1423             :                                           SmallVectorImpl<uint64_t> &Record,
    1424             :                                           unsigned Abbrev) {
    1425          92 :   Record.push_back(N->isDistinct());
    1426          46 :   Record.push_back(N->getCount());
    1427          92 :   Record.push_back(rotateSign(N->getLowerBound()));
    1428             : 
    1429          46 :   Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
    1430          46 :   Record.clear();
    1431          46 : }
    1432             : 
    1433          18 : void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
    1434             :                                             SmallVectorImpl<uint64_t> &Record,
    1435             :                                             unsigned Abbrev) {
    1436          36 :   Record.push_back(N->isDistinct());
    1437          36 :   Record.push_back(rotateSign(N->getValue()));
    1438          54 :   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
    1439             : 
    1440          18 :   Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
    1441          18 :   Record.clear();
    1442          18 : }
    1443             : 
    1444         202 : void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
    1445             :                                            SmallVectorImpl<uint64_t> &Record,
    1446             :                                            unsigned Abbrev) {
    1447         404 :   Record.push_back(N->isDistinct());
    1448         202 :   Record.push_back(N->getTag());
    1449         606 :   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
    1450         202 :   Record.push_back(N->getSizeInBits());
    1451         202 :   Record.push_back(N->getAlignInBits());
    1452         202 :   Record.push_back(N->getEncoding());
    1453             : 
    1454         202 :   Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
    1455         202 :   Record.clear();
    1456         202 : }
    1457             : 
    1458         151 : void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
    1459             :                                              SmallVectorImpl<uint64_t> &Record,
    1460             :                                              unsigned Abbrev) {
    1461         302 :   Record.push_back(N->isDistinct());
    1462         151 :   Record.push_back(N->getTag());
    1463         453 :   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
    1464         453 :   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
    1465         151 :   Record.push_back(N->getLine());
    1466         453 :   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
    1467         453 :   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
    1468         151 :   Record.push_back(N->getSizeInBits());
    1469         151 :   Record.push_back(N->getAlignInBits());
    1470         151 :   Record.push_back(N->getOffsetInBits());
    1471         151 :   Record.push_back(N->getFlags());
    1472         453 :   Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
    1473             : 
    1474             :   // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
    1475             :   // that there is no DWARF address space associated with DIDerivedType.
    1476         302 :   if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
    1477          12 :     Record.push_back(*DWARFAddressSpace + 1);
    1478             :   else
    1479         145 :     Record.push_back(0);
    1480             : 
    1481         151 :   Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
    1482         151 :   Record.clear();
    1483         151 : }
    1484             : 
    1485         251 : void ModuleBitcodeWriter::writeDICompositeType(
    1486             :     const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
    1487             :     unsigned Abbrev) {
    1488         251 :   const unsigned IsNotUsedInOldTypeRef = 0x2;
    1489         502 :   Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
    1490         251 :   Record.push_back(N->getTag());
    1491         753 :   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
    1492         753 :   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
    1493         251 :   Record.push_back(N->getLine());
    1494         753 :   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
    1495         753 :   Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
    1496         251 :   Record.push_back(N->getSizeInBits());
    1497         251 :   Record.push_back(N->getAlignInBits());
    1498         251 :   Record.push_back(N->getOffsetInBits());
    1499         251 :   Record.push_back(N->getFlags());
    1500         753 :   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
    1501         251 :   Record.push_back(N->getRuntimeLang());
    1502         753 :   Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
    1503         753 :   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
    1504         753 :   Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
    1505             : 
    1506         251 :   Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
    1507         251 :   Record.clear();
    1508         251 : }
    1509             : 
    1510         286 : void ModuleBitcodeWriter::writeDISubroutineType(
    1511             :     const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
    1512             :     unsigned Abbrev) {
    1513         286 :   const unsigned HasNoOldTypeRefs = 0x2;
    1514         572 :   Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
    1515         286 :   Record.push_back(N->getFlags());
    1516         858 :   Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
    1517         286 :   Record.push_back(N->getCC());
    1518             : 
    1519         286 :   Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
    1520         286 :   Record.clear();
    1521         286 : }
    1522             : 
    1523         516 : void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
    1524             :                                       SmallVectorImpl<uint64_t> &Record,
    1525             :                                       unsigned Abbrev) {
    1526        1032 :   Record.push_back(N->isDistinct());
    1527        1548 :   Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
    1528        1548 :   Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
    1529         516 :   Record.push_back(N->getChecksumKind());
    1530        1548 :   Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()));
    1531             : 
    1532         516 :   Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
    1533         516 :   Record.clear();
    1534         516 : }
    1535             : 
    1536         593 : void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
    1537             :                                              SmallVectorImpl<uint64_t> &Record,
    1538             :                                              unsigned Abbrev) {
    1539             :   assert(N->isDistinct() && "Expected distinct compile units");
    1540         593 :   Record.push_back(/* IsDistinct */ true);
    1541         593 :   Record.push_back(N->getSourceLanguage());
    1542        1779 :   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
    1543        1779 :   Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
    1544         593 :   Record.push_back(N->isOptimized());
    1545        1779 :   Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
    1546         593 :   Record.push_back(N->getRuntimeVersion());
    1547        1779 :   Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
    1548         593 :   Record.push_back(N->getEmissionKind());
    1549        1779 :   Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
    1550        1779 :   Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
    1551         593 :   Record.push_back(/* subprograms */ 0);
    1552        1779 :   Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
    1553        1779 :   Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
    1554         593 :   Record.push_back(N->getDWOId());
    1555        1779 :   Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
    1556         593 :   Record.push_back(N->getSplitDebugInlining());
    1557         593 :   Record.push_back(N->getDebugInfoForProfiling());
    1558         593 :   Record.push_back(N->getGnuPubnames());
    1559             : 
    1560         593 :   Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
    1561         593 :   Record.clear();
    1562         593 : }
    1563             : 
    1564         429 : void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
    1565             :                                             SmallVectorImpl<uint64_t> &Record,
    1566             :                                             unsigned Abbrev) {
    1567         429 :   uint64_t HasUnitFlag = 1 << 1;
    1568         858 :   Record.push_back(N->isDistinct() | HasUnitFlag);
    1569        1287 :   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
    1570        1287 :   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
    1571        1287 :   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
    1572        1287 :   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
    1573         429 :   Record.push_back(N->getLine());
    1574        1287 :   Record.push_back(VE.getMetadataOrNullID(N->getType()));
    1575         858 :   Record.push_back(N->isLocalToUnit());
    1576         858 :   Record.push_back(N->isDefinition());
    1577         429 :   Record.push_back(N->getScopeLine());
    1578        1287 :   Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
    1579         858 :   Record.push_back(N->getVirtuality());
    1580         429 :   Record.push_back(N->getVirtualIndex());
    1581         429 :   Record.push_back(N->getFlags());
    1582         858 :   Record.push_back(N->isOptimized());
    1583        1287 :   Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
    1584        1287 :   Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
    1585        1287 :   Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
    1586        1287 :   Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
    1587         429 :   Record.push_back(N->getThisAdjustment());
    1588        1287 :   Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
    1589             : 
    1590         429 :   Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
    1591         429 :   Record.clear();
    1592         429 : }
    1593             : 
    1594         119 : void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
    1595             :                                               SmallVectorImpl<uint64_t> &Record,
    1596             :                                               unsigned Abbrev) {
    1597         238 :   Record.push_back(N->isDistinct());
    1598         357 :   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
    1599         357 :   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
    1600         119 :   Record.push_back(N->getLine());
    1601         119 :   Record.push_back(N->getColumn());
    1602             : 
    1603         119 :   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
    1604         119 :   Record.clear();
    1605         119 : }
    1606             : 
    1607          52 : void ModuleBitcodeWriter::writeDILexicalBlockFile(
    1608             :     const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
    1609             :     unsigned Abbrev) {
    1610         104 :   Record.push_back(N->isDistinct());
    1611         156 :   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
    1612         156 :   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
    1613          52 :   Record.push_back(N->getDiscriminator());
    1614             : 
    1615          52 :   Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
    1616          52 :   Record.clear();
    1617          52 : }
    1618             : 
    1619          29 : void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
    1620             :                                            SmallVectorImpl<uint64_t> &Record,
    1621             :                                            unsigned Abbrev) {
    1622          87 :   Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
    1623          87 :   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
    1624          87 :   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
    1625             : 
    1626          29 :   Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
    1627          29 :   Record.clear();
    1628          29 : }
    1629             : 
    1630          13 : void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
    1631             :                                        SmallVectorImpl<uint64_t> &Record,
    1632             :                                        unsigned Abbrev) {
    1633          26 :   Record.push_back(N->isDistinct());
    1634          13 :   Record.push_back(N->getMacinfoType());
    1635          13 :   Record.push_back(N->getLine());
    1636          39 :   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
    1637          39 :   Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
    1638             : 
    1639          13 :   Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
    1640          13 :   Record.clear();
    1641          13 : }
    1642             : 
    1643          19 : void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
    1644             :                                            SmallVectorImpl<uint64_t> &Record,
    1645             :                                            unsigned Abbrev) {
    1646          38 :   Record.push_back(N->isDistinct());
    1647          19 :   Record.push_back(N->getMacinfoType());
    1648          19 :   Record.push_back(N->getLine());
    1649          57 :   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
    1650          57 :   Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
    1651             : 
    1652          19 :   Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
    1653          19 :   Record.clear();
    1654          19 : }
    1655             : 
    1656          12 : void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
    1657             :                                         SmallVectorImpl<uint64_t> &Record,
    1658             :                                         unsigned Abbrev) {
    1659          24 :   Record.push_back(N->isDistinct());
    1660          84 :   for (auto &I : N->operands())
    1661         180 :     Record.push_back(VE.getMetadataOrNullID(I));
    1662             : 
    1663          12 :   Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
    1664          12 :   Record.clear();
    1665          12 : }
    1666             : 
    1667          22 : void ModuleBitcodeWriter::writeDITemplateTypeParameter(
    1668             :     const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
    1669             :     unsigned Abbrev) {
    1670          44 :   Record.push_back(N->isDistinct());
    1671          66 :   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
    1672          66 :   Record.push_back(VE.getMetadataOrNullID(N->getType()));
    1673             : 
    1674          22 :   Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
    1675          22 :   Record.clear();
    1676          22 : }
    1677             : 
    1678          23 : void ModuleBitcodeWriter::writeDITemplateValueParameter(
    1679             :     const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
    1680             :     unsigned Abbrev) {
    1681          46 :   Record.push_back(N->isDistinct());
    1682          23 :   Record.push_back(N->getTag());
    1683          69 :   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
    1684          69 :   Record.push_back(VE.getMetadataOrNullID(N->getType()));
    1685          69 :   Record.push_back(VE.getMetadataOrNullID(N->getValue()));
    1686             : 
    1687          23 :   Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
    1688          23 :   Record.clear();
    1689          23 : }
    1690             : 
    1691          49 : void ModuleBitcodeWriter::writeDIGlobalVariable(
    1692             :     const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
    1693             :     unsigned Abbrev) {
    1694          49 :   const uint64_t Version = 1 << 1;
    1695          98 :   Record.push_back((uint64_t)N->isDistinct() | Version);
    1696         147 :   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
    1697         147 :   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
    1698         147 :   Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
    1699         147 :   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
    1700          49 :   Record.push_back(N->getLine());
    1701         147 :   Record.push_back(VE.getMetadataOrNullID(N->getType()));
    1702          49 :   Record.push_back(N->isLocalToUnit());
    1703          49 :   Record.push_back(N->isDefinition());
    1704          49 :   Record.push_back(/* expr */ 0);
    1705         147 :   Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
    1706          49 :   Record.push_back(N->getAlignInBits());
    1707             : 
    1708          49 :   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
    1709          49 :   Record.clear();
    1710          49 : }
    1711             : 
    1712         241 : void ModuleBitcodeWriter::writeDILocalVariable(
    1713             :     const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
    1714             :     unsigned Abbrev) {
    1715             :   // In order to support all possible bitcode formats in BitcodeReader we need
    1716             :   // to distinguish the following cases:
    1717             :   // 1) Record has no artificial tag (Record[1]),
    1718             :   //   has no obsolete inlinedAt field (Record[9]).
    1719             :   //   In this case Record size will be 8, HasAlignment flag is false.
    1720             :   // 2) Record has artificial tag (Record[1]),
    1721             :   //   has no obsolete inlignedAt field (Record[9]).
    1722             :   //   In this case Record size will be 9, HasAlignment flag is false.
    1723             :   // 3) Record has both artificial tag (Record[1]) and
    1724             :   //   obsolete inlignedAt field (Record[9]).
    1725             :   //   In this case Record size will be 10, HasAlignment flag is false.
    1726             :   // 4) Record has neither artificial tag, nor inlignedAt field, but
    1727             :   //   HasAlignment flag is true and Record[8] contains alignment value.
    1728         241 :   const uint64_t HasAlignmentFlag = 1 << 1;
    1729         482 :   Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
    1730         723 :   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
    1731         723 :   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
    1732         723 :   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
    1733         241 :   Record.push_back(N->getLine());
    1734         723 :   Record.push_back(VE.getMetadataOrNullID(N->getType()));
    1735         482 :   Record.push_back(N->getArg());
    1736         241 :   Record.push_back(N->getFlags());
    1737         241 :   Record.push_back(N->getAlignInBits());
    1738             : 
    1739         241 :   Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
    1740         241 :   Record.clear();
    1741         241 : }
    1742             : 
    1743          88 : void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
    1744             :                                             SmallVectorImpl<uint64_t> &Record,
    1745             :                                             unsigned Abbrev) {
    1746          88 :   Record.reserve(N->getElements().size() + 1);
    1747          88 :   const uint64_t Version = 3 << 1;
    1748         176 :   Record.push_back((uint64_t)N->isDistinct() | Version);
    1749         176 :   Record.append(N->elements_begin(), N->elements_end());
    1750             : 
    1751          88 :   Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
    1752          88 :   Record.clear();
    1753          88 : }
    1754             : 
    1755          34 : void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
    1756             :     const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
    1757             :     unsigned Abbrev) {
    1758          68 :   Record.push_back(N->isDistinct());
    1759         102 :   Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
    1760         102 :   Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
    1761             : 
    1762          34 :   Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
    1763          34 :   Record.clear();
    1764          34 : }
    1765             : 
    1766          16 : void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
    1767             :                                               SmallVectorImpl<uint64_t> &Record,
    1768             :                                               unsigned Abbrev) {
    1769          32 :   Record.push_back(N->isDistinct());
    1770          48 :   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
    1771          48 :   Record.push_back(VE.getMetadataOrNullID(N->getFile()));
    1772          16 :   Record.push_back(N->getLine());
    1773          48 :   Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
    1774          48 :   Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
    1775          16 :   Record.push_back(N->getAttributes());
    1776          48 :   Record.push_back(VE.getMetadataOrNullID(N->getType()));
    1777             : 
    1778          16 :   Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
    1779          16 :   Record.clear();
    1780          16 : }
    1781             : 
    1782          26 : void ModuleBitcodeWriter::writeDIImportedEntity(
    1783             :     const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
    1784             :     unsigned Abbrev) {
    1785          52 :   Record.push_back(N->isDistinct());
    1786          26 :   Record.push_back(N->getTag());
    1787          78 :   Record.push_back(VE.getMetadataOrNullID(N->getScope()));
    1788          78 :   Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
    1789          26 :   Record.push_back(N->getLine());
    1790          78 :   Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
    1791          78 :   Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
    1792             : 
    1793          26 :   Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
    1794          26 :   Record.clear();
    1795          26 : }
    1796             : 
    1797         811 : unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
    1798        1622 :   auto Abbv = std::make_shared<BitCodeAbbrev>();
    1799        2433 :   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
    1800        2433 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    1801        2433 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
    1802        3244 :   return Stream.EmitAbbrev(std::move(Abbv));
    1803             : }
    1804             : 
    1805         849 : void ModuleBitcodeWriter::writeNamedMetadata(
    1806             :     SmallVectorImpl<uint64_t> &Record) {
    1807        1698 :   if (M.named_metadata_empty())
    1808             :     return;
    1809             : 
    1810         811 :   unsigned Abbrev = createNamedMetadataAbbrev();
    1811        3233 :   for (const NamedMDNode &NMD : M.named_metadata()) {
    1812             :     // Write name.
    1813        1611 :     StringRef Str = NMD.getName();
    1814        3222 :     Record.append(Str.bytes_begin(), Str.bytes_end());
    1815        1611 :     Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
    1816        1611 :     Record.clear();
    1817             : 
    1818             :     // Write named metadata operands.
    1819        5299 :     for (const MDNode *N : NMD.operands())
    1820        7376 :       Record.push_back(VE.getMetadataID(N));
    1821        1611 :     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
    1822        1611 :     Record.clear();
    1823             :   }
    1824             : }
    1825             : 
    1826        1139 : unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
    1827        2278 :   auto Abbv = std::make_shared<BitCodeAbbrev>();
    1828        3417 :   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
    1829        3417 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
    1830        3417 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
    1831        3417 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
    1832        4556 :   return Stream.EmitAbbrev(std::move(Abbv));
    1833             : }
    1834             : 
    1835             : /// Write out a record for MDString.
    1836             : ///
    1837             : /// All the metadata strings in a metadata block are emitted in a single
    1838             : /// record.  The sizes and strings themselves are shoved into a blob.
    1839        1310 : void ModuleBitcodeWriter::writeMetadataStrings(
    1840             :     ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
    1841        1310 :   if (Strings.empty())
    1842         171 :     return;
    1843             : 
    1844             :   // Start the record with the number of strings.
    1845        1139 :   Record.push_back(bitc::METADATA_STRINGS);
    1846        1139 :   Record.push_back(Strings.size());
    1847             : 
    1848             :   // Emit the sizes of the strings in the blob.
    1849        2278 :   SmallString<256> Blob;
    1850             :   {
    1851        2278 :     BitstreamWriter W(Blob);
    1852        7261 :     for (const Metadata *MD : Strings)
    1853        9966 :       W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
    1854        1139 :     W.FlushToWord();
    1855             :   }
    1856             : 
    1857             :   // Add the offset to the strings to the record.
    1858        2278 :   Record.push_back(Blob.size());
    1859             : 
    1860             :   // Add the strings to the blob.
    1861        6122 :   for (const Metadata *MD : Strings)
    1862        9966 :     Blob.append(cast<MDString>(MD)->getString());
    1863             : 
    1864             :   // Emit the final record.
    1865        3417 :   Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
    1866        1139 :   Record.clear();
    1867             : }
    1868             : 
    1869             : // Generates an enum to use as an index in the Abbrev array of Metadata record.
    1870             : enum MetadataAbbrev : unsigned {
    1871             : #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
    1872             : #include "llvm/IR/Metadata.def"
    1873             :   LastPlusOne
    1874             : };
    1875             : 
    1876        1310 : void ModuleBitcodeWriter::writeMetadataRecords(
    1877             :     ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
    1878             :     std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
    1879        1310 :   if (MDs.empty())
    1880          21 :     return;
    1881             : 
    1882             :   // Initialize MDNode abbreviations.
    1883             : #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
    1884             : #include "llvm/IR/Metadata.def"
    1885             : 
    1886       14349 :   for (const Metadata *MD : MDs) {
    1887       11771 :     if (IndexPos)
    1888       27246 :       IndexPos->push_back(Stream.GetCurrentBitNo());
    1889        7862 :     if (const MDNode *N = dyn_cast<MDNode>(MD)) {
    1890             :       assert(N->isResolved() && "Expected forward references to be resolved");
    1891             : 
    1892       15724 :       switch (N->getMetadataID()) {
    1893           0 :       default:
    1894           0 :         llvm_unreachable("Invalid MDNode subclass");
    1895             : #define HANDLE_MDNODE_LEAF(CLASS)                                              \
    1896             :   case Metadata::CLASS##Kind:                                                  \
    1897             :     if (MDAbbrevs)                                                             \
    1898             :       write##CLASS(cast<CLASS>(N), Record,                                     \
    1899             :                    (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]);             \
    1900             :     else                                                                       \
    1901             :       write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev);                     \
    1902             :     continue;
    1903             : #include "llvm/IR/Metadata.def"
    1904             :       }
    1905             :     }
    1906        3909 :     writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
    1907             :   }
    1908             : }
    1909             : 
    1910        3629 : void ModuleBitcodeWriter::writeModuleMetadata() {
    1911       10047 :   if (!VE.hasMDs() && M.named_metadata_empty())
    1912        2780 :     return;
    1913             : 
    1914         849 :   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
    1915        1698 :   SmallVector<uint64_t, 64> Record;
    1916             : 
    1917             :   // Emit all abbrevs upfront, so that the reader can jump in the middle of the
    1918             :   // block and load any metadata.
    1919        1698 :   std::vector<unsigned> MDAbbrevs;
    1920             : 
    1921         849 :   MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
    1922         849 :   MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
    1923        1698 :   MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
    1924         849 :       createGenericDINodeAbbrev();
    1925             : 
    1926        1698 :   auto Abbv = std::make_shared<BitCodeAbbrev>();
    1927        2547 :   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
    1928        2547 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
    1929        2547 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
    1930        2547 :   unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
    1931             : 
    1932        2547 :   Abbv = std::make_shared<BitCodeAbbrev>();
    1933        2547 :   Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
    1934        2547 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    1935        2547 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
    1936        2547 :   unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
    1937             : 
    1938             :   // Emit MDStrings together upfront.
    1939        1698 :   writeMetadataStrings(VE.getMDStrings(), Record);
    1940             : 
    1941             :   // We only emit an index for the metadata record if we have more than a given
    1942             :   // (naive) threshold of metadatas, otherwise it is not worth it.
    1943        2547 :   if (VE.getNonMDStrings().size() > IndexThreshold) {
    1944             :     // Write a placeholder value in for the offset of the metadata index,
    1945             :     // which is written after the records, so that it can include
    1946             :     // the offset of each entry. The placeholder offset will be
    1947             :     // updated after all records are emitted.
    1948          78 :     uint64_t Vals[] = {0, 0};
    1949          78 :     Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
    1950             :   }
    1951             : 
    1952             :   // Compute and save the bit offset to the current position, which will be
    1953             :   // patched when we emit the index later. We can simply subtract the 64-bit
    1954             :   // fixed size from the current bit number to get the location to backpatch.
    1955        1698 :   uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
    1956             : 
    1957             :   // This index will contain the bitpos for each individual record.
    1958        1698 :   std::vector<uint64_t> IndexPos;
    1959        1698 :   IndexPos.reserve(VE.getNonMDStrings().size());
    1960             : 
    1961             :   // Write all the records
    1962        1698 :   writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
    1963             : 
    1964        2547 :   if (VE.getNonMDStrings().size() > IndexThreshold) {
    1965             :     // Now that we have emitted all the records we will emit the index. But
    1966             :     // first
    1967             :     // backpatch the forward reference so that the reader can skip the records
    1968             :     // efficiently.
    1969         156 :     Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
    1970         156 :                            Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
    1971             : 
    1972             :     // Delta encode the index.
    1973          78 :     uint64_t PreviousValue = IndexOffsetRecordBitPos;
    1974        3952 :     for (auto &Elt : IndexPos) {
    1975        3640 :       auto EltDelta = Elt - PreviousValue;
    1976        3640 :       PreviousValue = Elt;
    1977        3640 :       Elt = EltDelta;
    1978             :     }
    1979             :     // Emit the index record.
    1980          78 :     Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
    1981             :     IndexPos.clear();
    1982             :   }
    1983             : 
    1984             :   // Write the named metadata now.
    1985         849 :   writeNamedMetadata(Record);
    1986             : 
    1987          83 :   auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
    1988         166 :     SmallVector<uint64_t, 4> Record;
    1989         166 :     Record.push_back(VE.getValueID(&GO));
    1990          83 :     pushGlobalMetadataAttachment(Record, GO);
    1991          83 :     Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
    1992         932 :   };
    1993        5700 :   for (const Function &F : M)
    1994        4283 :     if (F.isDeclaration() && F.hasMetadata())
    1995          11 :       AddDeclAttachedMetadata(F);
    1996             :   // FIXME: Only store metadata for declarations here, and move data for global
    1997             :   // variable definitions to a separate block (PR28134).
    1998        4225 :   for (const GlobalVariable &GV : M.globals())
    1999        5054 :     if (GV.hasMetadata())
    2000          72 :       AddDeclAttachedMetadata(GV);
    2001             : 
    2002         849 :   Stream.ExitBlock();
    2003             : }
    2004             : 
    2005        7051 : void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
    2006       14102 :   if (!VE.hasMDs())
    2007        6590 :     return;
    2008             : 
    2009         461 :   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
    2010         922 :   SmallVector<uint64_t, 64> Record;
    2011         922 :   writeMetadataStrings(VE.getMDStrings(), Record);
    2012         922 :   writeMetadataRecords(VE.getNonMDStrings(), Record);
    2013         461 :   Stream.ExitBlock();
    2014             : }
    2015             : 
    2016         376 : void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
    2017             :     SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
    2018             :   // [n x [id, mdnode]]
    2019         752 :   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
    2020         376 :   GO.getAllMetadata(MDs);
    2021        1575 :   for (const auto &I : MDs) {
    2022         447 :     Record.push_back(I.first);
    2023         894 :     Record.push_back(VE.getMetadataID(I.second));
    2024             :   }
    2025         376 : }
    2026             : 
    2027         490 : void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
    2028         490 :   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
    2029             : 
    2030         980 :   SmallVector<uint64_t, 64> Record;
    2031             : 
    2032         980 :   if (F.hasMetadata()) {
    2033         293 :     pushGlobalMetadataAttachment(Record, F);
    2034         293 :     Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
    2035             :     Record.clear();
    2036             :   }
    2037             : 
    2038             :   // Write metadata attachments
    2039             :   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
    2040         980 :   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
    2041        3152 :   for (const BasicBlock &BB : F)
    2042       10748 :     for (const Instruction &I : BB) {
    2043        5702 :       MDs.clear();
    2044        5702 :       I.getAllMetadataOtherThanDebugLoc(MDs);
    2045             : 
    2046             :       // If no metadata, ignore instruction.
    2047        5702 :       if (MDs.empty()) continue;
    2048             : 
    2049         873 :       Record.push_back(VE.getInstructionID(&I));
    2050             : 
    2051        2709 :       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
    2052        1926 :         Record.push_back(MDs[i].first);
    2053        2889 :         Record.push_back(VE.getMetadataID(MDs[i].second));
    2054             :       }
    2055         873 :       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
    2056             :       Record.clear();
    2057             :     }
    2058             : 
    2059         490 :   Stream.ExitBlock();
    2060         490 : }
    2061             : 
    2062        3629 : void ModuleBitcodeWriter::writeModuleMetadataKinds() {
    2063        7258 :   SmallVector<uint64_t, 64> Record;
    2064             : 
    2065             :   // Write metadata kinds
    2066             :   // METADATA_KIND - [n x [id, name]]
    2067        7258 :   SmallVector<StringRef, 8> Names;
    2068        3629 :   M.getMDKindNames(Names);
    2069             : 
    2070        3629 :   if (Names.empty()) return;
    2071             : 
    2072        3629 :   Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
    2073             : 
    2074       91189 :   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
    2075       83931 :     Record.push_back(MDKindID);
    2076      167862 :     StringRef KName = Names[MDKindID];
    2077       83931 :     Record.append(KName.begin(), KName.end());
    2078             : 
    2079       83931 :     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
    2080       83931 :     Record.clear();
    2081             :   }
    2082             : 
    2083        3629 :   Stream.ExitBlock();
    2084             : }
    2085             : 
    2086        3629 : void ModuleBitcodeWriter::writeOperandBundleTags() {
    2087             :   // Write metadata kinds
    2088             :   //
    2089             :   // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
    2090             :   //
    2091             :   // OPERAND_BUNDLE_TAG - [strchr x N]
    2092             : 
    2093        7258 :   SmallVector<StringRef, 8> Tags;
    2094        3629 :   M.getOperandBundleTags(Tags);
    2095             : 
    2096        3629 :   if (Tags.empty())
    2097           0 :     return;
    2098             : 
    2099        3629 :   Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
    2100             : 
    2101        7258 :   SmallVector<uint64_t, 64> Record;
    2102             : 
    2103       21782 :   for (auto Tag : Tags) {
    2104       10895 :     Record.append(Tag.begin(), Tag.end());
    2105             : 
    2106       10895 :     Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
    2107       10895 :     Record.clear();
    2108             :   }
    2109             : 
    2110        3629 :   Stream.ExitBlock();
    2111             : }
    2112             : 
    2113        3629 : void ModuleBitcodeWriter::writeSyncScopeNames() {
    2114        7258 :   SmallVector<StringRef, 8> SSNs;
    2115        3629 :   M.getContext().getSyncScopeNames(SSNs);
    2116        3629 :   if (SSNs.empty())
    2117           0 :     return;
    2118             : 
    2119        3629 :   Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
    2120             : 
    2121        7258 :   SmallVector<uint64_t, 64> Record;
    2122       18165 :   for (auto SSN : SSNs) {
    2123        7278 :     Record.append(SSN.begin(), SSN.end());
    2124        7278 :     Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
    2125        7278 :     Record.clear();
    2126             :   }
    2127             : 
    2128        3629 :   Stream.ExitBlock();
    2129             : }
    2130             : 
    2131       11812 : static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
    2132       11812 :   if ((int64_t)V >= 0)
    2133       10903 :     Vals.push_back(V << 1);
    2134             :   else
    2135         909 :     Vals.push_back((-V << 1) | 1);
    2136       11812 : }
    2137             : 
    2138        8564 : void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
    2139             :                                          bool isGlobal) {
    2140       12467 :   if (FirstVal == LastVal) return;
    2141             : 
    2142        4661 :   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
    2143             : 
    2144        4661 :   unsigned AggregateAbbrev = 0;
    2145        4661 :   unsigned String8Abbrev = 0;
    2146        4661 :   unsigned CString7Abbrev = 0;
    2147        4661 :   unsigned CString6Abbrev = 0;
    2148             :   // If this is a constant pool for the module, emit module-specific abbrevs.
    2149        4661 :   if (isGlobal) {
    2150             :     // Abbrev for CST_CODE_AGGREGATE.
    2151        3026 :     auto Abbv = std::make_shared<BitCodeAbbrev>();
    2152        4539 :     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
    2153        4539 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    2154        6052 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
    2155        4539 :     AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
    2156             : 
    2157             :     // Abbrev for CST_CODE_STRING.
    2158        4539 :     Abbv = std::make_shared<BitCodeAbbrev>();
    2159        4539 :     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
    2160        4539 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    2161        4539 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
    2162        4539 :     String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
    2163             :     // Abbrev for CST_CODE_CSTRING.
    2164        4539 :     Abbv = std::make_shared<BitCodeAbbrev>();
    2165        4539 :     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
    2166        4539 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    2167        4539 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
    2168        4539 :     CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
    2169             :     // Abbrev for CST_CODE_CSTRING.
    2170        4539 :     Abbv = std::make_shared<BitCodeAbbrev>();
    2171        4539 :     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
    2172        4539 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    2173        4539 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
    2174        4539 :     CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
    2175             :   }
    2176             : 
    2177        9322 :   SmallVector<uint64_t, 64> Record;
    2178             : 
    2179        4661 :   const ValueEnumerator::ValueList &Vals = VE.getValues();
    2180        4661 :   Type *LastTy = nullptr;
    2181       23937 :   for (unsigned i = FirstVal; i != LastVal; ++i) {
    2182       38552 :     const Value *V = Vals[i].first;
    2183             :     // If we need to switch types, do so now.
    2184       19276 :     if (V->getType() != LastTy) {
    2185        9917 :       LastTy = V->getType();
    2186       19834 :       Record.push_back(VE.getTypeID(LastTy));
    2187        9917 :       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
    2188             :                         CONSTANTS_SETTYPE_ABBREV);
    2189             :       Record.clear();
    2190             :     }
    2191             : 
    2192          55 :     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
    2193         165 :       Record.push_back(unsigned(IA->hasSideEffects()) |
    2194         165 :                        unsigned(IA->isAlignStack()) << 1 |
    2195          55 :                        unsigned(IA->getDialect()&1) << 2);
    2196             : 
    2197             :       // Add the asm string.
    2198          55 :       const std::string &AsmStr = IA->getAsmString();
    2199          55 :       Record.push_back(AsmStr.size());
    2200         110 :       Record.append(AsmStr.begin(), AsmStr.end());
    2201             : 
    2202             :       // Add the constraint string.
    2203          55 :       const std::string &ConstraintStr = IA->getConstraintString();
    2204          55 :       Record.push_back(ConstraintStr.size());
    2205         110 :       Record.append(ConstraintStr.begin(), ConstraintStr.end());
    2206          55 :       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
    2207          55 :       Record.clear();
    2208          55 :       continue;
    2209             :     }
    2210       19221 :     const Constant *C = cast<Constant>(V);
    2211       19221 :     unsigned Code = -1U;
    2212       19221 :     unsigned AbbrevToUse = 0;
    2213       19221 :     if (C->isNullValue()) {
    2214             :       Code = bitc::CST_CODE_NULL;
    2215       32452 :     } else if (isa<UndefValue>(C)) {
    2216             :       Code = bitc::CST_CODE_UNDEF;
    2217       26276 :     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
    2218       10473 :       if (IV->getBitWidth() <= 64) {
    2219       10451 :         uint64_t V = IV->getSExtValue();
    2220       10451 :         emitSignedInt64(Record, V);
    2221       10451 :         Code = bitc::CST_CODE_INTEGER;
    2222       10451 :         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
    2223             :       } else {                             // Wide integers, > 64 bits in size.
    2224             :         // We have an arbitrary precision integer value to write whose
    2225             :         // bit width is > 64. However, in canonical unsigned integer
    2226             :         // format it is likely that the high bits are going to be zero.
    2227             :         // So, we only write the number of active words.
    2228          44 :         unsigned NWords = IV->getValue().getActiveWords();
    2229          44 :         const uint64_t *RawWords = IV->getValue().getRawData();
    2230          58 :         for (unsigned i = 0; i != NWords; ++i) {
    2231          36 :           emitSignedInt64(Record, RawWords[i]);
    2232             :         }
    2233             :         Code = bitc::CST_CODE_WIDE_INTEGER;
    2234             :       }
    2235        5666 :     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
    2236         336 :       Code = bitc::CST_CODE_FLOAT;
    2237         336 :       Type *Ty = CFP->getType();
    2238         860 :       if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
    2239         966 :         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
    2240          14 :       } else if (Ty->isX86_FP80Ty()) {
    2241             :         // api needed to prevent premature destruction
    2242             :         // bits are not in the same order as a normal i80 APInt, compensate.
    2243          26 :         APInt api = CFP->getValueAPF().bitcastToAPInt();
    2244          13 :         const uint64_t *p = api.getRawData();
    2245          13 :         Record.push_back((p[1] << 48) | (p[0] >> 16));
    2246          13 :         Record.push_back(p[0] & 0xffffLL);
    2247           1 :       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
    2248           2 :         APInt api = CFP->getValueAPF().bitcastToAPInt();
    2249           1 :         const uint64_t *p = api.getRawData();
    2250           1 :         Record.push_back(p[0]);
    2251           1 :         Record.push_back(p[1]);
    2252             :       } else {
    2253             :         assert(0 && "Unknown FP type!");
    2254             :       }
    2255        5995 :     } else if (isa<ConstantDataSequential>(C) &&
    2256        2002 :                cast<ConstantDataSequential>(C)->isString()) {
    2257         984 :       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
    2258             :       // Emit constant strings specially.
    2259         492 :       unsigned NumElts = Str->getNumElements();
    2260             :       // If this is a null-terminated string, use the denser CSTRING encoding.
    2261         492 :       if (Str->isCString()) {
    2262         462 :         Code = bitc::CST_CODE_CSTRING;
    2263         462 :         --NumElts;  // Don't encode the null, which isn't allowed by char6.
    2264             :       } else {
    2265             :         Code = bitc::CST_CODE_STRING;
    2266             :         AbbrevToUse = String8Abbrev;
    2267             :       }
    2268         492 :       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
    2269         492 :       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
    2270       17715 :       for (unsigned i = 0; i != NumElts; ++i) {
    2271       17223 :         unsigned char V = Str->getElementAsInteger(i);
    2272       17223 :         Record.push_back(V);
    2273       17223 :         isCStr7 &= (V & 128) == 0;
    2274       17223 :         if (isCStrChar6)
    2275             :           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
    2276             :       }
    2277             : 
    2278         492 :       if (isCStrChar6)
    2279             :         AbbrevToUse = CString6Abbrev;
    2280         156 :       else if (isCStr7)
    2281         126 :         AbbrevToUse = CString7Abbrev;
    2282             :     } else if (const ConstantDataSequential *CDS =
    2283        5011 :                   dyn_cast<ConstantDataSequential>(C)) {
    2284         509 :       Code = bitc::CST_CODE_DATA;
    2285         509 :       Type *EltTy = CDS->getType()->getElementType();
    2286        1018 :       if (isa<IntegerType>(EltTy)) {
    2287        1806 :         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
    2288        1342 :           Record.push_back(CDS->getElementAsInteger(i));
    2289             :       } else {
    2290         181 :         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
    2291         136 :           Record.push_back(
    2292         680 :               CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
    2293             :       }
    2294        3993 :     } else if (isa<ConstantAggregate>(C)) {
    2295        1201 :       Code = bitc::CST_CODE_AGGREGATE;
    2296        6291 :       for (const Value *Op : C->operands())
    2297        3889 :         Record.push_back(VE.getValueID(Op));
    2298             :       AbbrevToUse = AggregateAbbrev;
    2299        5507 :     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
    2300        2715 :       switch (CE->getOpcode()) {
    2301        1336 :       default:
    2302        2672 :         if (Instruction::isCast(CE->getOpcode())) {
    2303        1195 :           Code = bitc::CST_CODE_CE_CAST;
    2304        1195 :           Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
    2305        3585 :           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
    2306        2390 :           Record.push_back(VE.getValueID(C->getOperand(0)));
    2307        1195 :           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
    2308             :         } else {
    2309             :           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
    2310         141 :           Code = bitc::CST_CODE_CE_BINOP;
    2311         141 :           Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
    2312         282 :           Record.push_back(VE.getValueID(C->getOperand(0)));
    2313         282 :           Record.push_back(VE.getValueID(C->getOperand(1)));
    2314         141 :           uint64_t Flags = getOptimizationFlags(CE);
    2315         141 :           if (Flags != 0)
    2316          85 :             Record.push_back(Flags);
    2317             :         }
    2318             :         break;
    2319        1313 :       case Instruction::GetElementPtr: {
    2320        1313 :         Code = bitc::CST_CODE_CE_GEP;
    2321        2626 :         const auto *GO = cast<GEPOperator>(C);
    2322        2626 :         Record.push_back(VE.getTypeID(GO->getSourceElementType()));
    2323        2626 :         if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
    2324          30 :           Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
    2325          60 :           Record.push_back((*Idx << 1) | GO->isInBounds());
    2326        1283 :         } else if (GO->isInBounds())
    2327        1218 :           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
    2328        6629 :         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
    2329       12009 :           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
    2330        8006 :           Record.push_back(VE.getValueID(C->getOperand(i)));
    2331             :         }
    2332             :         break;
    2333             :       }
    2334           6 :       case Instruction::Select:
    2335           6 :         Code = bitc::CST_CODE_CE_SELECT;
    2336          12 :         Record.push_back(VE.getValueID(C->getOperand(0)));
    2337          12 :         Record.push_back(VE.getValueID(C->getOperand(1)));
    2338          12 :         Record.push_back(VE.getValueID(C->getOperand(2)));
    2339           6 :         break;
    2340          17 :       case Instruction::ExtractElement:
    2341          17 :         Code = bitc::CST_CODE_CE_EXTRACTELT;
    2342          51 :         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
    2343          34 :         Record.push_back(VE.getValueID(C->getOperand(0)));
    2344          51 :         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
    2345          34 :         Record.push_back(VE.getValueID(C->getOperand(1)));
    2346          17 :         break;
    2347           0 :       case Instruction::InsertElement:
    2348           0 :         Code = bitc::CST_CODE_CE_INSERTELT;
    2349           0 :         Record.push_back(VE.getValueID(C->getOperand(0)));
    2350           0 :         Record.push_back(VE.getValueID(C->getOperand(1)));
    2351           0 :         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
    2352           0 :         Record.push_back(VE.getValueID(C->getOperand(2)));
    2353           0 :         break;
    2354           0 :       case Instruction::ShuffleVector:
    2355             :         // If the return type and argument types are the same, this is a
    2356             :         // standard shufflevector instruction.  If the types are different,
    2357             :         // then the shuffle is widening or truncating the input vectors, and
    2358             :         // the argument type must also be encoded.
    2359           0 :         if (C->getType() == C->getOperand(0)->getType()) {
    2360             :           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
    2361             :         } else {
    2362           0 :           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
    2363           0 :           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
    2364             :         }
    2365           0 :         Record.push_back(VE.getValueID(C->getOperand(0)));
    2366           0 :         Record.push_back(VE.getValueID(C->getOperand(1)));
    2367           0 :         Record.push_back(VE.getValueID(C->getOperand(2)));
    2368           0 :         break;
    2369          43 :       case Instruction::ICmp:
    2370             :       case Instruction::FCmp:
    2371          43 :         Code = bitc::CST_CODE_CE_CMP;
    2372         129 :         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
    2373          86 :         Record.push_back(VE.getValueID(C->getOperand(0)));
    2374          86 :         Record.push_back(VE.getValueID(C->getOperand(1)));
    2375          43 :         Record.push_back(CE->getPredicate());
    2376          43 :         break;
    2377             :       }
    2378         154 :     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
    2379          77 :       Code = bitc::CST_CODE_BLOCKADDRESS;
    2380         308 :       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
    2381         154 :       Record.push_back(VE.getValueID(BA->getFunction()));
    2382         154 :       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
    2383             :     } else {
    2384             : #ifndef NDEBUG
    2385             :       C->dump();
    2386             : #endif
    2387           0 :       llvm_unreachable("Unknown constant!");
    2388             :     }
    2389       19221 :     Stream.EmitRecord(Code, Record, AbbrevToUse);
    2390       19221 :     Record.clear();
    2391             :   }
    2392             : 
    2393        4661 :   Stream.ExitBlock();
    2394             : }
    2395             : 
    2396        3629 : void ModuleBitcodeWriter::writeModuleConstants() {
    2397        3629 :   const ValueEnumerator::ValueList &Vals = VE.getValues();
    2398             : 
    2399             :   // Find the first constant to emit, which is the first non-globalvalue value.
    2400             :   // We know globalvalues have been emitted by WriteModuleInfo.
    2401       22512 :   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
    2402       33534 :     if (!isa<GlobalValue>(Vals[i].first)) {
    2403        1513 :       writeConstants(i, Vals.size(), true);
    2404        1513 :       return;
    2405             :     }
    2406             :   }
    2407             : }
    2408             : 
    2409             : /// pushValueAndType - The file has to encode both the value and type id for
    2410             : /// many values, because we need to know what type to create for forward
    2411             : /// references.  However, most operands are not forward references, so this type
    2412             : /// field is not needed.
    2413             : ///
    2414             : /// This function adds V's value ID to Vals.  If the value ID is higher than the
    2415             : /// instruction ID, then it is a forward reference, and it also includes the
    2416             : /// type ID.  The value ID that is written is encoded relative to the InstID.
    2417       54578 : bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
    2418             :                                            SmallVectorImpl<unsigned> &Vals) {
    2419       54578 :   unsigned ValID = VE.getValueID(V);
    2420             :   // Make encoding relative to the InstID.
    2421       54578 :   Vals.push_back(InstID - ValID);
    2422       54578 :   if (ValID >= InstID) {
    2423         184 :     Vals.push_back(VE.getTypeID(V->getType()));
    2424          92 :     return true;
    2425             :   }
    2426             :   return false;
    2427             : }
    2428             : 
    2429          41 : void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
    2430             :                                               unsigned InstID) {
    2431          82 :   SmallVector<unsigned, 64> Record;
    2432          41 :   LLVMContext &C = CS.getInstruction()->getContext();
    2433             : 
    2434         109 :   for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
    2435          68 :     const auto &Bundle = CS.getOperandBundleAt(i);
    2436         136 :     Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
    2437             : 
    2438         300 :     for (auto &Input : Bundle.Inputs)
    2439         164 :       pushValueAndType(Input, InstID, Record);
    2440             : 
    2441          68 :     Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
    2442          68 :     Record.clear();
    2443             :   }
    2444          41 : }
    2445             : 
    2446             : /// pushValue - Like pushValueAndType, but where the type of the value is
    2447             : /// omitted (perhaps it was already encoded in an earlier operand).
    2448             : void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
    2449             :                                     SmallVectorImpl<unsigned> &Vals) {
    2450       22351 :   unsigned ValID = VE.getValueID(V);
    2451       22351 :   Vals.push_back(InstID - ValID);
    2452             : }
    2453             : 
    2454             : void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
    2455             :                                           SmallVectorImpl<uint64_t> &Vals) {
    2456        1325 :   unsigned ValID = VE.getValueID(V);
    2457        1325 :   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
    2458        1325 :   emitSignedInt64(Vals, diff);
    2459             : }
    2460             : 
    2461             : /// WriteInstruction - Emit an instruction to the specified stream.
    2462       55178 : void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
    2463             :                                            unsigned InstID,
    2464             :                                            SmallVectorImpl<unsigned> &Vals) {
    2465       55178 :   unsigned Code = 0;
    2466       55178 :   unsigned AbbrevToUse = 0;
    2467       55178 :   VE.setInstructionID(&I);
    2468       55178 :   switch (I.getOpcode()) {
    2469        7253 :   default:
    2470       14506 :     if (Instruction::isCast(I.getOpcode())) {
    2471        3472 :       Code = bitc::FUNC_CODE_INST_CAST;
    2472        6944 :       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
    2473        3465 :         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
    2474        6944 :       Vals.push_back(VE.getTypeID(I.getType()));
    2475        6944 :       Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
    2476             :     } else {
    2477             :       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
    2478        3781 :       Code = bitc::FUNC_CODE_INST_BINOP;
    2479        7562 :       if (!pushValueAndType(I.getOperand(0), InstID, Vals))
    2480        3720 :         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
    2481       11343 :       pushValue(I.getOperand(1), InstID, Vals);
    2482        7562 :       Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
    2483        3781 :       uint64_t Flags = getOptimizationFlags(&I);
    2484        3781 :       if (Flags != 0) {
    2485        1604 :         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
    2486        1578 :           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
    2487        1604 :         Vals.push_back(Flags);
    2488             :       }
    2489             :     }
    2490             :     break;
    2491             : 
    2492        3194 :   case Instruction::GetElementPtr: {
    2493        3194 :     Code = bitc::FUNC_CODE_INST_GEP;
    2494        3194 :     AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
    2495        3194 :     auto &GEPInst = cast<GetElementPtrInst>(I);
    2496        3194 :     Vals.push_back(GEPInst.isInBounds());
    2497        6388 :     Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
    2498       15340 :     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
    2499       17904 :       pushValueAndType(I.getOperand(i), InstID, Vals);
    2500             :     break;
    2501             :   }
    2502         224 :   case Instruction::ExtractValue: {
    2503         224 :     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
    2504         448 :     pushValueAndType(I.getOperand(0), InstID, Vals);
    2505         224 :     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
    2506         448 :     Vals.append(EVI->idx_begin(), EVI->idx_end());
    2507         224 :     break;
    2508             :   }
    2509          38 :   case Instruction::InsertValue: {
    2510          38 :     Code = bitc::FUNC_CODE_INST_INSERTVAL;
    2511          76 :     pushValueAndType(I.getOperand(0), InstID, Vals);
    2512          76 :     pushValueAndType(I.getOperand(1), InstID, Vals);
    2513          38 :     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
    2514          76 :     Vals.append(IVI->idx_begin(), IVI->idx_end());
    2515          38 :     break;
    2516             :   }
    2517         176 :   case Instruction::Select:
    2518         176 :     Code = bitc::FUNC_CODE_INST_VSELECT;
    2519         352 :     pushValueAndType(I.getOperand(1), InstID, Vals);
    2520         528 :     pushValue(I.getOperand(2), InstID, Vals);
    2521         352 :     pushValueAndType(I.getOperand(0), InstID, Vals);
    2522         176 :     break;
    2523          46 :   case Instruction::ExtractElement:
    2524          46 :     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
    2525          92 :     pushValueAndType(I.getOperand(0), InstID, Vals);
    2526          92 :     pushValueAndType(I.getOperand(1), InstID, Vals);
    2527          46 :     break;
    2528          27 :   case Instruction::InsertElement:
    2529          27 :     Code = bitc::FUNC_CODE_INST_INSERTELT;
    2530          54 :     pushValueAndType(I.getOperand(0), InstID, Vals);
    2531          81 :     pushValue(I.getOperand(1), InstID, Vals);
    2532          54 :     pushValueAndType(I.getOperand(2), InstID, Vals);
    2533          27 :     break;
    2534          38 :   case Instruction::ShuffleVector:
    2535          38 :     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
    2536          76 :     pushValueAndType(I.getOperand(0), InstID, Vals);
    2537         114 :     pushValue(I.getOperand(1), InstID, Vals);
    2538          76 :     pushValue(I.getOperand(2), InstID, Vals);
    2539             :     break;
    2540        5183 :   case Instruction::ICmp:
    2541             :   case Instruction::FCmp: {
    2542             :     // compare returning Int1Ty or vector of Int1Ty
    2543        5183 :     Code = bitc::FUNC_CODE_INST_CMP2;
    2544       10366 :     pushValueAndType(I.getOperand(0), InstID, Vals);
    2545       15549 :     pushValue(I.getOperand(1), InstID, Vals);
    2546       15549 :     Vals.push_back(cast<CmpInst>(I).getPredicate());
    2547        5183 :     uint64_t Flags = getOptimizationFlags(&I);
    2548        5183 :     if (Flags != 0)
    2549           3 :       Vals.push_back(Flags);
    2550             :     break;
    2551             :   }
    2552             : 
    2553        7046 :   case Instruction::Ret:
    2554             :     {
    2555        7046 :       Code = bitc::FUNC_CODE_INST_RET;
    2556       14092 :       unsigned NumOperands = I.getNumOperands();
    2557        7046 :       if (NumOperands == 0)
    2558             :         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
    2559        2657 :       else if (NumOperands == 1) {
    2560        5314 :         if (!pushValueAndType(I.getOperand(0), InstID, Vals))
    2561        2657 :           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
    2562             :       } else {
    2563           0 :         for (unsigned i = 0, e = NumOperands; i != e; ++i)
    2564           0 :           pushValueAndType(I.getOperand(i), InstID, Vals);
    2565             :       }
    2566             :     }
    2567             :     break;
    2568        4439 :   case Instruction::Br:
    2569             :     {
    2570        4439 :       Code = bitc::FUNC_CODE_INST_BR;
    2571        4439 :       const BranchInst &II = cast<BranchInst>(I);
    2572        8878 :       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
    2573        4439 :       if (II.isConditional()) {
    2574        3734 :         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
    2575        1867 :         pushValue(II.getCondition(), InstID, Vals);
    2576             :       }
    2577             :     }
    2578             :     break;
    2579          62 :   case Instruction::Switch:
    2580             :     {
    2581          62 :       Code = bitc::FUNC_CODE_INST_SWITCH;
    2582          62 :       const SwitchInst &SI = cast<SwitchInst>(I);
    2583         186 :       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
    2584         124 :       pushValue(SI.getCondition(), InstID, Vals);
    2585         124 :       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
    2586         309 :       for (auto Case : SI.cases()) {
    2587         370 :         Vals.push_back(VE.getValueID(Case.getCaseValue()));
    2588         185 :         Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
    2589          62 :       }
    2590             :     }
    2591          62 :     break;
    2592          17 :   case Instruction::IndirectBr:
    2593          17 :     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
    2594          51 :     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
    2595             :     // Encode the address operand as relative, but not the basic blocks.
    2596          51 :     pushValue(I.getOperand(0), InstID, Vals);
    2597          60 :     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
    2598          43 :       Vals.push_back(VE.getValueID(I.getOperand(i)));
    2599             :     break;
    2600             : 
    2601         144 :   case Instruction::Invoke: {
    2602         144 :     const InvokeInst *II = cast<InvokeInst>(&I);
    2603         144 :     const Value *Callee = II->getCalledValue();
    2604         144 :     FunctionType *FTy = II->getFunctionType();
    2605             : 
    2606         144 :     if (II->hasOperandBundles())
    2607          22 :       writeOperandBundles(II, InstID);
    2608             : 
    2609         144 :     Code = bitc::FUNC_CODE_INST_INVOKE;
    2610             : 
    2611         288 :     Vals.push_back(VE.getAttributeListID(II->getAttributes()));
    2612         288 :     Vals.push_back(II->getCallingConv() | 1 << 13);
    2613         288 :     Vals.push_back(VE.getValueID(II->getNormalDest()));
    2614         288 :     Vals.push_back(VE.getValueID(II->getUnwindDest()));
    2615         288 :     Vals.push_back(VE.getTypeID(FTy));
    2616         144 :     pushValueAndType(Callee, InstID, Vals);
    2617             : 
    2618             :     // Emit value #'s for the fixed parameters.
    2619         388 :     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
    2620         300 :       pushValue(I.getOperand(i), InstID, Vals); // fixed param.
    2621             : 
    2622             :     // Emit type/value pairs for varargs params.
    2623         144 :     if (FTy->isVarArg()) {
    2624          18 :       for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
    2625          12 :            i != e; ++i)
    2626          12 :         pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
    2627             :     }
    2628             :     break;
    2629             :   }
    2630          16 :   case Instruction::Resume:
    2631          16 :     Code = bitc::FUNC_CODE_INST_RESUME;
    2632          32 :     pushValueAndType(I.getOperand(0), InstID, Vals);
    2633          16 :     break;
    2634           8 :   case Instruction::CleanupRet: {
    2635           8 :     Code = bitc::FUNC_CODE_INST_CLEANUPRET;
    2636           8 :     const auto &CRI = cast<CleanupReturnInst>(I);
    2637          16 :     pushValue(CRI.getCleanupPad(), InstID, Vals);
    2638           8 :     if (CRI.hasUnwindDest())
    2639           0 :       Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
    2640             :     break;
    2641             :   }
    2642           8 :   case Instruction::CatchRet: {
    2643           8 :     Code = bitc::FUNC_CODE_INST_CATCHRET;
    2644           8 :     const auto &CRI = cast<CatchReturnInst>(I);
    2645          16 :     pushValue(CRI.getCatchPad(), InstID, Vals);
    2646          16 :     Vals.push_back(VE.getValueID(CRI.getSuccessor()));
    2647           8 :     break;
    2648             :   }
    2649          33 :   case Instruction::CleanupPad:
    2650             :   case Instruction::CatchPad: {
    2651          33 :     const auto &FuncletPad = cast<FuncletPadInst>(I);
    2652          33 :     Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
    2653             :                                          : bitc::FUNC_CODE_INST_CLEANUPPAD;
    2654          66 :     pushValue(FuncletPad.getParentPad(), InstID, Vals);
    2655             : 
    2656          33 :     unsigned NumArgOperands = FuncletPad.getNumArgOperands();
    2657          33 :     Vals.push_back(NumArgOperands);
    2658          51 :     for (unsigned Op = 0; Op != NumArgOperands; ++Op)
    2659          18 :       pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
    2660             :     break;
    2661             :   }
    2662          16 :   case Instruction::CatchSwitch: {
    2663          16 :     Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
    2664          16 :     const auto &CatchSwitch = cast<CatchSwitchInst>(I);
    2665             : 
    2666          32 :     pushValue(CatchSwitch.getParentPad(), InstID, Vals);
    2667             : 
    2668          16 :     unsigned NumHandlers = CatchSwitch.getNumHandlers();
    2669          16 :     Vals.push_back(NumHandlers);
    2670          48 :     for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
    2671          16 :       Vals.push_back(VE.getValueID(CatchPadBB));
    2672             : 
    2673          16 :     if (CatchSwitch.hasUnwindDest())
    2674           8 :       Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
    2675             :     break;
    2676             :   }
    2677             :   case Instruction::Unreachable:
    2678             :     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
    2679             :     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
    2680             :     break;
    2681             : 
    2682         671 :   case Instruction::PHI: {
    2683         671 :     const PHINode &PN = cast<PHINode>(I);
    2684         671 :     Code = bitc::FUNC_CODE_INST_PHI;
    2685             :     // With the newer instruction encoding, forward references could give
    2686             :     // negative valued IDs.  This is most common for PHIs, so we use
    2687             :     // signed VBRs.
    2688        1342 :     SmallVector<uint64_t, 128> Vals64;
    2689        1342 :     Vals64.push_back(VE.getTypeID(PN.getType()));
    2690        2667 :     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
    2691        2650 :       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
    2692        2650 :       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
    2693             :     }
    2694             :     // Emit a Vals64 vector and exit.
    2695         671 :     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
    2696         671 :     Vals64.clear();
    2697             :     return;
    2698             :   }
    2699             : 
    2700          82 :   case Instruction::LandingPad: {
    2701          82 :     const LandingPadInst &LP = cast<LandingPadInst>(I);
    2702          82 :     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
    2703         164 :     Vals.push_back(VE.getTypeID(LP.getType()));
    2704         164 :     Vals.push_back(LP.isCleanup());
    2705         164 :     Vals.push_back(LP.getNumClauses());
    2706         184 :     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
    2707          20 :       if (LP.isCatch(I))
    2708          15 :         Vals.push_back(LandingPadInst::Catch);
    2709             :       else
    2710           5 :         Vals.push_back(LandingPadInst::Filter);
    2711          20 :       pushValueAndType(LP.getClause(I), InstID, Vals);
    2712             :     }
    2713             :     break;
    2714             :   }
    2715             : 
    2716        4948 :   case Instruction::Alloca: {
    2717        4948 :     Code = bitc::FUNC_CODE_INST_ALLOCA;
    2718        4948 :     const AllocaInst &AI = cast<AllocaInst>(I);
    2719        9896 :     Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
    2720       14844 :     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
    2721        9896 :     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
    2722        9896 :     unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
    2723             :     assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
    2724             :            "not enough bits for maximum alignment");
    2725             :     assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
    2726        4948 :     AlignRecord |= AI.isUsedWithInAlloca() << 5;
    2727        4948 :     AlignRecord |= 1 << 6;
    2728        4948 :     AlignRecord |= AI.isSwiftError() << 7;
    2729        4948 :     Vals.push_back(AlignRecord);
    2730             :     break;
    2731             :   }
    2732             : 
    2733        5878 :   case Instruction::Load:
    2734        5878 :     if (cast<LoadInst>(I).isAtomic()) {
    2735         101 :       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
    2736         202 :       pushValueAndType(I.getOperand(0), InstID, Vals);
    2737             :     } else {
    2738        5777 :       Code = bitc::FUNC_CODE_INST_LOAD;
    2739       11554 :       if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
    2740        5773 :         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
    2741             :     }
    2742       11756 :     Vals.push_back(VE.getTypeID(I.getType()));
    2743       23512 :     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
    2744       17634 :     Vals.push_back(cast<LoadInst>(I).isVolatile());
    2745        5878 :     if (cast<LoadInst>(I).isAtomic()) {
    2746         404 :       Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
    2747         303 :       Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
    2748             :     }
    2749             :     break;
    2750        7540 :   case Instruction::Store:
    2751        7540 :     if (cast<StoreInst>(I).isAtomic())
    2752             :       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
    2753             :     else
    2754        7455 :       Code = bitc::FUNC_CODE_INST_STORE;
    2755       15080 :     pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
    2756       15080 :     pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
    2757       30160 :     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
    2758       22620 :     Vals.push_back(cast<StoreInst>(I).isVolatile());
    2759        7540 :     if (cast<StoreInst>(I).isAtomic()) {
    2760         340 :       Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
    2761         170 :       Vals.push_back(
    2762         255 :           getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
    2763             :     }
    2764             :     break;
    2765         187 :   case Instruction::AtomicCmpXchg:
    2766         187 :     Code = bitc::FUNC_CODE_INST_CMPXCHG;
    2767         374 :     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
    2768         374 :     pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
    2769         561 :     pushValue(I.getOperand(2), InstID, Vals);        // newval.
    2770         561 :     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
    2771         374 :     Vals.push_back(
    2772         748 :         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
    2773         374 :     Vals.push_back(
    2774         561 :         getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
    2775         374 :     Vals.push_back(
    2776         748 :         getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
    2777         561 :     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
    2778         187 :     break;
    2779          43 :   case Instruction::AtomicRMW:
    2780          43 :     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
    2781          86 :     pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
    2782         129 :     pushValue(I.getOperand(1), InstID, Vals);        // val.
    2783          86 :     Vals.push_back(
    2784         129 :         getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
    2785         129 :     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
    2786         172 :     Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
    2787          86 :     Vals.push_back(
    2788         129 :         getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
    2789          43 :     break;
    2790          37 :   case Instruction::Fence:
    2791          37 :     Code = bitc::FUNC_CODE_INST_FENCE;
    2792         148 :     Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
    2793         111 :     Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
    2794          37 :     break;
    2795        7569 :   case Instruction::Call: {
    2796        7569 :     const CallInst &CI = cast<CallInst>(I);
    2797        7569 :     FunctionType *FTy = CI.getFunctionType();
    2798             : 
    2799        7569 :     if (CI.hasOperandBundles())
    2800          19 :       writeOperandBundles(&CI, InstID);
    2801             : 
    2802        7569 :     Code = bitc::FUNC_CODE_INST_CALL;
    2803             : 
    2804       15138 :     Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
    2805             : 
    2806        7569 :     unsigned Flags = getOptimizationFlags(&I);
    2807       30276 :     Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
    2808       15138 :                    unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
    2809        7569 :                    unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
    2810        7569 :                    1 << bitc::CALL_EXPLICIT_TYPE |
    2811       22707 :                    unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
    2812             :                    unsigned(Flags != 0) << bitc::CALL_FMF);
    2813        7569 :     if (Flags != 0)
    2814           6 :       Vals.push_back(Flags);
    2815             : 
    2816       15138 :     Vals.push_back(VE.getTypeID(FTy));
    2817        7569 :     pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
    2818             : 
    2819             :     // Emit value #'s for the fixed parameters.
    2820       15138 :     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
    2821             :       // Check for labels (can happen with asm labels).
    2822       32277 :       if (FTy->getParamType(i)->isLabelTy())
    2823           4 :         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
    2824             :       else
    2825       10757 :         pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
    2826             :     }
    2827             : 
    2828             :     // Emit type/value pairs for varargs params.
    2829        7569 :     if (FTy->isVarArg()) {
    2830        1291 :       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
    2831         838 :            i != e; ++i)
    2832         385 :         pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
    2833             :     }
    2834             :     break;
    2835             :   }
    2836          10 :   case Instruction::VAArg:
    2837          10 :     Code = bitc::FUNC_CODE_INST_VAARG;
    2838          30 :     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
    2839          30 :     pushValue(I.getOperand(0), InstID, Vals);                   // valist.
    2840          20 :     Vals.push_back(VE.getTypeID(I.getType())); // restype.
    2841          10 :     break;
    2842             :   }
    2843             : 
    2844       54507 :   Stream.EmitRecord(Code, Vals, AbbrevToUse);
    2845             :   Vals.clear();
    2846             : }
    2847             : 
    2848             : /// Write a GlobalValue VST to the module. The purpose of this data structure is
    2849             : /// to allow clients to efficiently find the function body.
    2850        3629 : void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
    2851             :   DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
    2852             :   // Get the offset of the VST we are writing, and backpatch it into
    2853             :   // the VST forward declaration record.
    2854        7258 :   uint64_t VSTOffset = Stream.GetCurrentBitNo();
    2855             :   // The BitcodeStartBit was the stream offset of the identification block.
    2856        3629 :   VSTOffset -= bitcodeStartBit();
    2857             :   assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
    2858             :   // Note that we add 1 here because the offset is relative to one word
    2859             :   // before the start of the identification block, which was historically
    2860             :   // always the start of the regular bitcode header.
    2861        7258 :   Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
    2862             : 
    2863        3629 :   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
    2864             : 
    2865        7258 :   auto Abbv = std::make_shared<BitCodeAbbrev>();
    2866       10887 :   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
    2867       10887 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
    2868       10887 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
    2869       10887 :   unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
    2870             : 
    2871       20514 :   for (const Function &F : M) {
    2872             :     uint64_t Record[2];
    2873             : 
    2874        9627 :     if (F.isDeclaration())
    2875        2576 :       continue;
    2876             : 
    2877        7051 :     Record[0] = VE.getValueID(&F);
    2878             : 
    2879             :     // Save the word offset of the function (from the start of the
    2880             :     // actual bitcode written to the stream).
    2881       14102 :     uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
    2882             :     assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
    2883             :     // Note that we add 1 here because the offset is relative to one word
    2884             :     // before the start of the identification block, which was historically
    2885             :     // always the start of the regular bitcode header.
    2886        7051 :     Record[1] = BitcodeIndex / 32 + 1;
    2887             : 
    2888        7051 :     Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
    2889             :   }
    2890             : 
    2891        3629 :   Stream.ExitBlock();
    2892        3629 : }
    2893             : 
    2894             : /// Emit names for arguments, instructions and basic blocks in a function.
    2895        6987 : void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
    2896             :     const ValueSymbolTable &VST) {
    2897        6987 :   if (VST.empty())
    2898        2736 :     return;
    2899             : 
    2900        4251 :   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
    2901             : 
    2902             :   // FIXME: Set up the abbrev, we know how many values there are!
    2903             :   // FIXME: We know if the type names can use 7-bit ascii.
    2904        8502 :   SmallVector<uint64_t, 64> NameVals;
    2905             : 
    2906       75126 :   for (const ValueName &Name : VST) {
    2907             :     // Figure out the encoding to use for the name.
    2908       29061 :     StringEncoding Bits = getStringEncoding(Name.getKey());
    2909             : 
    2910       29061 :     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
    2911       29061 :     NameVals.push_back(VE.getValueID(Name.getValue()));
    2912             : 
    2913             :     // VST_CODE_ENTRY:   [valueid, namechar x N]
    2914             :     // VST_CODE_BBENTRY: [bbid, namechar x N]
    2915             :     unsigned Code;
    2916       58122 :     if (isa<BasicBlock>(Name.getValue())) {
    2917        5644 :       Code = bitc::VST_CODE_BBENTRY;
    2918        5644 :       if (Bits == SE_Char6)
    2919        5590 :         AbbrevToUse = VST_BBENTRY_6_ABBREV;
    2920             :     } else {
    2921       23417 :       Code = bitc::VST_CODE_ENTRY;
    2922       23417 :       if (Bits == SE_Char6)
    2923             :         AbbrevToUse = VST_ENTRY_6_ABBREV;
    2924          74 :       else if (Bits == SE_Fixed7)
    2925          74 :         AbbrevToUse = VST_ENTRY_7_ABBREV;
    2926             :     }
    2927             : 
    2928      301263 :     for (const auto P : Name.getKey())
    2929      243141 :       NameVals.push_back((unsigned char)P);
    2930             : 
    2931             :     // Emit the finished record.
    2932       29061 :     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
    2933       29061 :     NameVals.clear();
    2934             :   }
    2935             : 
    2936        4251 :   Stream.ExitBlock();
    2937             : }
    2938             : 
    2939        1536 : void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
    2940             :   assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
    2941             :   unsigned Code;
    2942        3072 :   if (isa<BasicBlock>(Order.V))
    2943             :     Code = bitc::USELIST_CODE_BB;
    2944             :   else
    2945        1343 :     Code = bitc::USELIST_CODE_DEFAULT;
    2946             : 
    2947        7680 :   SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
    2948        1536 :   Record.push_back(VE.getValueID(Order.V));
    2949        1536 :   Stream.EmitRecord(Code, Record);
    2950        1536 : }
    2951             : 
    2952        6973 : void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
    2953             :   assert(VE.shouldPreserveUseListOrder() &&
    2954             :          "Expected to be preserving use-list order");
    2955             : 
    2956             :   auto hasMore = [&]() {
    2957       21668 :     return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
    2958        6973 :   };
    2959         649 :   if (!hasMore())
    2960             :     // Nothing to do.
    2961             :     return;
    2962             : 
    2963         649 :   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
    2964        1536 :   while (hasMore()) {
    2965        3072 :     writeUseList(std::move(VE.UseListOrders.back()));
    2966        1536 :     VE.UseListOrders.pop_back();
    2967             :   }
    2968         649 :   Stream.ExitBlock();
    2969             : }
    2970             : 
    2971             : /// Emit a function body to the module stream.
    2972        7051 : void ModuleBitcodeWriter::writeFunction(
    2973             :     const Function &F,
    2974             :     DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
    2975             :   // Save the bitcode index of the start of this function block for recording
    2976             :   // in the VST.
    2977       21153 :   FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
    2978             : 
    2979        7051 :   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
    2980        7051 :   VE.incorporateFunction(F);
    2981             : 
    2982       14102 :   SmallVector<unsigned, 64> Vals;
    2983             : 
    2984             :   // Emit the number of basic blocks, so the reader can create them ahead of
    2985             :   // time.
    2986       14102 :   Vals.push_back(VE.getBasicBlocks().size());
    2987        7051 :   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
    2988        7051 :   Vals.clear();
    2989             : 
    2990             :   // If there are function-local constants, emit them now.
    2991             :   unsigned CstStart, CstEnd;
    2992       14102 :   VE.getFunctionConstantRange(CstStart, CstEnd);
    2993        7051 :   writeConstants(CstStart, CstEnd, false);
    2994             : 
    2995             :   // If there is function-local metadata, emit it now.
    2996        7051 :   writeFunctionMetadata(F);
    2997             : 
    2998             :   // Keep a running idea of what the instruction ID is.
    2999        7051 :   unsigned InstID = CstEnd;
    3000             : 
    3001       14102 :   bool NeedsMetadataAttachment = F.hasMetadata();
    3002             : 
    3003        7051 :   DILocation *LastDL = nullptr;
    3004             :   // Finally, emit all the instructions, in order.
    3005       14102 :   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
    3006       48004 :     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
    3007       67179 :          I != E; ++I) {
    3008       55178 :       writeInstruction(*I, InstID, Vals);
    3009             : 
    3010      110356 :       if (!I->getType()->isVoidTy())
    3011       29782 :         ++InstID;
    3012             : 
    3013             :       // If the instruction has metadata, write a metadata attachment later.
    3014      110356 :       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
    3015             : 
    3016             :       // If the instruction has a debug location, emit it.
    3017      165534 :       DILocation *DL = I->getDebugLoc();
    3018       55178 :       if (!DL)
    3019       53197 :         continue;
    3020             : 
    3021        2764 :       if (DL == LastDL) {
    3022             :         // Just repeat the same debug loc as last time.
    3023         783 :         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
    3024         783 :         continue;
    3025             :       }
    3026             : 
    3027        1198 :       Vals.push_back(DL->getLine());
    3028        1198 :       Vals.push_back(DL->getColumn());
    3029        3594 :       Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
    3030        3594 :       Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
    3031        1198 :       Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
    3032        1198 :       Vals.clear();
    3033             : 
    3034        1198 :       LastDL = DL;
    3035             :     }
    3036             : 
    3037             :   // Emit names for all the instructions etc.
    3038        7051 :   if (auto *Symtab = F.getValueSymbolTable())
    3039        6987 :     writeFunctionLevelValueSymbolTable(*Symtab);
    3040             : 
    3041        7051 :   if (NeedsMetadataAttachment)
    3042         490 :     writeFunctionMetadataAttachment(F);
    3043        7051 :   if (VE.shouldPreserveUseListOrder())
    3044        4409 :     writeUseListBlock(&F);
    3045        7051 :   VE.purgeFunction();
    3046        7051 :   Stream.ExitBlock();
    3047        7051 : }
    3048             : 
    3049             : // Emit blockinfo, which defines the standard abbreviations etc.
    3050        3629 : void ModuleBitcodeWriter::writeBlockInfo() {
    3051             :   // We only want to emit block info records for blocks that have multiple
    3052             :   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
    3053             :   // Other blocks can define their abbrevs inline.
    3054        3629 :   Stream.EnterBlockInfoBlock();
    3055             : 
    3056             :   { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
    3057        7258 :     auto Abbv = std::make_shared<BitCodeAbbrev>();
    3058       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
    3059       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
    3060       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    3061       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
    3062       10887 :     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
    3063             :         VST_ENTRY_8_ABBREV)
    3064           0 :       llvm_unreachable("Unexpected abbrev ordering!");
    3065             :   }
    3066             : 
    3067             :   { // 7-bit fixed width VST_CODE_ENTRY strings.
    3068        7258 :     auto Abbv = std::make_shared<BitCodeAbbrev>();
    3069       10887 :     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
    3070       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
    3071       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    3072       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
    3073       10887 :     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
    3074             :         VST_ENTRY_7_ABBREV)
    3075           0 :       llvm_unreachable("Unexpected abbrev ordering!");
    3076             :   }
    3077             :   { // 6-bit char6 VST_CODE_ENTRY strings.
    3078        7258 :     auto Abbv = std::make_shared<BitCodeAbbrev>();
    3079       10887 :     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
    3080       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
    3081       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    3082       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
    3083       10887 :     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
    3084             :         VST_ENTRY_6_ABBREV)
    3085           0 :       llvm_unreachable("Unexpected abbrev ordering!");
    3086             :   }
    3087             :   { // 6-bit char6 VST_CODE_BBENTRY strings.
    3088        7258 :     auto Abbv = std::make_shared<BitCodeAbbrev>();
    3089       10887 :     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
    3090       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
    3091       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    3092       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
    3093       10887 :     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
    3094             :         VST_BBENTRY_6_ABBREV)
    3095           0 :       llvm_unreachable("Unexpected abbrev ordering!");
    3096             :   }
    3097             : 
    3098             :   { // SETTYPE abbrev for CONSTANTS_BLOCK.
    3099        7258 :     auto Abbv = std::make_shared<BitCodeAbbrev>();
    3100       10887 :     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
    3101       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
    3102             :                               VE.computeBitsRequiredForTypeIndicies()));
    3103       10887 :     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
    3104             :         CONSTANTS_SETTYPE_ABBREV)
    3105           0 :       llvm_unreachable("Unexpected abbrev ordering!");
    3106             :   }
    3107             : 
    3108             :   { // INTEGER abbrev for CONSTANTS_BLOCK.
    3109        7258 :     auto Abbv = std::make_shared<BitCodeAbbrev>();
    3110       10887 :     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
    3111       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
    3112       10887 :     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
    3113             :         CONSTANTS_INTEGER_ABBREV)
    3114           0 :       llvm_unreachable("Unexpected abbrev ordering!");
    3115             :   }
    3116             : 
    3117             :   { // CE_CAST abbrev for CONSTANTS_BLOCK.
    3118        7258 :     auto Abbv = std::make_shared<BitCodeAbbrev>();
    3119       10887 :     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
    3120       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
    3121       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
    3122             :                               VE.computeBitsRequiredForTypeIndicies()));
    3123       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
    3124             : 
    3125       10887 :     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
    3126             :         CONSTANTS_CE_CAST_Abbrev)
    3127           0 :       llvm_unreachable("Unexpected abbrev ordering!");
    3128             :   }
    3129             :   { // NULL abbrev for CONSTANTS_BLOCK.
    3130        7258 :     auto Abbv = std::make_shared<BitCodeAbbrev>();
    3131       10887 :     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
    3132       10887 :     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
    3133             :         CONSTANTS_NULL_Abbrev)
    3134           0 :       llvm_unreachable("Unexpected abbrev ordering!");
    3135             :   }
    3136             : 
    3137             :   // FIXME: This should only use space for first class types!
    3138             : 
    3139             :   { // INST_LOAD abbrev for FUNCTION_BLOCK.
    3140        7258 :     auto Abbv = std::make_shared<BitCodeAbbrev>();
    3141       10887 :     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
    3142       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
    3143       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,    // dest ty
    3144             :                               VE.computeBitsRequiredForTypeIndicies()));
    3145       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
    3146       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
    3147       10887 :     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
    3148             :         FUNCTION_INST_LOAD_ABBREV)
    3149           0 :       llvm_unreachable("Unexpected abbrev ordering!");
    3150             :   }
    3151             :   { // INST_BINOP abbrev for FUNCTION_BLOCK.
    3152        7258 :     auto Abbv = std::make_shared<BitCodeAbbrev>();
    3153       10887 :     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
    3154       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
    3155       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
    3156       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
    3157       10887 :     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
    3158             :         FUNCTION_INST_BINOP_ABBREV)
    3159           0 :       llvm_unreachable("Unexpected abbrev ordering!");
    3160             :   }
    3161             :   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
    3162        7258 :     auto Abbv = std::make_shared<BitCodeAbbrev>();
    3163       10887 :     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
    3164       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
    3165       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
    3166       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
    3167       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
    3168       10887 :     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
    3169             :         FUNCTION_INST_BINOP_FLAGS_ABBREV)
    3170           0 :       llvm_unreachable("Unexpected abbrev ordering!");
    3171             :   }
    3172             :   { // INST_CAST abbrev for FUNCTION_BLOCK.
    3173        7258 :     auto Abbv = std::make_shared<BitCodeAbbrev>();
    3174       10887 :     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
    3175       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
    3176       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
    3177             :                               VE.computeBitsRequiredForTypeIndicies()));
    3178       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
    3179       10887 :     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
    3180             :         FUNCTION_INST_CAST_ABBREV)
    3181           0 :       llvm_unreachable("Unexpected abbrev ordering!");
    3182             :   }
    3183             : 
    3184             :   { // INST_RET abbrev for FUNCTION_BLOCK.
    3185        7258 :     auto Abbv = std::make_shared<BitCodeAbbrev>();
    3186       10887 :     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
    3187       10887 :     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
    3188             :         FUNCTION_INST_RET_VOID_ABBREV)
    3189           0 :       llvm_unreachable("Unexpected abbrev ordering!");
    3190             :   }
    3191             :   { // INST_RET abbrev for FUNCTION_BLOCK.
    3192        7258 :     auto Abbv = std::make_shared<BitCodeAbbrev>();
    3193       10887 :     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
    3194       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
    3195       10887 :     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
    3196             :         FUNCTION_INST_RET_VAL_ABBREV)
    3197           0 :       llvm_unreachable("Unexpected abbrev ordering!");
    3198             :   }
    3199             :   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
    3200        7258 :     auto Abbv = std::make_shared<BitCodeAbbrev>();
    3201       10887 :     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
    3202       10887 :     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
    3203             :         FUNCTION_INST_UNREACHABLE_ABBREV)
    3204           0 :       llvm_unreachable("Unexpected abbrev ordering!");
    3205             :   }
    3206             :   {
    3207        7258 :     auto Abbv = std::make_shared<BitCodeAbbrev>();
    3208       10887 :     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
    3209       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
    3210       14516 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
    3211       10887 :                               Log2_32_Ceil(VE.getTypes().size() + 1)));
    3212       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    3213       10887 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
    3214       10887 :     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
    3215             :         FUNCTION_INST_GEP_ABBREV)
    3216           0 :       llvm_unreachable("Unexpected abbrev ordering!");
    3217             :   }
    3218             : 
    3219        3629 :   Stream.ExitBlock();
    3220        3629 : }
    3221             : 
    3222             : /// Write the module path strings, currently only used when generating
    3223             : /// a combined index file.
    3224         130 : void IndexBitcodeWriter::writeModStrings() {
    3225         130 :   Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
    3226             : 
    3227             :   // TODO: See which abbrev sizes we actually need to emit
    3228             : 
    3229             :   // 8-bit fixed-width MST_ENTRY strings.
    3230         260 :   auto Abbv = std::make_shared<BitCodeAbbrev>();
    3231         390 :   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
    3232         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
    3233         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    3234         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
    3235         390 :   unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
    3236             : 
    3237             :   // 7-bit fixed width MST_ENTRY strings.
    3238         390 :   Abbv = std::make_shared<BitCodeAbbrev>();
    3239         390 :   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
    3240         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
    3241         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    3242         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
    3243         390 :   unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
    3244             : 
    3245             :   // 6-bit char6 MST_ENTRY strings.
    3246         390 :   Abbv = std::make_shared<BitCodeAbbrev>();
    3247         390 :   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
    3248         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
    3249         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    3250         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
    3251         390 :   unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
    3252             : 
    3253             :   // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
    3254         390 :   Abbv = std::make_shared<BitCodeAbbrev>();
    3255         390 :   Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
    3256         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
    3257         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
    3258         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
    3259         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
    3260         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
    3261         390 :   unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
    3262             : 
    3263         260 :   SmallVector<unsigned, 64> Vals;
    3264         130 :   forEachModule(
    3265         214 :       [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
    3266         214 :         StringRef Key = MPSE.getKey();
    3267         214 :         const auto &Value = MPSE.getValue();
    3268         214 :         StringEncoding Bits = getStringEncoding(Key);
    3269         214 :         unsigned AbbrevToUse = Abbrev8Bit;
    3270         214 :         if (Bits == SE_Char6)
    3271           1 :           AbbrevToUse = Abbrev6Bit;
    3272         213 :         else if (Bits == SE_Fixed7)
    3273         213 :           AbbrevToUse = Abbrev7Bit;
    3274             : 
    3275         708 :         Vals.push_back(Value.first);
    3276         428 :         Vals.append(Key.begin(), Key.end());
    3277             : 
    3278             :         // Emit the finished record.
    3279         461 :         Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
    3280             : 
    3281             :         // Emit an optional hash for the module now
    3282         214 :         const auto &Hash = Value.second;
    3283         428 :         if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
    3284         132 :           Vals.assign(Hash.begin(), Hash.end());
    3285             :           // Emit the hash record.
    3286          66 :           Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
    3287             :         }
    3288             : 
    3289         428 :         Vals.clear();
    3290         214 :       });
    3291         130 :   Stream.ExitBlock();
    3292         130 : }
    3293             : 
    3294             : /// Write the function type metadata related records that need to appear before
    3295             : /// a function summary entry (whether per-module or combined).
    3296         874 : static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
    3297             :                                              FunctionSummary *FS) {
    3298         874 :   if (!FS->type_tests().empty())
    3299          16 :     Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
    3300             : 
    3301        1748 :   SmallVector<uint64_t, 64> Record;
    3302             : 
    3303             :   auto WriteVFuncIdVec = [&](uint64_t Ty,
    3304        1748 :                              ArrayRef<FunctionSummary::VFuncId> VFs) {
    3305        1748 :     if (VFs.empty())
    3306             :       return;
    3307          34 :     Record.clear();
    3308          20 :     for (auto &VF : VFs) {
    3309           8 :       Record.push_back(VF.GUID);
    3310           8 :       Record.push_back(VF.Offset);
    3311             :     }
    3312          12 :     Stream.EmitRecord(Ty, Record);
    3313         874 :   };
    3314             : 
    3315         874 :   WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
    3316             :                   FS->type_test_assume_vcalls());
    3317         874 :   WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
    3318             :                   FS->type_checked_load_vcalls());
    3319             : 
    3320             :   auto WriteConstVCallVec = [&](uint64_t Ty,
    3321        1748 :                                 ArrayRef<FunctionSummary::ConstVCall> VCs) {
    3322        3503 :     for (auto &VC : VCs) {
    3323          35 :       Record.clear();
    3324           7 :       Record.push_back(VC.VFunc.GUID);
    3325           7 :       Record.push_back(VC.VFunc.Offset);
    3326          28 :       Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
    3327          14 :       Stream.EmitRecord(Ty, Record);
    3328             :     }
    3329        2622 :   };
    3330             : 
    3331         874 :   WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
    3332             :                      FS->type_test_assume_const_vcalls());
    3333         874 :   WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
    3334             :                      FS->type_checked_load_const_vcalls());
    3335         874 : }
    3336             : 
    3337             : // Helper to emit a single function summary record.
    3338         484 : void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
    3339             :     SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
    3340             :     unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
    3341             :     const Function &F) {
    3342         484 :   NameVals.push_back(ValueID);
    3343             : 
    3344         484 :   FunctionSummary *FS = cast<FunctionSummary>(Summary);
    3345         484 :   writeFunctionTypeMetadataRecords(Stream, FS);
    3346             : 
    3347         968 :   NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
    3348         484 :   NameVals.push_back(FS->instCount());
    3349         968 :   NameVals.push_back(getEncodedFFlags(FS->fflags()));
    3350         968 :   NameVals.push_back(FS->refs().size());
    3351             : 
    3352        1523 :   for (auto &RI : FS->refs())
    3353         142 :     NameVals.push_back(VE.getValueID(RI.getValue()));
    3354             : 
    3355         968 :   bool HasProfileData = F.getEntryCount().hasValue();
    3356        1230 :   for (auto &ECI : FS->calls()) {
    3357         262 :     NameVals.push_back(getValueId(ECI.first));
    3358         262 :     if (HasProfileData)
    3359          39 :       NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
    3360             :   }
    3361             : 
    3362         484 :   unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
    3363         484 :   unsigned Code =
    3364         484 :       (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
    3365             : 
    3366             :   // Emit the finished record.
    3367         484 :   Stream.EmitRecord(Code, NameVals, FSAbbrev);
    3368         968 :   NameVals.clear();
    3369         484 : }
    3370             : 
    3371             : // Collect the global value references in the given variable's initializer,
    3372             : // and emit them in a summary record.
    3373         121 : void ModuleBitcodeWriterBase::writeModuleLevelReferences(
    3374             :     const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
    3375             :     unsigned FSModRefsAbbrev) {
    3376         363 :   auto VI = Index->getValueInfo(GlobalValue::getGUID(V.getName()));
    3377         235 :   if (!VI || VI.getSummaryList().empty()) {
    3378             :     // Only declarations should not have a summary (a declaration might however
    3379             :     // have a summary if the def was in module level asm).
    3380             :     assert(V.isDeclaration());
    3381          32 :     return;
    3382             :   }
    3383         178 :   auto *Summary = VI.getSummaryList()[0].get();
    3384          89 :   NameVals.push_back(VE.getValueID(&V));
    3385          89 :   GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
    3386         178 :   NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
    3387             : 
    3388         178 :   unsigned SizeBeforeRefs = NameVals.size();
    3389         313 :   for (auto &RI : VS->refs())
    3390          92 :     NameVals.push_back(VE.getValueID(RI.getValue()));
    3391             :   // Sort the refs for determinism output, the vector returned by FS->refs() has
    3392             :   // been initialized from a DenseSet.
    3393         356 :   std::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
    3394             : 
    3395          89 :   Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
    3396             :                     FSModRefsAbbrev);
    3397         178 :   NameVals.clear();
    3398             : }
    3399             : 
    3400             : // Current version for the summary.
    3401             : // This is bumped whenever we introduce changes in the way some record are
    3402             : // interpreted, like flags for instance.
    3403             : static const uint64_t INDEX_VERSION = 4;
    3404             : 
    3405             : /// Emit the per-module summary section alongside the rest of
    3406             : /// the module's bitcode.
    3407         294 : void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
    3408             :   // By default we compile with ThinLTO if the module has a summary, but the
    3409             :   // client can request full LTO with a module flag.
    3410         294 :   bool IsThinLTO = true;
    3411          20 :   if (auto *MD =
    3412         882 :           mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
    3413          20 :     IsThinLTO = MD->getZExtValue();
    3414         294 :   Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
    3415             :                                  : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
    3416             :                        4);
    3417             : 
    3418         588 :   Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
    3419             : 
    3420         882 :   if (Index->begin() == Index->end()) {
    3421          17 :     Stream.ExitBlock();
    3422          17 :     return;
    3423             :   }
    3424             : 
    3425         837 :   for (const auto &GVI : valueIds()) {
    3426          12 :     Stream.EmitRecord(bitc::FS_VALUE_GUID,
    3427          18 :                       ArrayRef<uint64_t>{GVI.second, GVI.first});
    3428             :   }
    3429             : 
    3430             :   // Abbrev for FS_PERMODULE.
    3431         554 :   auto Abbv = std::make_shared<BitCodeAbbrev>();
    3432         831 :   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
    3433         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
    3434         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
    3435         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
    3436         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
    3437         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
    3438             :   // numrefs x valueid, n x (valueid)
    3439         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    3440         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
    3441         831 :   unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
    3442             : 
    3443             :   // Abbrev for FS_PERMODULE_PROFILE.
    3444         831 :   Abbv = std::make_shared<BitCodeAbbrev>();
    3445         831 :   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
    3446         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
    3447         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
    3448         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
    3449         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
    3450         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
    3451             :   // numrefs x valueid, n x (valueid, hotness)
    3452         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    3453         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
    3454         831 :   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
    3455             : 
    3456             :   // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
    3457         831 :   Abbv = std::make_shared<BitCodeAbbrev>();
    3458         831 :   Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
    3459         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
    3460         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
    3461         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));  // valueids
    3462         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
    3463         831 :   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
    3464             : 
    3465             :   // Abbrev for FS_ALIAS.
    3466         831 :   Abbv = std::make_shared<BitCodeAbbrev>();
    3467         831 :   Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
    3468         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
    3469         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
    3470         831 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
    3471         831 :   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
    3472             : 
    3473         554 :   SmallVector<uint64_t, 64> NameVals;
    3474             :   // Iterate over the list of functions instead of the Index to
    3475             :   // ensure the ordering is stable.
    3476        1550 :   for (const Function &F : M) {
    3477             :     // Summary emission does not support anonymous functions, they have to
    3478             :     // renamed using the anonymous function renaming pass.
    3479        1438 :     if (!F.hasName())
    3480           0 :       report_fatal_error("Unexpected anonymous function when writing summary");
    3481             : 
    3482        2157 :     ValueInfo VI = Index->getValueInfo(GlobalValue::getGUID(F.getName()));
    3483        1644 :     if (!VI || VI.getSummaryList().empty()) {
    3484             :       // Only declarations should not have a summary (a declaration might
    3485             :       // however have a summary if the def was in module level asm).
    3486             :       assert(F.isDeclaration());
    3487         235 :       continue;
    3488             :     }
    3489         968 :     auto *Summary = VI.getSummaryList()[0].get();
    3490         484 :     writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
    3491             :                                         FSCallsAbbrev, FSCallsProfileAbbrev, F);
    3492             :   }
    3493             : 
    3494             :   // Capture references from GlobalVariable initializers, which are outside
    3495             :   // of a function scope.
    3496         675 :   for (const GlobalVariable &G : M.globals())
    3497         121 :     writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
    3498             : 
    3499         663 :   for (const GlobalAlias &A : M.aliases()) {
    3500         109 :     auto *Aliasee = A.getBaseObject();
    3501         218 :     if (!Aliasee->hasName())
    3502             :       // Nameless function don't have an entry in the summary, skip it.
    3503           0 :       continue;
    3504         109 :     auto AliasId = VE.getValueID(&A);
    3505         109 :     auto AliaseeId = VE.getValueID(Aliasee);
    3506         109 :     NameVals.push_back(AliasId);
    3507         109 :     auto *Summary = Index->getGlobalValueSummary(A);
    3508         109 :     AliasSummary *AS = cast<AliasSummary>(Summary);
    3509         218 :     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
    3510         109 :     NameVals.push_back(AliaseeId);
    3511         109 :     Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
    3512             :     NameVals.clear();
    3513             :   }
    3514             : 
    3515         277 :   Stream.ExitBlock();
    3516             : }
    3517             : 
    3518             : /// Emit the combined summary section into the combined index file.
    3519         130 : void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
    3520         130 :   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
    3521         260 :   Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
    3522             : 
    3523         895 :   for (const auto &GVI : valueIds()) {
    3524        1010 :     Stream.EmitRecord(bitc::FS_VALUE_GUID,
    3525        1515 :                       ArrayRef<uint64_t>{GVI.second, GVI.first});
    3526             :   }
    3527             : 
    3528             :   // Abbrev for FS_COMBINED.
    3529         260 :   auto Abbv = std::make_shared<BitCodeAbbrev>();
    3530         390 :   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
    3531         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
    3532         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
    3533         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
    3534         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
    3535         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
    3536         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
    3537             :   // numrefs x valueid, n x (valueid)
    3538         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    3539         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
    3540         390 :   unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
    3541             : 
    3542             :   // Abbrev for FS_COMBINED_PROFILE.
    3543         390 :   Abbv = std::make_shared<BitCodeAbbrev>();
    3544         390 :   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
    3545         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
    3546         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
    3547         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
    3548         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // instcount
    3549         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // fflags
    3550         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4));   // numrefs
    3551             :   // numrefs x valueid, n x (valueid, hotness)
    3552         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    3553         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
    3554         390 :   unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
    3555             : 
    3556             :   // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
    3557         390 :   Abbv = std::make_shared<BitCodeAbbrev>();
    3558         390 :   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
    3559         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
    3560         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
    3561         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
    3562         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));    // valueids
    3563         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
    3564         390 :   unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
    3565             : 
    3566             :   // Abbrev for FS_COMBINED_ALIAS.
    3567         390 :   Abbv = std::make_shared<BitCodeAbbrev>();
    3568         390 :   Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
    3569         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
    3570         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // modid
    3571         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // flags
    3572         390 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // valueid
    3573         390 :   unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
    3574             : 
    3575             :   // The aliases are emitted as a post-pass, and will point to the value
    3576             :   // id of the aliasee. Save them in a vector for post-processing.
    3577         260 :   SmallVector<AliasSummary *, 64> Aliases;
    3578             : 
    3579             :   // Save the value id for each summary for alias emission.
    3580         260 :   DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
    3581             : 
    3582         260 :   SmallVector<uint64_t, 64> NameVals;
    3583             : 
    3584             :   // For local linkage, we also emit the original name separately
    3585             :   // immediately after the record.
    3586         548 :   auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
    3587         548 :     if (!GlobalValue::isLocalLinkage(S.linkage()))
    3588             :       return;
    3589         177 :     NameVals.push_back(S.getOriginalName());
    3590         118 :     Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
    3591          59 :     NameVals.clear();
    3592         130 :   };
    3593             : 
    3594         678 :   forEachSummary([&](GVInfo I) {
    3595         548 :     GlobalValueSummary *S = I.second;
    3596             :     assert(S);
    3597             : 
    3598        3073 :     auto ValueId = getValueId(I.first);
    3599             :     assert(ValueId);
    3600        1096 :     SummaryToValueIdMap[S] = *ValueId;
    3601             : 
    3602         548 :     if (auto *AS = dyn_cast<AliasSummary>(S)) {
    3603             :       // Will process aliases as a post-pass because the reader wants all
    3604             :       // global to be loaded first.
    3605         101 :       Aliases.push_back(AS);
    3606         101 :       return;
    3607             :     }
    3608             : 
    3609          57 :     if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
    3610        4109 :       NameVals.push_back(*ValueId);
    3611         171 :       NameVals.push_back(Index.getModuleId(VS->modulePath()));
    3612         114 :       NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
    3613         187 :       for (auto &RI : VS->refs()) {
    3614          47 :         auto RefValueId = getValueId(RI.getGUID());
    3615          16 :         if (!RefValueId)
    3616           1 :           continue;
    3617          30 :         NameVals.push_back(*RefValueId);
    3618             :       }
    3619             : 
    3620             :       // Emit the finished record.
    3621         171 :       Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
    3622          57 :                         FSModRefsAbbrev);
    3623         114 :       NameVals.clear();
    3624         447 :       MaybeEmitOriginalName(*S);
    3625          57 :       return;
    3626             :     }
    3627             : 
    3628         390 :     auto *FS = cast<FunctionSummary>(S);
    3629         390 :     writeFunctionTypeMetadataRecords(Stream, FS);
    3630             : 
    3631         780 :     NameVals.push_back(*ValueId);
    3632        1170 :     NameVals.push_back(Index.getModuleId(FS->modulePath()));
    3633         780 :     NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
    3634         390 :     NameVals.push_back(FS->instCount());
    3635         780 :     NameVals.push_back(getEncodedFFlags(FS->fflags()));
    3636             :     // Fill in below
    3637         390 :     NameVals.push_back(0);
    3638             : 
    3639         390 :     unsigned Count = 0;
    3640        1223 :     for (auto &RI : FS->refs()) {
    3641         151 :       auto RefValueId = getValueId(RI.getGUID());
    3642          53 :       if (!RefValueId)
    3643           8 :         continue;
    3644          90 :       NameVals.push_back(*RefValueId);
    3645          45 :       Count++;
    3646             :     }
    3647         780 :     NameVals[5] = Count;
    3648             : 
    3649         390 :     bool HasProfileData = false;
    3650         977 :     for (auto &EI : FS->calls()) {
    3651         211 :       HasProfileData |= EI.second.Hotness != CalleeInfo::HotnessType::Unknown;
    3652         211 :       if (HasProfileData)
    3653             :         break;
    3654             :     }
    3655             : 
    3656         624 :     for (auto &EI : FS->calls()) {
    3657             :       // If this GUID doesn't have a value id, it doesn't have a function
    3658             :       // summary and we don't need to record any calls to it.
    3659         468 :       GlobalValue::GUID GUID = EI.first.getGUID();
    3660         454 :       auto CallValueId = getValueId(GUID);
    3661         234 :       if (!CallValueId) {
    3662             :         // For SamplePGO, the indirect call targets for local functions will
    3663             :         // have its original name annotated in profile. We try to find the
    3664             :         // corresponding PGOFuncName as the GUID.
    3665          19 :         GUID = Index.getGUIDFromOriginalID(GUID);
    3666           3 :         if (GUID == 0)
    3667          27 :           continue;
    3668           9 :         CallValueId = getValueId(GUID);
    3669           3 :         if (!CallValueId)
    3670           0 :           continue;
    3671             :         // The mapping from OriginalId to GUID may return a GUID
    3672             :         // that corresponds to a static variable. Filter it out here.
    3673             :         // This can happen when 
    3674             :         // 1) There is a call to a library function which does not have
    3675             :         // a CallValidId;
    3676             :         // 2) There is a static variable with the  OriginalGUID identical
    3677             :         // to the GUID of the library function in 1);
    3678             :         // When this happens, the logic for SamplePGO kicks in and
    3679             :         // the static varible in 2) will be found, which needs to be
    3680             :         // filtered out.
    3681           3 :         auto *GVSum = Index.getGlobalValueSummary(GUID, false);
    3682           6 :         if (GVSum &&
    3683           3 :             GVSum->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
    3684           1 :           continue;
    3685             :       }
    3686         440 :       NameVals.push_back(*CallValueId);
    3687         220 :       if (HasProfileData)
    3688          34 :         NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
    3689             :     }
    3690             : 
    3691         390 :     unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
    3692         390 :     unsigned Code =
    3693         390 :         (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
    3694             : 
    3695             :     // Emit the finished record.
    3696         780 :     Stream.EmitRecord(Code, NameVals, FSAbbrev);
    3697         780 :     NameVals.clear();
    3698         390 :     MaybeEmitOriginalName(*S);
    3699             :   });
    3700             : 
    3701         491 :   for (auto *AS : Aliases) {
    3702         202 :     auto AliasValueId = SummaryToValueIdMap[AS];
    3703             :     assert(AliasValueId);
    3704         101 :     NameVals.push_back(AliasValueId);
    3705         202 :     NameVals.push_back(Index.getModuleId(AS->modulePath()));
    3706         202 :     NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
    3707         202 :     auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
    3708             :     assert(AliaseeValueId);
    3709         101 :     NameVals.push_back(AliaseeValueId);
    3710             : 
    3711             :     // Emit the finished record.
    3712         101 :     Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
    3713         101 :     NameVals.clear();
    3714         101 :     MaybeEmitOriginalName(*AS);
    3715             :   }
    3716             : 
    3717         260 :   if (!Index.cfiFunctionDefs().empty()) {
    3718          12 :     for (auto &S : Index.cfiFunctionDefs()) {
    3719           6 :       NameVals.push_back(StrtabBuilder.add(S));
    3720           3 :       NameVals.push_back(S.size());
    3721             :     }
    3722           3 :     Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
    3723             :     NameVals.clear();
    3724             :   }
    3725             : 
    3726         260 :   if (!Index.cfiFunctionDecls().empty()) {
    3727           8 :     for (auto &S : Index.cfiFunctionDecls()) {
    3728           4 :       NameVals.push_back(StrtabBuilder.add(S));
    3729           2 :       NameVals.push_back(S.size());
    3730             :     }
    3731           2 :     Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
    3732             :     NameVals.clear();
    3733             :   }
    3734             : 
    3735         130 :   Stream.ExitBlock();
    3736         130 : }
    3737             : 
    3738             : /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
    3739             : /// current llvm version, and a record for the epoch number.
    3740        3629 : static void writeIdentificationBlock(BitstreamWriter &Stream) {
    3741        3629 :   Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
    3742             : 
    3743             :   // Write the "user readable" string identifying the bitcode producer
    3744        7258 :   auto Abbv = std::make_shared<BitCodeAbbrev>();
    3745       10887 :   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
    3746       10887 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    3747       10887 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
    3748       10887 :   auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
    3749        3629 :   writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
    3750             :                     "LLVM" LLVM_VERSION_STRING, StringAbbrev);
    3751             : 
    3752             :   // Write the epoch version
    3753       10887 :   Abbv = std::make_shared<BitCodeAbbrev>();
    3754       10887 :   Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
    3755       10887 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
    3756       10887 :   auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
    3757       10887 :   SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
    3758        3629 :   Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
    3759        3629 :   Stream.ExitBlock();
    3760        3629 : }
    3761             : 
    3762        3629 : void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
    3763             :   // Emit the module's hash.
    3764             :   // MODULE_CODE_HASH: [5*i32]
    3765        3629 :   if (GenerateHash) {
    3766             :     uint32_t Vals[5];
    3767         300 :     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
    3768         150 :                                     Buffer.size() - BlockStartPos));
    3769          75 :     StringRef Hash = Hasher.result();
    3770         450 :     for (int Pos = 0; Pos < 20; Pos += 4) {
    3771         750 :       Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
    3772             :     }
    3773             : 
    3774             :     // Emit the finished record.
    3775          75 :     Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
    3776             : 
    3777          75 :     if (ModHash)
    3778             :       // Save the written hash value.
    3779          92 :       std::copy(std::begin(Vals), std::end(Vals), std::begin(*ModHash));
    3780             :   }
    3781        3629 : }
    3782             : 
    3783        3629 : void ModuleBitcodeWriter::write() {
    3784        3629 :   writeIdentificationBlock(Stream);
    3785             : 
    3786        3629 :   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
    3787        7258 :   size_t BlockStartPos = Buffer.size();
    3788             : 
    3789        3629 :   writeModuleVersion();
    3790             : 
    3791             :   // Emit blockinfo, which defines the standard abbreviations etc.
    3792        3629 :   writeBlockInfo();
    3793             : 
    3794             :   // Emit information about attribute groups.
    3795        3629 :   writeAttributeGroupTable();
    3796             : 
    3797             :   // Emit information about parameter attributes.
    3798        3629 :   writeAttributeTable();
    3799             : 
    3800             :   // Emit information describing all of the types in the module.
    3801        3629 :   writeTypeTable();
    3802             : 
    3803        3629 :   writeComdats();
    3804             : 
    3805             :   // Emit top-level description of module, including target triple, inline asm,
    3806             :   // descriptors for global variables, and function prototype info.
    3807        3629 :   writeModuleInfo();
    3808             : 
    3809             :   // Emit constants.
    3810        3629 :   writeModuleConstants();
    3811             : 
    3812             :   // Emit metadata kind names.
    3813        3629 :   writeModuleMetadataKinds();
    3814             : 
    3815             :   // Emit metadata.
    3816        3629 :   writeModuleMetadata();
    3817             : 
    3818             :   // Emit module-level use-lists.
    3819        3629 :   if (VE.shouldPreserveUseListOrder())
    3820        2564 :     writeUseListBlock(nullptr);
    3821             : 
    3822        3629 :   writeOperandBundleTags();
    3823        3629 :   writeSyncScopeNames();
    3824             : 
    3825             :   // Emit function bodies.
    3826        7258 :   DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
    3827       10887 :   for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
    3828        9627 :     if (!F->isDeclaration())
    3829        7051 :       writeFunction(*F, FunctionToBitcodeIndex);
    3830             : 
    3831             :   // Need to write after the above call to WriteFunction which populates
    3832             :   // the summary information in the index.
    3833        3629 :   if (Index)
    3834         286 :     writePerModuleGlobalValueSummary();
    3835             : 
    3836        3629 :   writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
    3837             : 
    3838        3629 :   writeModuleHash(BlockStartPos);
    3839             : 
    3840        3629 :   Stream.ExitBlock();
    3841        3629 : }
    3842             : 
    3843             : static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
    3844             :                                uint32_t &Position) {
    3845        3555 :   support::endian::write32le(&Buffer[Position], Value);
    3846        1185 :   Position += 4;
    3847             : }
    3848             : 
    3849             : /// If generating a bc file on darwin, we have to emit a
    3850             : /// header and trailer to make it compatible with the system archiver.  To do
    3851             : /// this we emit the following header, and then emit a trailer that pads the
    3852             : /// file out to be a multiple of 16 bytes.
    3853             : ///
    3854             : /// struct bc_header {
    3855             : ///   uint32_t Magic;         // 0x0B17C0DE
    3856             : ///   uint32_t Version;       // Version, currently always 0.
    3857             : ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
    3858             : ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
    3859             : ///   uint32_t CPUType;       // CPU specifier.
    3860             : ///   ... potentially more later ...
    3861             : /// };
    3862         237 : static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
    3863             :                                          const Triple &TT) {
    3864         237 :   unsigned CPUType = ~0U;
    3865             : 
    3866             :   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
    3867             :   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
    3868             :   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
    3869             :   // specific constants here because they are implicitly part of the Darwin ABI.
    3870             :   enum {
    3871             :     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
    3872             :     DARWIN_CPU_TYPE_X86        = 7,
    3873             :     DARWIN_CPU_TYPE_ARM        = 12,
    3874             :     DARWIN_CPU_TYPE_POWERPC    = 18
    3875             :   };
    3876             : 
    3877         237 :   Triple::ArchType Arch = TT.getArch();
    3878         237 :   if (Arch == Triple::x86_64)
    3879             :     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
    3880          48 :   else if (Arch == Triple::x86)
    3881             :     CPUType = DARWIN_CPU_TYPE_X86;
    3882          15 :   else if (Arch == Triple::ppc)
    3883             :     CPUType = DARWIN_CPU_TYPE_POWERPC;
    3884           8 :   else if (Arch == Triple::ppc64)
    3885             :     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
    3886           8 :   else if (Arch == Triple::arm || Arch == Triple::thumb)
    3887           8 :     CPUType = DARWIN_CPU_TYPE_ARM;
    3888             : 
    3889             :   // Traditional Bitcode starts after header.
    3890             :   assert(Buffer.size() >= BWH_HeaderSize &&
    3891             :          "Expected header size to be reserved");
    3892         237 :   unsigned BCOffset = BWH_HeaderSize;
    3893         474 :   unsigned BCSize = Buffer.size() - BWH_HeaderSize;
    3894             : 
    3895             :   // Write the magic and version.
    3896         237 :   unsigned Position = 0;
    3897         237 :   writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
    3898         237 :   writeInt32ToBuffer(0, Buffer, Position); // Version.
    3899         237 :   writeInt32ToBuffer(BCOffset, Buffer, Position);
    3900         237 :   writeInt32ToBuffer(BCSize, Buffer, Position);
    3901             :   writeInt32ToBuffer(CPUType, Buffer, Position);
    3902             : 
    3903             :   // If the file is not a multiple of 16 bytes, insert dummy padding.
    3904        4122 :   while (Buffer.size() & 15)
    3905        1216 :     Buffer.push_back(0);
    3906         237 : }
    3907             : 
    3908             : /// Helper to write the header common to all bitcode files.
    3909        3772 : static void writeBitcodeHeader(BitstreamWriter &Stream) {
    3910             :   // Emit the file header.
    3911        3772 :   Stream.Emit((unsigned)'B', 8);
    3912        3772 :   Stream.Emit((unsigned)'C', 8);
    3913        3772 :   Stream.Emit(0x0, 4);
    3914        3772 :   Stream.Emit(0xC, 4);
    3915        3772 :   Stream.Emit(0xE, 4);
    3916        3772 :   Stream.Emit(0xD, 4);
    3917        3772 : }
    3918             : 
    3919        3772 : BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
    3920       18860 :     : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
    3921        7544 :   writeBitcodeHeader(*Stream);
    3922        3772 : }
    3923             : 
    3924        7544 : BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
    3925             : 
    3926        5454 : void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
    3927       10908 :   Stream->EnterSubblock(Block, 3);
    3928             : 
    3929       10908 :   auto Abbv = std::make_shared<BitCodeAbbrev>();
    3930       16362 :   Abbv->Add(BitCodeAbbrevOp(Record));
    3931       16362 :   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
    3932       21816 :   auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
    3933             : 
    3934       21816 :   Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
    3935             : 
    3936       10908 :   Stream->ExitBlock();
    3937        5454 : }
    3938             : 
    3939        3613 : void BitcodeWriter::writeSymtab() {
    3940             :   assert(!WroteStrtab && !WroteSymtab);
    3941             : 
    3942             :   // If any module has module-level inline asm, we will require a registered asm
    3943             :   // parser for the target so that we can create an accurate symbol table for
    3944             :   // the module.
    3945       18054 :   for (Module *M : Mods) {
    3946        3631 :     if (M->getModuleInlineAsm().empty())
    3947        3556 :       continue;
    3948             : 
    3949         121 :     std::string Err;
    3950         196 :     const Triple TT(M->getTargetTriple());
    3951          75 :     const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
    3952          75 :     if (!T || !T->hasMCAsmParser())
    3953          29 :       return;
    3954             :   }
    3955             : 
    3956        3584 :   WroteSymtab = true;
    3957        5259 :   SmallVector<char, 0> Symtab;
    3958             :   // The irsymtab::build function may be unable to create a symbol table if the
    3959             :   // module is malformed (e.g. it contains an invalid alias). Writing a symbol
    3960             :   // table is not required for correctness, but we still want to be able to
    3961             :   // write malformed modules to bitcode files, so swallow the error.
    3962       12427 :   if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
    3963        5727 :     consumeError(std::move(E));
    3964        1909 :     return;
    3965             :   }
    3966             : 
    3967        3350 :   writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
    3968        3350 :             {Symtab.data(), Symtab.size()});
    3969             : }
    3970             : 
    3971        3747 : void BitcodeWriter::writeStrtab() {
    3972             :   assert(!WroteStrtab);
    3973             : 
    3974        7494 :   std::vector<char> Strtab;
    3975        3747 :   StrtabBuilder.finalizeInOrder();
    3976        3747 :   Strtab.resize(StrtabBuilder.getSize());
    3977        7494 :   StrtabBuilder.write((uint8_t *)Strtab.data());
    3978             : 
    3979       11241 :   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
    3980        3747 :             {Strtab.data(), Strtab.size()});
    3981             : 
    3982        3747 :   WroteStrtab = true;
    3983        3747 : }
    3984             : 
    3985          32 : void BitcodeWriter::copyStrtab(StringRef Strtab) {
    3986          32 :   writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
    3987          32 :   WroteStrtab = true;
    3988          32 : }
    3989             : 
    3990        3629 : void BitcodeWriter::writeModule(const Module *M,
    3991             :                                 bool ShouldPreserveUseListOrder,
    3992             :                                 const ModuleSummaryIndex *Index,
    3993             :                                 bool GenerateHash, ModuleHash *ModHash) {
    3994             :   assert(!WroteStrtab);
    3995             : 
    3996             :   // The Mods vector is used by irsymtab::build, which requires non-const
    3997             :   // Modules in case it needs to materialize metadata. But the bitcode writer
    3998             :   // requires that the module is materialized, so we can cast to non-const here,
    3999             :   // after checking that it is in fact materialized.
    4000             :   assert(M->isMaterialized());
    4001        7258 :   Mods.push_back(const_cast<Module *>(M));
    4002             : 
    4003        7258 :   ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
    4004             :                                    ShouldPreserveUseListOrder, Index,
    4005       10887 :                                    GenerateHash, ModHash);
    4006        3629 :   ModuleWriter.write();
    4007        3629 : }
    4008             : 
    4009         130 : void BitcodeWriter::writeIndex(
    4010             :     const ModuleSummaryIndex *Index,
    4011             :     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
    4012         260 :   IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
    4013         390 :                                  ModuleToSummariesForIndex);
    4014         130 :   IndexWriter.write();
    4015         130 : }
    4016             : 
    4017             : /// WriteBitcodeToFile - Write the specified module to the specified output
    4018             : /// stream.
    4019        3588 : void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
    4020             :                               bool ShouldPreserveUseListOrder,
    4021             :                               const ModuleSummaryIndex *Index,
    4022             :                               bool GenerateHash, ModuleHash *ModHash) {
    4023        7176 :   SmallVector<char, 0> Buffer;
    4024        3588 :   Buffer.reserve(256*1024);
    4025             : 
    4026             :   // If this is darwin or another generic macho target, reserve space for the
    4027             :   // header.
    4028       10764 :   Triple TT(M->getTargetTriple());
    4029        6704 :   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
    4030         474 :     Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
    4031             : 
    4032        7176 :   BitcodeWriter Writer(Buffer);
    4033        3588 :   Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
    4034             :                      ModHash);
    4035        3588 :   Writer.writeSymtab();
    4036        3588 :   Writer.writeStrtab();
    4037             : 
    4038        6704 :   if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
    4039         237 :     emitDarwinBCHeaderAndTrailer(Buffer, TT);
    4040             : 
    4041             :   // Write the generated bitstream to "Out".
    4042        7176 :   Out.write((char*)&Buffer.front(), Buffer.size());
    4043        3588 : }
    4044             : 
    4045         130 : void IndexBitcodeWriter::write() {
    4046         130 :   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
    4047             : 
    4048         130 :   writeModuleVersion();
    4049             : 
    4050             :   // Write the module paths in the combined index.
    4051         130 :   writeModStrings();
    4052             : 
    4053             :   // Write the summary combined index records.
    4054         130 :   writeCombinedGlobalValueSummary();
    4055             : 
    4056         130 :   Stream.ExitBlock();
    4057         130 : }
    4058             : 
    4059             : // Write the specified module summary index to the given raw output stream,
    4060             : // where it will be written in a new bitcode block. This is used when
    4061             : // writing the combined index file for ThinLTO. When writing a subset of the
    4062             : // index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
    4063         130 : void llvm::WriteIndexToFile(
    4064             :     const ModuleSummaryIndex &Index, raw_ostream &Out,
    4065             :     const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
    4066         260 :   SmallVector<char, 0> Buffer;
    4067         130 :   Buffer.reserve(256 * 1024);
    4068             : 
    4069         260 :   BitcodeWriter Writer(Buffer);
    4070         130 :   Writer.writeIndex(&Index, ModuleToSummariesForIndex);
    4071         130 :   Writer.writeStrtab();
    4072             : 
    4073         260 :   Out.write((char *)&Buffer.front(), Buffer.size());
    4074         130 : }
    4075             : 
    4076             : namespace {
    4077             : 
    4078             : /// Class to manage the bitcode writing for a thin link bitcode file.
    4079          16 : class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
    4080             :   /// ModHash is for use in ThinLTO incremental build, generated while writing
    4081             :   /// the module bitcode file.
    4082             :   const ModuleHash *ModHash;
    4083             : 
    4084             : public:
    4085             :   ThinLinkBitcodeWriter(const Module *M, StringTableBuilder &StrtabBuilder,
    4086             :                         BitstreamWriter &Stream,
    4087             :                         const ModuleSummaryIndex &Index,
    4088             :                         const ModuleHash &ModHash)
    4089           8 :       : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
    4090             :                                 /*ShouldPreserveUseListOrder=*/false, &Index),
    4091           8 :         ModHash(&ModHash) {}
    4092             : 
    4093             :   void write();
    4094             : 
    4095             : private:
    4096             :   void writeSimplifiedModuleInfo();
    4097             : };
    4098             : 
    4099             : } // end anonymous namespace
    4100             : 
    4101             : // This function writes a simpilified module info for thin link bitcode file.
    4102             : // It only contains the source file name along with the name(the offset and
    4103             : // size in strtab) and linkage for global values. For the global value info
    4104             : // entry, in order to keep linkage at offset 5, there are three zeros used
    4105             : // as padding.
    4106           8 : void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
    4107          16 :   SmallVector<unsigned, 64> Vals;
    4108             :   // Emit the module's source file name.
    4109             :   {
    4110          24 :     StringEncoding Bits = getStringEncoding(M.getSourceFileName());
    4111           8 :     BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
    4112           8 :     if (Bits == SE_Char6)
    4113           0 :       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
    4114           8 :     else if (Bits == SE_Fixed7)
    4115           8 :       AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
    4116             : 
    4117             :     // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
    4118          16 :     auto Abbv = std::make_shared<BitCodeAbbrev>();
    4119          24 :     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
    4120          24 :     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    4121          16 :     Abbv->Add(AbbrevOpToUse);
    4122          24 :     unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
    4123             : 
    4124         784 :     for (const auto P : M.getSourceFileName())
    4125         752 :       Vals.push_back((unsigned char)P);
    4126             : 
    4127           8 :     Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
    4128           8 :     Vals.clear();
    4129             :   }
    4130             : 
    4131             :   // Emit the global variable information.
    4132          19 :   for (const GlobalVariable &GV : M.globals()) {
    4133             :     // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
    4134           3 :     Vals.push_back(StrtabBuilder.add(GV.getName()));
    4135           6 :     Vals.push_back(GV.getName().size());
    4136           3 :     Vals.push_back(0);
    4137           3 :     Vals.push_back(0);
    4138           3 :     Vals.push_back(0);
    4139           6 :     Vals.push_back(getEncodedLinkage(GV));
    4140             : 
    4141           3 :     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
    4142           3 :     Vals.clear();
    4143             :   }
    4144             : 
    4145             :   // Emit the function proto information.
    4146          33 :   for (const Function &F : M) {
    4147             :     // FUNCTION:  [strtab offset, strtab size, 0, 0, 0, linkage]
    4148           9 :     Vals.push_back(StrtabBuilder.add(F.getName()));
    4149          18 :     Vals.push_back(F.getName().size());
    4150           9 :     Vals.push_back(0);
    4151           9 :     Vals.push_back(0);
    4152           9 :     Vals.push_back(0);
    4153          18 :     Vals.push_back(getEncodedLinkage(F));
    4154             : 
    4155           9 :     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
    4156           9 :     Vals.clear();
    4157             :   }
    4158             : 
    4159             :   // Emit the alias information.
    4160          16 :   for (const GlobalAlias &A : M.aliases()) {
    4161             :     // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
    4162           0 :     Vals.push_back(StrtabBuilder.add(A.getName()));
    4163           0 :     Vals.push_back(A.getName().size());
    4164           0 :     Vals.push_back(0);
    4165           0 :     Vals.push_back(0);
    4166           0 :     Vals.push_back(0);
    4167           0 :     Vals.push_back(getEncodedLinkage(A));
    4168             : 
    4169           0 :     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
    4170           0 :     Vals.clear();
    4171             :   }
    4172             : 
    4173             :   // Emit the ifunc information.
    4174          16 :   for (const GlobalIFunc &I : M.ifuncs()) {
    4175             :     // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
    4176           0 :     Vals.push_back(StrtabBuilder.add(I.getName()));
    4177           0 :     Vals.push_back(I.getName().size());
    4178           0 :     Vals.push_back(0);
    4179           0 :     Vals.push_back(0);
    4180           0 :     Vals.push_back(0);
    4181           0 :     Vals.push_back(getEncodedLinkage(I));
    4182             : 
    4183           0 :     Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
    4184           0 :     Vals.clear();
    4185             :   }
    4186           8 : }
    4187             : 
    4188           8 : void ThinLinkBitcodeWriter::write() {
    4189           8 :   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
    4190             : 
    4191           8 :   writeModuleVersion();
    4192             : 
    4193           8 :   writeSimplifiedModuleInfo();
    4194             : 
    4195           8 :   writePerModuleGlobalValueSummary();
    4196             : 
    4197             :   // Write module hash.
    4198          16 :   Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
    4199             : 
    4200           8 :   Stream.ExitBlock();
    4201           8 : }
    4202             : 
    4203           8 : void BitcodeWriter::writeThinLinkBitcode(const Module *M,
    4204             :                                          const ModuleSummaryIndex &Index,
    4205             :                                          const ModuleHash &ModHash) {
    4206             :   assert(!WroteStrtab);
    4207             : 
    4208             :   // The Mods vector is used by irsymtab::build, which requires non-const
    4209             :   // Modules in case it needs to materialize metadata. But the bitcode writer
    4210             :   // requires that the module is materialized, so we can cast to non-const here,
    4211             :   // after checking that it is in fact materialized.
    4212             :   assert(M->isMaterialized());
    4213          16 :   Mods.push_back(const_cast<Module *>(M));
    4214             : 
    4215          16 :   ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
    4216          24 :                                        ModHash);
    4217           8 :   ThinLinkWriter.write();
    4218           8 : }
    4219             : 
    4220             : // Write the specified thin link bitcode file to the given raw output stream,
    4221             : // where it will be written in a new bitcode block. This is used when
    4222             : // writing the per-module index file for ThinLTO.
    4223           7 : void llvm::WriteThinLinkBitcodeToFile(const Module *M, raw_ostream &Out,
    4224             :                                       const ModuleSummaryIndex &Index,
    4225             :                                       const ModuleHash &ModHash) {
    4226          14 :   SmallVector<char, 0> Buffer;
    4227           7 :   Buffer.reserve(256 * 1024);
    4228             : 
    4229          14 :   BitcodeWriter Writer(Buffer);
    4230           7 :   Writer.writeThinLinkBitcode(M, Index, ModHash);
    4231           7 :   Writer.writeSymtab();
    4232           7 :   Writer.writeStrtab();
    4233             : 
    4234          14 :   Out.write((char *)&Buffer.front(), Buffer.size());
    4235      216925 : }

Generated by: LCOV version 1.13