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