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