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