blob: 06eb0f76254ab2a71987fb2eb03eeee09f6a7b4b [file] [log] [blame]
Eugene Zelenko975293f2017-09-07 23:28:24 +00001//===- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ------------------===//
Chris Lattnerc1d10d62007-04-22 06:24:45 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerc1d10d62007-04-22 06:24:45 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Bitcode writer implementation.
11//
12//===----------------------------------------------------------------------===//
13
Teresa Johnsonad176792016-11-11 05:34:58 +000014#include "llvm/Bitcode/BitcodeWriter.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "ValueEnumerator.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000016#include "llvm/ADT/APFloat.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/None.h"
21#include "llvm/ADT/Optional.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/StringMap.h"
26#include "llvm/ADT/StringRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/ADT/Triple.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000028#include "llvm/Bitcode/BitCodes.h"
Chris Lattnerc1d10d62007-04-22 06:24:45 +000029#include "llvm/Bitcode/BitstreamWriter.h"
Chris Lattner362b4a12007-04-23 01:01:37 +000030#include "llvm/Bitcode/LLVMBitCodes.h"
Nico Weber432a3882018-04-30 14:59:11 +000031#include "llvm/Config/llvm-config.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000032#include "llvm/IR/Attributes.h"
33#include "llvm/IR/BasicBlock.h"
Sanjoy Dasb513a9f2015-09-24 23:34:52 +000034#include "llvm/IR/CallSite.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000035#include "llvm/IR/Comdat.h"
36#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000038#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000039#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000041#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"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/InlineAsm.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000048#include "llvm/IR/InstrTypes.h"
49#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000050#include "llvm/IR/Instructions.h"
Teresa Johnson76a1c1d2016-03-11 18:52:24 +000051#include "llvm/IR/LLVMContext.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000052#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/Module.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000054#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/Operator.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000056#include "llvm/IR/Type.h"
Duncan P. N. Exon Smith6b6fdc92014-07-25 14:49:26 +000057#include "llvm/IR/UseListOrder.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000058#include "llvm/IR/Value.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000059#include "llvm/IR/ValueSymbolTable.h"
Peter Collingbournea0f371a2017-04-17 17:51:36 +000060#include "llvm/MC/StringTableBuilder.h"
Peter Collingbourne92648c22017-06-27 23:50:11 +000061#include "llvm/Object/IRSymtab.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000062#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"
Torok Edwin56d06592009-07-11 20:10:48 +000067#include "llvm/Support/ErrorHandling.h"
Chris Lattnerc1d10d62007-04-22 06:24:45 +000068#include "llvm/Support/MathExtras.h"
Mehdi Aminid7ad2212016-04-01 05:33:11 +000069#include "llvm/Support/SHA1.h"
Peter Collingbourne92648c22017-06-27 23:50:11 +000070#include "llvm/Support/TargetRegistry.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000071#include "llvm/Support/raw_ostream.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000072#include <algorithm>
73#include <cassert>
74#include <cstddef>
75#include <cstdint>
76#include <iterator>
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000077#include <map>
Eugene Zelenko975293f2017-09-07 23:28:24 +000078#include <memory>
79#include <string>
80#include <utility>
81#include <vector>
82
Chris Lattnerc1d10d62007-04-22 06:24:45 +000083using namespace llvm;
84
Eugene Zelenko975293f2017-09-07 23:28:24 +000085static cl::opt<unsigned>
Mehdi Aminie98f9252016-12-28 22:30:28 +000086 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"));
Eugene Zelenko975293f2017-09-07 23:28:24 +000089
Easwaran Ramanc73cec82018-01-25 19:27:17 +000090cl::opt<bool> WriteRelBFToSummary(
91 "write-relbf-to-summary", cl::Hidden, cl::init(false),
92 cl::desc("Write relative block frequency to function summary "));
Teresa Johnsondb83ace2018-03-31 00:18:08 +000093
94extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold;
95
Eugene Zelenko975293f2017-09-07 23:28:24 +000096namespace {
97
Chris Lattner4d925982007-05-04 20:52:02 +000098/// These are manifest constants used by the bitcode writer. They do not need to
99/// be kept in sync with the reader, but need to be consistent within this file.
100enum {
Chris Lattner4d925982007-05-04 20:52:02 +0000101 // VALUE_SYMTAB_BLOCK abbrev id's.
102 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
Chris Lattnerfd1ad102007-05-04 20:58:35 +0000103 VST_ENTRY_7_ABBREV,
Chris Lattnere760d6f2007-05-05 01:26:50 +0000104 VST_ENTRY_6_ABBREV,
Chris Lattnerda5e5d22007-05-05 07:36:14 +0000105 VST_BBENTRY_6_ABBREV,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000106
Chris Lattnerda5e5d22007-05-05 07:36:14 +0000107 // CONSTANTS_BLOCK abbrev id's.
108 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
109 CONSTANTS_INTEGER_ABBREV,
110 CONSTANTS_CE_CAST_Abbrev,
Chris Lattnerb80751d2007-05-05 07:44:49 +0000111 CONSTANTS_NULL_Abbrev,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000112
Chris Lattnerb80751d2007-05-05 07:44:49 +0000113 // FUNCTION_BLOCK abbrev id's.
Chris Lattnercc6d4c92007-05-06 01:28:01 +0000114 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
Cameron McInallycbde0d92018-11-13 18:15:47 +0000115 FUNCTION_INST_UNOP_ABBREV,
116 FUNCTION_INST_UNOP_FLAGS_ABBREV,
Chris Lattnerc67e6d92007-05-06 02:38:57 +0000117 FUNCTION_INST_BINOP_ABBREV,
Dan Gohman0ebd6962009-07-20 21:19:07 +0000118 FUNCTION_INST_BINOP_FLAGS_ABBREV,
Chris Lattnerc67e6d92007-05-06 02:38:57 +0000119 FUNCTION_INST_CAST_ABBREV,
Chris Lattnercc6d4c92007-05-06 01:28:01 +0000120 FUNCTION_INST_RET_VOID_ABBREV,
121 FUNCTION_INST_RET_VAL_ABBREV,
David Blaikieb5b5efd2015-02-25 01:08:52 +0000122 FUNCTION_INST_UNREACHABLE_ABBREV,
123 FUNCTION_INST_GEP_ABBREV,
Chris Lattner4d925982007-05-04 20:52:02 +0000124};
125
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000126/// Abstract class to manage the bitcode writing, subclassed for each bitcode
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000127/// file type.
128class BitcodeWriterBase {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000129protected:
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000130 /// The stream created and owned by the client.
131 BitstreamWriter &Stream;
Teresa Johnson37687f32016-04-23 04:30:47 +0000132
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000133 StringTableBuilder &StrtabBuilder;
134
Teresa Johnson37687f32016-04-23 04:30:47 +0000135public:
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000136 /// Constructs a BitcodeWriterBase object that writes to the provided
137 /// \p Stream.
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000138 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
139 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
Teresa Johnson37687f32016-04-23 04:30:47 +0000140
141protected:
Teresa Johnson37687f32016-04-23 04:30:47 +0000142 void writeBitcodeHeader();
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000143 void writeModuleVersion();
Teresa Johnson37687f32016-04-23 04:30:47 +0000144};
145
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000146void BitcodeWriterBase::writeModuleVersion() {
147 // VERSION: [version#]
148 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
149}
150
Haojie Wang1dec57d2017-07-21 17:25:20 +0000151/// Base class to manage the module bitcode writing, currently subclassed for
152/// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
153class ModuleBitcodeWriterBase : public BitcodeWriterBase {
154protected:
Teresa Johnson37687f32016-04-23 04:30:47 +0000155 /// The Module to write to bitcode.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000156 const Module &M;
Teresa Johnson37687f32016-04-23 04:30:47 +0000157
158 /// Enumerates ids for all values in the module.
159 ValueEnumerator VE;
160
161 /// Optional per-module index to write for ThinLTO.
162 const ModuleSummaryIndex *Index;
163
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000164 /// Map that holds the correspondence between GUIDs in the summary index,
165 /// that came from indirect call profiles, and a value id generated by this
166 /// class to use in the VST and summary block records.
167 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
168
169 /// Tracks the last value id recorded in the GUIDToValueMap.
170 unsigned GlobalValueId;
171
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000172 /// Saves the offset of the VSTOffset record that must eventually be
173 /// backpatched with the offset of the actual VST.
174 uint64_t VSTOffsetPlaceholder = 0;
175
Teresa Johnson37687f32016-04-23 04:30:47 +0000176public:
Haojie Wang1dec57d2017-07-21 17:25:20 +0000177 /// Constructs a ModuleBitcodeWriterBase object for the given Module,
Teresa Johnson37687f32016-04-23 04:30:47 +0000178 /// writing to the provided \p Buffer.
Rafael Espindola6a86e252018-02-14 19:11:32 +0000179 ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
Haojie Wang1dec57d2017-07-21 17:25:20 +0000180 BitstreamWriter &Stream,
181 bool ShouldPreserveUseListOrder,
182 const ModuleSummaryIndex *Index)
Rafael Espindola6a86e252018-02-14 19:11:32 +0000183 : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
184 VE(M, ShouldPreserveUseListOrder), Index(Index) {
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000185 // Assign ValueIds to any callee values in the index that came from
186 // indirect call profiles and were recorded as a GUID not a Value*
187 // (which would have been assigned an ID by the ValueEnumerator).
188 // The starting ValueId is just after the number of values in the
189 // ValueEnumerator, so that they can be emitted in the VST.
190 GlobalValueId = VE.getValues().size();
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000191 if (!Index)
192 return;
193 for (const auto &GUIDSummaryLists : *Index)
194 // Examine all summaries for this GUID.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000195 for (auto &Summary : GUIDSummaryLists.second.SummaryList)
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000196 if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
197 // For each call in the function summary, see if the call
198 // is to a GUID (which means it is for an indirect call,
199 // otherwise we would have a Value for it). If so, synthesize
200 // a value id.
201 for (auto &CallEdge : FS->calls())
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000202 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000203 assignValueId(CallEdge.first.getGUID());
Teresa Johnson37687f32016-04-23 04:30:47 +0000204 }
205
Haojie Wang1dec57d2017-07-21 17:25:20 +0000206protected:
207 void writePerModuleGlobalValueSummary();
208
209private:
210 void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
211 GlobalValueSummary *Summary,
212 unsigned ValueID,
213 unsigned FSCallsAbbrev,
214 unsigned FSCallsProfileAbbrev,
215 const Function &F);
216 void writeModuleLevelReferences(const GlobalVariable &V,
217 SmallVector<uint64_t, 64> &NameVals,
218 unsigned FSModRefsAbbrev);
219
220 void assignValueId(GlobalValue::GUID ValGUID) {
221 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
222 }
Eugene Zelenko975293f2017-09-07 23:28:24 +0000223
Haojie Wang1dec57d2017-07-21 17:25:20 +0000224 unsigned getValueId(GlobalValue::GUID ValGUID) {
225 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
226 // Expect that any GUID value had a value Id assigned by an
227 // earlier call to assignValueId.
228 assert(VMI != GUIDToValueIdMap.end() &&
229 "GUID does not have assigned value Id");
230 return VMI->second;
231 }
Eugene Zelenko975293f2017-09-07 23:28:24 +0000232
Haojie Wang1dec57d2017-07-21 17:25:20 +0000233 // Helper to get the valueId for the type of value recorded in VI.
234 unsigned getValueId(ValueInfo VI) {
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000235 if (!VI.haveGVs() || !VI.getValue())
Haojie Wang1dec57d2017-07-21 17:25:20 +0000236 return getValueId(VI.getGUID());
237 return VE.getValueID(VI.getValue());
238 }
Eugene Zelenko975293f2017-09-07 23:28:24 +0000239
Haojie Wang1dec57d2017-07-21 17:25:20 +0000240 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
241};
242
243/// Class to manage the bitcode writing for a module.
244class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
245 /// Pointer to the buffer allocated by caller for bitcode writing.
246 const SmallVectorImpl<char> &Buffer;
247
248 /// True if a module hash record should be written.
249 bool GenerateHash;
250
251 /// If non-null, when GenerateHash is true, the resulting hash is written
252 /// into ModHash.
253 ModuleHash *ModHash;
254
255 SHA1 Hasher;
256
257 /// The start bit of the identification block.
258 uint64_t BitcodeStartBit;
259
260public:
261 /// Constructs a ModuleBitcodeWriter object for the given Module,
262 /// writing to the provided \p Buffer.
Rafael Espindola6a86e252018-02-14 19:11:32 +0000263 ModuleBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer,
Haojie Wang1dec57d2017-07-21 17:25:20 +0000264 StringTableBuilder &StrtabBuilder,
265 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
266 const ModuleSummaryIndex *Index, bool GenerateHash,
267 ModuleHash *ModHash = nullptr)
268 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
269 ShouldPreserveUseListOrder, Index),
270 Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash),
271 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
272
Teresa Johnson37687f32016-04-23 04:30:47 +0000273 /// Emit the current module to the bitstream.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000274 void write();
Teresa Johnson37687f32016-04-23 04:30:47 +0000275
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000276private:
Teresa Johnson37687f32016-04-23 04:30:47 +0000277 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
278
Peter Collingbournec8556152017-07-06 17:56:01 +0000279 size_t addToStrtab(StringRef Str);
280
Teresa Johnson37687f32016-04-23 04:30:47 +0000281 void writeAttributeGroupTable();
282 void writeAttributeTable();
283 void writeTypeTable();
284 void writeComdats();
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000285 void writeValueSymbolTableForwardDecl();
Teresa Johnson37687f32016-04-23 04:30:47 +0000286 void writeModuleInfo();
287 void writeValueAsMetadata(const ValueAsMetadata *MD,
288 SmallVectorImpl<uint64_t> &Record);
289 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
290 unsigned Abbrev);
291 unsigned createDILocationAbbrev();
292 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
293 unsigned &Abbrev);
294 unsigned createGenericDINodeAbbrev();
295 void writeGenericDINode(const GenericDINode *N,
296 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
297 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
298 unsigned Abbrev);
299 void writeDIEnumerator(const DIEnumerator *N,
300 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
301 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
302 unsigned Abbrev);
303 void writeDIDerivedType(const DIDerivedType *N,
304 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
305 void writeDICompositeType(const DICompositeType *N,
306 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
307 void writeDISubroutineType(const DISubroutineType *N,
308 SmallVectorImpl<uint64_t> &Record,
309 unsigned Abbrev);
310 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
311 unsigned Abbrev);
312 void writeDICompileUnit(const DICompileUnit *N,
313 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
314 void writeDISubprogram(const DISubprogram *N,
315 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
316 void writeDILexicalBlock(const DILexicalBlock *N,
317 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
318 void writeDILexicalBlockFile(const DILexicalBlockFile *N,
319 SmallVectorImpl<uint64_t> &Record,
320 unsigned Abbrev);
321 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
322 unsigned Abbrev);
323 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
324 unsigned Abbrev);
325 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
326 unsigned Abbrev);
327 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
328 unsigned Abbrev);
329 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
330 SmallVectorImpl<uint64_t> &Record,
331 unsigned Abbrev);
332 void writeDITemplateValueParameter(const DITemplateValueParameter *N,
333 SmallVectorImpl<uint64_t> &Record,
334 unsigned Abbrev);
335 void writeDIGlobalVariable(const DIGlobalVariable *N,
336 SmallVectorImpl<uint64_t> &Record,
337 unsigned Abbrev);
338 void writeDILocalVariable(const DILocalVariable *N,
339 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
Shiva Chen2c864552018-05-09 02:40:45 +0000340 void writeDILabel(const DILabel *N,
341 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
Teresa Johnson37687f32016-04-23 04:30:47 +0000342 void writeDIExpression(const DIExpression *N,
343 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000344 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
345 SmallVectorImpl<uint64_t> &Record,
346 unsigned Abbrev);
Teresa Johnson37687f32016-04-23 04:30:47 +0000347 void writeDIObjCProperty(const DIObjCProperty *N,
348 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
349 void writeDIImportedEntity(const DIImportedEntity *N,
350 SmallVectorImpl<uint64_t> &Record,
351 unsigned Abbrev);
352 unsigned createNamedMetadataAbbrev();
353 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
354 unsigned createMetadataStringsAbbrev();
355 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
356 SmallVectorImpl<uint64_t> &Record);
357 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
Mehdi Aminie98f9252016-12-28 22:30:28 +0000358 SmallVectorImpl<uint64_t> &Record,
359 std::vector<unsigned> *MDAbbrevs = nullptr,
360 std::vector<uint64_t> *IndexPos = nullptr);
Teresa Johnson37687f32016-04-23 04:30:47 +0000361 void writeModuleMetadata();
362 void writeFunctionMetadata(const Function &F);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000363 void writeFunctionMetadataAttachment(const Function &F);
364 void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
365 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
366 const GlobalObject &GO);
Peter Collingbourne21521892016-06-21 23:42:48 +0000367 void writeModuleMetadataKinds();
Teresa Johnson37687f32016-04-23 04:30:47 +0000368 void writeOperandBundleTags();
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000369 void writeSyncScopeNames();
Teresa Johnson37687f32016-04-23 04:30:47 +0000370 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
371 void writeModuleConstants();
372 bool pushValueAndType(const Value *V, unsigned InstID,
373 SmallVectorImpl<unsigned> &Vals);
374 void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
375 void pushValue(const Value *V, unsigned InstID,
376 SmallVectorImpl<unsigned> &Vals);
377 void pushValueSigned(const Value *V, unsigned InstID,
378 SmallVectorImpl<uint64_t> &Vals);
379 void writeInstruction(const Instruction &I, unsigned InstID,
380 SmallVectorImpl<unsigned> &Vals);
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000381 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
382 void writeGlobalValueSymbolTable(
383 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
Teresa Johnson37687f32016-04-23 04:30:47 +0000384 void writeUseList(UseListOrder &&Order);
385 void writeUseListBlock(const Function *F);
386 void
387 writeFunction(const Function &F,
388 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
389 void writeBlockInfo();
Teresa Johnson37687f32016-04-23 04:30:47 +0000390 void writeModuleHash(size_t BlockStartPos);
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000391
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000392 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
393 return unsigned(SSID);
394 }
Teresa Johnson37687f32016-04-23 04:30:47 +0000395};
396
397/// Class to manage the bitcode writing for a combined index.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000398class IndexBitcodeWriter : public BitcodeWriterBase {
Teresa Johnson37687f32016-04-23 04:30:47 +0000399 /// The combined index to write to bitcode.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000400 const ModuleSummaryIndex &Index;
Teresa Johnson37687f32016-04-23 04:30:47 +0000401
Teresa Johnson84174c32016-05-10 13:48:23 +0000402 /// When writing a subset of the index for distributed backends, client
403 /// provides a map of modules to the corresponding GUIDs/summaries to write.
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +0000404 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
Teresa Johnson84174c32016-05-10 13:48:23 +0000405
Teresa Johnson37687f32016-04-23 04:30:47 +0000406 /// Map that holds the correspondence between the GUID used in the combined
407 /// index and a value id generated by this class to use in references.
408 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
409
410 /// Tracks the last value id recorded in the GUIDToValueMap.
411 unsigned GlobalValueId = 0;
412
413public:
414 /// Constructs a IndexBitcodeWriter object for the given combined index,
Teresa Johnson84174c32016-05-10 13:48:23 +0000415 /// writing to the provided \p Buffer. When writing a subset of the index
416 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000417 IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
418 const ModuleSummaryIndex &Index,
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +0000419 const std::map<std::string, GVSummaryMapTy>
Teresa Johnson84174c32016-05-10 13:48:23 +0000420 *ModuleToSummariesForIndex = nullptr)
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000421 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
Teresa Johnson84174c32016-05-10 13:48:23 +0000422 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
423 // Assign unique value ids to all summaries to be written, for use
Teresa Johnson37687f32016-04-23 04:30:47 +0000424 // in writing out the call graph edges. Save the mapping from GUID
425 // to the new global value id to use when writing those edges, which
426 // are currently saved in the index in terms of GUID.
Teresa Johnson81bbf742017-12-16 00:18:12 +0000427 forEachSummary([&](GVInfo I, bool) {
Teresa Johnson84174c32016-05-10 13:48:23 +0000428 GUIDToValueIdMap[I.first] = ++GlobalValueId;
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000429 });
Teresa Johnson37687f32016-04-23 04:30:47 +0000430 }
431
Teresa Johnson84174c32016-05-10 13:48:23 +0000432 /// The below iterator returns the GUID and associated summary.
Eugene Zelenko975293f2017-09-07 23:28:24 +0000433 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
Teresa Johnson84174c32016-05-10 13:48:23 +0000434
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000435 /// Calls the callback for each value GUID and summary to be written to
436 /// bitcode. This hides the details of whether they are being pulled from the
437 /// entire index or just those in a provided ModuleToSummariesForIndex map.
David Blaikie358c0122017-06-02 18:25:29 +0000438 template<typename Functor>
439 void forEachSummary(Functor Callback) {
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000440 if (ModuleToSummariesForIndex) {
441 for (auto &M : *ModuleToSummariesForIndex)
Teresa Johnson81bbf742017-12-16 00:18:12 +0000442 for (auto &Summary : M.second) {
443 Callback(Summary, false);
444 // Ensure aliasee is handled, e.g. for assigning a valueId,
445 // even if we are not importing the aliasee directly (the
446 // imported alias will contain a copy of aliasee).
447 if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
448 Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
449 }
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000450 } else {
451 for (auto &Summaries : Index)
Peter Collingbourne9667b912017-05-04 18:03:25 +0000452 for (auto &Summary : Summaries.second.SummaryList)
Teresa Johnson81bbf742017-12-16 00:18:12 +0000453 Callback({Summaries.first, Summary.get()}, false);
Teresa Johnson84174c32016-05-10 13:48:23 +0000454 }
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000455 }
Teresa Johnson84174c32016-05-10 13:48:23 +0000456
Teresa Johnson7a27b132017-06-02 01:56:02 +0000457 /// Calls the callback for each entry in the modulePaths StringMap that
458 /// should be written to the module path string table. This hides the details
459 /// of whether they are being pulled from the entire index or just those in a
460 /// provided ModuleToSummariesForIndex map.
David Blaikieb6b42e02017-06-02 17:24:26 +0000461 template <typename Functor> void forEachModule(Functor Callback) {
Teresa Johnson7a27b132017-06-02 01:56:02 +0000462 if (ModuleToSummariesForIndex) {
463 for (const auto &M : *ModuleToSummariesForIndex) {
464 const auto &MPI = Index.modulePaths().find(M.first);
465 if (MPI == Index.modulePaths().end()) {
466 // This should only happen if the bitcode file was empty, in which
467 // case we shouldn't be importing (the ModuleToSummariesForIndex
468 // would only include the module we are writing and index for).
469 assert(ModuleToSummariesForIndex->size() == 1);
470 continue;
471 }
472 Callback(*MPI);
473 }
474 } else {
475 for (const auto &MPSE : Index.modulePaths())
476 Callback(MPSE);
477 }
478 }
479
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000480 /// Main entry point for writing a combined index to bitcode.
481 void write();
Teresa Johnson37687f32016-04-23 04:30:47 +0000482
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000483private:
Teresa Johnson37687f32016-04-23 04:30:47 +0000484 void writeModStrings();
Teresa Johnson37687f32016-04-23 04:30:47 +0000485 void writeCombinedGlobalValueSummary();
486
Teresa Johnsona6a3fb52017-05-31 18:58:11 +0000487 Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000488 auto VMI = GUIDToValueIdMap.find(ValGUID);
Teresa Johnsona6a3fb52017-05-31 18:58:11 +0000489 if (VMI == GUIDToValueIdMap.end())
490 return None;
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000491 return VMI->second;
Teresa Johnson37687f32016-04-23 04:30:47 +0000492 }
Eugene Zelenko975293f2017-09-07 23:28:24 +0000493
Teresa Johnson37687f32016-04-23 04:30:47 +0000494 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
495};
Eugene Zelenko975293f2017-09-07 23:28:24 +0000496
Benjamin Kramera65b6102016-05-15 15:18:11 +0000497} // end anonymous namespace
Teresa Johnson37687f32016-04-23 04:30:47 +0000498
499static unsigned getEncodedCastOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000500 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000501 default: llvm_unreachable("Unknown cast instruction!");
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000502 case Instruction::Trunc : return bitc::CAST_TRUNC;
503 case Instruction::ZExt : return bitc::CAST_ZEXT;
504 case Instruction::SExt : return bitc::CAST_SEXT;
505 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
506 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
507 case Instruction::UIToFP : return bitc::CAST_UITOFP;
508 case Instruction::SIToFP : return bitc::CAST_SITOFP;
509 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
510 case Instruction::FPExt : return bitc::CAST_FPEXT;
511 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
512 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
513 case Instruction::BitCast : return bitc::CAST_BITCAST;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000514 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000515 }
516}
517
Cameron McInallycbde0d92018-11-13 18:15:47 +0000518static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
519 switch (Opcode) {
520 default: llvm_unreachable("Unknown binary instruction!");
521 case Instruction::FNeg: return bitc::UNOP_NEG;
522 }
523}
524
Teresa Johnson37687f32016-04-23 04:30:47 +0000525static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000526 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000527 default: llvm_unreachable("Unknown binary instruction!");
Dan Gohmana5b96452009-06-04 22:49:04 +0000528 case Instruction::Add:
529 case Instruction::FAdd: return bitc::BINOP_ADD;
530 case Instruction::Sub:
531 case Instruction::FSub: return bitc::BINOP_SUB;
532 case Instruction::Mul:
533 case Instruction::FMul: return bitc::BINOP_MUL;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000534 case Instruction::UDiv: return bitc::BINOP_UDIV;
535 case Instruction::FDiv:
536 case Instruction::SDiv: return bitc::BINOP_SDIV;
537 case Instruction::URem: return bitc::BINOP_UREM;
538 case Instruction::FRem:
539 case Instruction::SRem: return bitc::BINOP_SREM;
540 case Instruction::Shl: return bitc::BINOP_SHL;
541 case Instruction::LShr: return bitc::BINOP_LSHR;
542 case Instruction::AShr: return bitc::BINOP_ASHR;
543 case Instruction::And: return bitc::BINOP_AND;
544 case Instruction::Or: return bitc::BINOP_OR;
545 case Instruction::Xor: return bitc::BINOP_XOR;
546 }
547}
548
Teresa Johnson37687f32016-04-23 04:30:47 +0000549static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000550 switch (Op) {
551 default: llvm_unreachable("Unknown RMW operation!");
552 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
553 case AtomicRMWInst::Add: return bitc::RMW_ADD;
554 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
555 case AtomicRMWInst::And: return bitc::RMW_AND;
556 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
557 case AtomicRMWInst::Or: return bitc::RMW_OR;
558 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
559 case AtomicRMWInst::Max: return bitc::RMW_MAX;
560 case AtomicRMWInst::Min: return bitc::RMW_MIN;
561 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
562 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
563 }
564}
565
Teresa Johnson37687f32016-04-23 04:30:47 +0000566static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000567 switch (Ordering) {
JF Bastien800f87a2016-04-06 21:19:33 +0000568 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
569 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
570 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
571 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
572 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
573 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
574 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000575 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000576 llvm_unreachable("Invalid ordering");
Eli Friedmanfee02c62011-07-25 23:16:38 +0000577}
578
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000579static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
580 StringRef Str, unsigned AbbrevToUse) {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000581 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000582
Chris Lattnere14cb882007-05-04 19:11:41 +0000583 // Code: [strchar x N]
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000584 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
585 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
586 AbbrevToUse = 0;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000587 Vals.push_back(Str[i]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000588 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000589
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000590 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000591 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000592}
593
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000594static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
595 switch (Kind) {
596 case Attribute::Alignment:
597 return bitc::ATTR_KIND_ALIGNMENT;
George Burgess IV278199f2016-04-12 01:05:35 +0000598 case Attribute::AllocSize:
599 return bitc::ATTR_KIND_ALLOC_SIZE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000600 case Attribute::AlwaysInline:
601 return bitc::ATTR_KIND_ALWAYS_INLINE;
Igor Laevsky39d662f2015-07-11 10:30:36 +0000602 case Attribute::ArgMemOnly:
603 return bitc::ATTR_KIND_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000604 case Attribute::Builtin:
605 return bitc::ATTR_KIND_BUILTIN;
606 case Attribute::ByVal:
607 return bitc::ATTR_KIND_BY_VAL;
Owen Anderson85fa7d52015-05-26 23:48:40 +0000608 case Attribute::Convergent:
609 return bitc::ATTR_KIND_CONVERGENT;
Reid Klecknera534a382013-12-19 02:14:12 +0000610 case Attribute::InAlloca:
611 return bitc::ATTR_KIND_IN_ALLOCA;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000612 case Attribute::Cold:
613 return bitc::ATTR_KIND_COLD;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +0000614 case Attribute::InaccessibleMemOnly:
615 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
616 case Attribute::InaccessibleMemOrArgMemOnly:
617 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000618 case Attribute::InlineHint:
619 return bitc::ATTR_KIND_INLINE_HINT;
620 case Attribute::InReg:
621 return bitc::ATTR_KIND_IN_REG;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000622 case Attribute::JumpTable:
623 return bitc::ATTR_KIND_JUMP_TABLE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000624 case Attribute::MinSize:
625 return bitc::ATTR_KIND_MIN_SIZE;
626 case Attribute::Naked:
627 return bitc::ATTR_KIND_NAKED;
628 case Attribute::Nest:
629 return bitc::ATTR_KIND_NEST;
630 case Attribute::NoAlias:
631 return bitc::ATTR_KIND_NO_ALIAS;
632 case Attribute::NoBuiltin:
633 return bitc::ATTR_KIND_NO_BUILTIN;
634 case Attribute::NoCapture:
635 return bitc::ATTR_KIND_NO_CAPTURE;
636 case Attribute::NoDuplicate:
637 return bitc::ATTR_KIND_NO_DUPLICATE;
638 case Attribute::NoImplicitFloat:
639 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
640 case Attribute::NoInline:
641 return bitc::ATTR_KIND_NO_INLINE;
James Molloye6f87ca2015-11-06 10:32:53 +0000642 case Attribute::NoRecurse:
643 return bitc::ATTR_KIND_NO_RECURSE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000644 case Attribute::NonLazyBind:
645 return bitc::ATTR_KIND_NON_LAZY_BIND;
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000646 case Attribute::NonNull:
647 return bitc::ATTR_KIND_NON_NULL;
Hal Finkelb0407ba2014-07-18 15:51:28 +0000648 case Attribute::Dereferenceable:
649 return bitc::ATTR_KIND_DEREFERENCEABLE;
Sanjoy Das31ea6d12015-04-16 20:29:50 +0000650 case Attribute::DereferenceableOrNull:
651 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000652 case Attribute::NoRedZone:
653 return bitc::ATTR_KIND_NO_RED_ZONE;
654 case Attribute::NoReturn:
655 return bitc::ATTR_KIND_NO_RETURN;
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +0000656 case Attribute::NoCfCheck:
657 return bitc::ATTR_KIND_NOCF_CHECK;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000658 case Attribute::NoUnwind:
659 return bitc::ATTR_KIND_NO_UNWIND;
Matt Morehouse236cdaf2018-03-22 17:07:51 +0000660 case Attribute::OptForFuzzing:
661 return bitc::ATTR_KIND_OPT_FOR_FUZZING;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000662 case Attribute::OptimizeForSize:
663 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000664 case Attribute::OptimizeNone:
665 return bitc::ATTR_KIND_OPTIMIZE_NONE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000666 case Attribute::ReadNone:
667 return bitc::ATTR_KIND_READ_NONE;
668 case Attribute::ReadOnly:
669 return bitc::ATTR_KIND_READ_ONLY;
670 case Attribute::Returned:
671 return bitc::ATTR_KIND_RETURNED;
672 case Attribute::ReturnsTwice:
673 return bitc::ATTR_KIND_RETURNS_TWICE;
674 case Attribute::SExt:
675 return bitc::ATTR_KIND_S_EXT;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +0000676 case Attribute::Speculatable:
677 return bitc::ATTR_KIND_SPECULATABLE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000678 case Attribute::StackAlignment:
679 return bitc::ATTR_KIND_STACK_ALIGNMENT;
680 case Attribute::StackProtect:
681 return bitc::ATTR_KIND_STACK_PROTECT;
682 case Attribute::StackProtectReq:
683 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
684 case Attribute::StackProtectStrong:
685 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000686 case Attribute::SafeStack:
687 return bitc::ATTR_KIND_SAFESTACK;
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +0000688 case Attribute::ShadowCallStack:
689 return bitc::ATTR_KIND_SHADOWCALLSTACK;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +0000690 case Attribute::StrictFP:
691 return bitc::ATTR_KIND_STRICT_FP;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000692 case Attribute::StructRet:
693 return bitc::ATTR_KIND_STRUCT_RET;
694 case Attribute::SanitizeAddress:
695 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +0000696 case Attribute::SanitizeHWAddress:
697 return bitc::ATTR_KIND_SANITIZE_HWADDRESS;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000698 case Attribute::SanitizeThread:
699 return bitc::ATTR_KIND_SANITIZE_THREAD;
700 case Attribute::SanitizeMemory:
701 return bitc::ATTR_KIND_SANITIZE_MEMORY;
Chandler Carruth664aa862018-09-04 12:38:00 +0000702 case Attribute::SpeculativeLoadHardening:
703 return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING;
Manman Ren9bfd0d02016-04-01 21:41:15 +0000704 case Attribute::SwiftError:
705 return bitc::ATTR_KIND_SWIFT_ERROR;
Manman Renf46262e2016-03-29 17:37:21 +0000706 case Attribute::SwiftSelf:
707 return bitc::ATTR_KIND_SWIFT_SELF;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000708 case Attribute::UWTable:
709 return bitc::ATTR_KIND_UW_TABLE;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +0000710 case Attribute::WriteOnly:
711 return bitc::ATTR_KIND_WRITEONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000712 case Attribute::ZExt:
713 return bitc::ATTR_KIND_Z_EXT;
714 case Attribute::EndAttrKinds:
715 llvm_unreachable("Can not encode end-attribute kinds marker.");
716 case Attribute::None:
717 llvm_unreachable("Can not encode none-attribute.");
718 }
719
720 llvm_unreachable("Trying to encode unknown attribute");
721}
722
Teresa Johnson37687f32016-04-23 04:30:47 +0000723void ModuleBitcodeWriter::writeAttributeGroupTable() {
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000724 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
725 VE.getAttributeGroups();
Bill Wendling92ed7002013-02-11 22:33:26 +0000726 if (AttrGrps.empty()) return;
Bill Wendlingdc095552013-02-10 23:09:32 +0000727
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000728 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
Bill Wendlingdc095552013-02-10 23:09:32 +0000729
730 SmallVector<uint64_t, 64> Record;
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000731 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
732 unsigned AttrListIndex = Pair.first;
733 AttributeSet AS = Pair.second;
734 Record.push_back(VE.getAttributeGroupID(Pair));
735 Record.push_back(AttrListIndex);
Bill Wendlingdc095552013-02-10 23:09:32 +0000736
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000737 for (Attribute Attr : AS) {
738 if (Attr.isEnumAttribute()) {
739 Record.push_back(0);
740 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
741 } else if (Attr.isIntAttribute()) {
742 Record.push_back(1);
743 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
744 Record.push_back(Attr.getValueAsInt());
745 } else {
746 StringRef Kind = Attr.getKindAsString();
747 StringRef Val = Attr.getValueAsString();
Bill Wendlingdc095552013-02-10 23:09:32 +0000748
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000749 Record.push_back(Val.empty() ? 3 : 4);
750 Record.append(Kind.begin(), Kind.end());
751 Record.push_back(0);
752 if (!Val.empty()) {
753 Record.append(Val.begin(), Val.end());
Bill Wendlingdc095552013-02-10 23:09:32 +0000754 Record.push_back(0);
Bill Wendlingdc095552013-02-10 23:09:32 +0000755 }
756 }
Bill Wendlingdc095552013-02-10 23:09:32 +0000757 }
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000758
759 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
760 Record.clear();
Bill Wendlingdc095552013-02-10 23:09:32 +0000761 }
762
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000763 Stream.ExitBlock();
Bill Wendlingdc095552013-02-10 23:09:32 +0000764}
765
Teresa Johnson37687f32016-04-23 04:30:47 +0000766void ModuleBitcodeWriter::writeAttributeTable() {
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000767 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000768 if (Attrs.empty()) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000769
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000770 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000771
772 SmallVector<uint64_t, 64> Record;
773 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
Reid Kleckner8bf67fe2017-05-23 17:01:48 +0000774 AttributeList AL = Attrs[i];
775 for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) {
776 AttributeSet AS = AL.getAttributes(i);
777 if (AS.hasAttributes())
778 Record.push_back(VE.getAttributeGroupID({i, AS}));
779 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000780
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000781 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000782 Record.clear();
783 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000784
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000785 Stream.ExitBlock();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000786}
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000787
788/// WriteTypeTable - Write out the type table for a module.
Teresa Johnson37687f32016-04-23 04:30:47 +0000789void ModuleBitcodeWriter::writeTypeTable() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000790 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000791
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000792 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000793 SmallVector<uint64_t, 64> TypeVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000794
David Blaikie7b028102015-02-25 00:51:52 +0000795 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
Chad Rosier9646c0d2011-12-08 00:38:45 +0000796
Chris Lattnerccee7062007-05-05 06:30:12 +0000797 // Abbrev for TYPE_CODE_POINTER.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000798 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000799 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000800 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
Christopher Lamb25f50762007-12-12 08:44:39 +0000801 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
David Blaikie7ad9dc12017-01-04 22:36:33 +0000802 unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000803
Chris Lattnerccee7062007-05-05 06:30:12 +0000804 // Abbrev for TYPE_CODE_FUNCTION.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000805 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000806 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
807 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
Chris Lattnerccee7062007-05-05 06:30:12 +0000808 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000809 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000810 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000811
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000812 // Abbrev for TYPE_CODE_STRUCT_ANON.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000813 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000814 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
Chris Lattnerccee7062007-05-05 06:30:12 +0000815 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
816 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000817 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000818 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000819
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000820 // Abbrev for TYPE_CODE_STRUCT_NAME.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000821 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000822 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
823 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
824 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000825 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000826
827 // Abbrev for TYPE_CODE_STRUCT_NAMED.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000828 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000829 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
830 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
831 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000832 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000833 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000834
Chris Lattnerccee7062007-05-05 06:30:12 +0000835 // Abbrev for TYPE_CODE_ARRAY.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000836 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000837 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
838 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
Chad Rosier9646c0d2011-12-08 00:38:45 +0000839 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000840 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000841
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000842 // Emit an entry count so the reader can reserve space.
843 TypeVals.push_back(TypeList.size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000844 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000845 TypeVals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000846
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000847 // Loop over all of the types, emitting each in turn.
848 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +0000849 Type *T = TypeList[i];
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000850 int AbbrevToUse = 0;
851 unsigned Code = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000852
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000853 switch (T->getTypeID()) {
Joe Abbey2ad8df22012-11-25 15:23:39 +0000854 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
855 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
856 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
857 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
858 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
859 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000860 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
Joe Abbey2ad8df22012-11-25 15:23:39 +0000861 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
862 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
863 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
David Majnemerb611e3f2015-08-14 05:09:07 +0000864 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000865 case Type::IntegerTyID:
866 // INTEGER: [width]
867 Code = bitc::TYPE_CODE_INTEGER;
868 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
869 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000870 case Type::PointerTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000871 PointerType *PTy = cast<PointerType>(T);
Christopher Lamb25f50762007-12-12 08:44:39 +0000872 // POINTER: [pointee type, address space]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000873 Code = bitc::TYPE_CODE_POINTER;
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000874 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
Christopher Lamb25f50762007-12-12 08:44:39 +0000875 unsigned AddressSpace = PTy->getAddressSpace();
876 TypeVals.push_back(AddressSpace);
877 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000878 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000879 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000880 case Type::FunctionTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000881 FunctionType *FT = cast<FunctionType>(T);
Chad Rosier95898722011-11-03 00:14:01 +0000882 // FUNCTION: [isvararg, retty, paramty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000883 Code = bitc::TYPE_CODE_FUNCTION;
884 TypeVals.push_back(FT->isVarArg());
885 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000886 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
887 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
Chris Lattnerccee7062007-05-05 06:30:12 +0000888 AbbrevToUse = FunctionAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000889 break;
890 }
891 case Type::StructTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000892 StructType *ST = cast<StructType>(T);
Chris Lattnerccee7062007-05-05 06:30:12 +0000893 // STRUCT: [ispacked, eltty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000894 TypeVals.push_back(ST->isPacked());
Chris Lattnere14cb882007-05-04 19:11:41 +0000895 // Output all of the element types.
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000896 for (StructType::element_iterator I = ST->element_begin(),
897 E = ST->element_end(); I != E; ++I)
898 TypeVals.push_back(VE.getTypeID(*I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000899
Chris Lattner335d3992011-08-12 18:06:37 +0000900 if (ST->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000901 Code = bitc::TYPE_CODE_STRUCT_ANON;
902 AbbrevToUse = StructAnonAbbrev;
903 } else {
904 if (ST->isOpaque()) {
905 Code = bitc::TYPE_CODE_OPAQUE;
906 } else {
907 Code = bitc::TYPE_CODE_STRUCT_NAMED;
908 AbbrevToUse = StructNamedAbbrev;
909 }
910
911 // Emit the name if it is present.
912 if (!ST->getName().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000913 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
Teresa Johnson37687f32016-04-23 04:30:47 +0000914 StructNameAbbrev);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000915 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000916 break;
917 }
918 case Type::ArrayTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000919 ArrayType *AT = cast<ArrayType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000920 // ARRAY: [numelts, eltty]
921 Code = bitc::TYPE_CODE_ARRAY;
922 TypeVals.push_back(AT->getNumElements());
923 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
Chris Lattnerccee7062007-05-05 06:30:12 +0000924 AbbrevToUse = ArrayAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000925 break;
926 }
927 case Type::VectorTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000928 VectorType *VT = cast<VectorType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000929 // VECTOR [numelts, eltty]
930 Code = bitc::TYPE_CODE_VECTOR;
931 TypeVals.push_back(VT->getNumElements());
932 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
933 break;
934 }
935 }
936
937 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000938 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000939 TypeVals.clear();
940 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000941
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000942 Stream.ExitBlock();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000943}
944
Teresa Johnson5e22e442016-02-06 16:07:35 +0000945static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
946 switch (Linkage) {
Rafael Espindola261d25b2015-01-08 16:25:01 +0000947 case GlobalValue::ExternalLinkage:
948 return 0;
949 case GlobalValue::WeakAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000950 return 16;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000951 case GlobalValue::AppendingLinkage:
952 return 2;
953 case GlobalValue::InternalLinkage:
954 return 3;
955 case GlobalValue::LinkOnceAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000956 return 18;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000957 case GlobalValue::ExternalWeakLinkage:
958 return 7;
959 case GlobalValue::CommonLinkage:
960 return 8;
961 case GlobalValue::PrivateLinkage:
962 return 9;
963 case GlobalValue::WeakODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000964 return 17;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000965 case GlobalValue::LinkOnceODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000966 return 19;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000967 case GlobalValue::AvailableExternallyLinkage:
968 return 12;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000969 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000970 llvm_unreachable("Invalid linkage");
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000971}
972
Teresa Johnson5e22e442016-02-06 16:07:35 +0000973static unsigned getEncodedLinkage(const GlobalValue &GV) {
974 return getEncodedLinkage(GV.getLinkage());
975}
976
Charles Saternos75da10d2017-08-04 16:00:58 +0000977static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) {
978 uint64_t RawFlags = 0;
979 RawFlags |= Flags.ReadNone;
980 RawFlags |= (Flags.ReadOnly << 1);
981 RawFlags |= (Flags.NoRecurse << 2);
982 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
Teresa Johnsoncb397462018-11-06 19:41:35 +0000983 RawFlags |= (Flags.NoInline << 4);
Charles Saternos75da10d2017-08-04 16:00:58 +0000984 return RawFlags;
985}
986
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000987// Decode the flags for GlobalValue in the summary
988static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
989 uint64_t RawFlags = 0;
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000990
Mehdi Amini1380edf2017-02-03 07:41:43 +0000991 RawFlags |= Flags.NotEligibleToImport; // bool
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000992 RawFlags |= (Flags.Live << 1);
Sean Fertile4595a912017-11-04 17:04:39 +0000993 RawFlags |= (Flags.DSOLocal << 2);
994
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000995 // Linkage don't need to be remapped at that time for the summary. Any future
996 // change to the getEncodedLinkage() function will need to be taken into
997 // account here as well.
Mehdi Amini1380edf2017-02-03 07:41:43 +0000998 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
999
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00001000 return RawFlags;
1001}
1002
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001003static unsigned getEncodedVisibility(const GlobalValue &GV) {
1004 switch (GV.getVisibility()) {
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +00001005 case GlobalValue::DefaultVisibility: return 0;
1006 case GlobalValue::HiddenVisibility: return 1;
1007 case GlobalValue::ProtectedVisibility: return 2;
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001008 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00001009 llvm_unreachable("Invalid visibility");
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001010}
1011
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001012static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1013 switch (GV.getDLLStorageClass()) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001014 case GlobalValue::DefaultStorageClass: return 0;
1015 case GlobalValue::DLLImportStorageClass: return 1;
1016 case GlobalValue::DLLExportStorageClass: return 2;
1017 }
1018 llvm_unreachable("Invalid DLL storage class");
1019}
1020
Rafael Espindola59f7eba2014-05-28 18:15:43 +00001021static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001022 switch (GV.getThreadLocalMode()) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001023 case GlobalVariable::NotThreadLocal: return 0;
1024 case GlobalVariable::GeneralDynamicTLSModel: return 1;
1025 case GlobalVariable::LocalDynamicTLSModel: return 2;
1026 case GlobalVariable::InitialExecTLSModel: return 3;
1027 case GlobalVariable::LocalExecTLSModel: return 4;
1028 }
1029 llvm_unreachable("Invalid TLS model");
1030}
1031
David Majnemerdad0a642014-06-27 18:19:56 +00001032static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1033 switch (C.getSelectionKind()) {
1034 case Comdat::Any:
1035 return bitc::COMDAT_SELECTION_KIND_ANY;
1036 case Comdat::ExactMatch:
1037 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
1038 case Comdat::Largest:
1039 return bitc::COMDAT_SELECTION_KIND_LARGEST;
1040 case Comdat::NoDuplicates:
1041 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
1042 case Comdat::SameSize:
1043 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
1044 }
1045 llvm_unreachable("Invalid selection kind");
1046}
1047
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001048static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1049 switch (GV.getUnnamedAddr()) {
1050 case GlobalValue::UnnamedAddr::None: return 0;
1051 case GlobalValue::UnnamedAddr::Local: return 2;
1052 case GlobalValue::UnnamedAddr::Global: return 1;
1053 }
1054 llvm_unreachable("Invalid unnamed_addr");
1055}
1056
Peter Collingbournec8556152017-07-06 17:56:01 +00001057size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1058 if (GenerateHash)
1059 Hasher.update(Str);
1060 return StrtabBuilder.add(Str);
1061}
1062
Teresa Johnson37687f32016-04-23 04:30:47 +00001063void ModuleBitcodeWriter::writeComdats() {
David Majnemer90a021f2016-03-13 08:01:03 +00001064 SmallVector<unsigned, 64> Vals;
David Majnemerdad0a642014-06-27 18:19:56 +00001065 for (const Comdat *C : VE.getComdats()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001066 // COMDAT: [strtab offset, strtab size, selection_kind]
Peter Collingbournec8556152017-07-06 17:56:01 +00001067 Vals.push_back(addToStrtab(C->getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001068 Vals.push_back(C->getName().size());
David Majnemerdad0a642014-06-27 18:19:56 +00001069 Vals.push_back(getEncodedComdatSelectionKind(*C));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001070 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
David Majnemerdad0a642014-06-27 18:19:56 +00001071 Vals.clear();
1072 }
1073}
1074
Teresa Johnsonff642b92015-09-17 20:12:00 +00001075/// Write a record that will eventually hold the word offset of the
1076/// module-level VST. For now the offset is 0, which will be backpatched
Teresa Johnson37687f32016-04-23 04:30:47 +00001077/// after the real VST is written. Saves the bit offset to backpatch.
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001078void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001079 // Write a placeholder value in for the offset of the real VST,
1080 // which is written after the function blocks so that it can include
1081 // the offset of each function. The placeholder offset will be
1082 // updated when the real VST is written.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001083 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnsonff642b92015-09-17 20:12:00 +00001084 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1085 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1086 // hold the real VST offset. Must use fixed instead of VBR as we don't
1087 // know how many VBR chunks to reserve ahead of time.
1088 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001089 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnsonff642b92015-09-17 20:12:00 +00001090
1091 // Emit the placeholder
1092 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001093 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001094
Teresa Johnson37687f32016-04-23 04:30:47 +00001095 // Compute and save the bit offset to the placeholder, which will be
Teresa Johnsonff642b92015-09-17 20:12:00 +00001096 // patched when the real VST is written. We can simply subtract the 32-bit
1097 // fixed size from the current bit number to get the location to backpatch.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001098 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
Teresa Johnsonff642b92015-09-17 20:12:00 +00001099}
1100
Teresa Johnsone1164de2016-02-10 21:55:02 +00001101enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
1102
1103/// Determine the encoding to use for the given string name and length.
David Blaikieb6b42e02017-06-02 17:24:26 +00001104static StringEncoding getStringEncoding(StringRef Str) {
Teresa Johnsone1164de2016-02-10 21:55:02 +00001105 bool isChar6 = true;
David Blaikieb6b42e02017-06-02 17:24:26 +00001106 for (char C : Str) {
Teresa Johnsone1164de2016-02-10 21:55:02 +00001107 if (isChar6)
David Blaikieb6b42e02017-06-02 17:24:26 +00001108 isChar6 = BitCodeAbbrevOp::isChar6(C);
1109 if ((unsigned char)C & 128)
Teresa Johnsone1164de2016-02-10 21:55:02 +00001110 // don't bother scanning the rest.
1111 return SE_Fixed8;
1112 }
1113 if (isChar6)
1114 return SE_Char6;
David Blaikieb6b42e02017-06-02 17:24:26 +00001115 return SE_Fixed7;
Teresa Johnsone1164de2016-02-10 21:55:02 +00001116}
1117
Teresa Johnsonff642b92015-09-17 20:12:00 +00001118/// Emit top-level description of module, including target triple, inline asm,
1119/// descriptors for global variables, and function prototype info.
1120/// Returns the bit offset to backpatch with the location of the real VST.
Teresa Johnson37687f32016-04-23 04:30:47 +00001121void ModuleBitcodeWriter::writeModuleInfo() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001122 // Emit various pieces of data attached to a module.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001123 if (!M.getTargetTriple().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001124 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001125 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001126 const std::string &DL = M.getDataLayoutStr();
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001127 if (!DL.empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001128 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001129 if (!M.getModuleInlineAsm().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001130 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001131 0 /*TODO*/);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001132
Gordon Henriksend930f912008-08-17 18:44:35 +00001133 // Emit information about sections and GC, computing how many there are. Also
1134 // compute the maximum alignment value.
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001135 std::map<std::string, unsigned> SectionMap;
Gordon Henriksend930f912008-08-17 18:44:35 +00001136 std::map<std::string, unsigned> GCMap;
Chris Lattner4b00d922007-04-23 16:04:05 +00001137 unsigned MaxAlignment = 0;
Chris Lattnerb5491372007-04-23 18:58:34 +00001138 unsigned MaxGlobalType = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001139 for (const GlobalValue &GV : M.globals()) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001140 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
David Blaikie1a848da2015-04-27 19:58:56 +00001141 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001142 if (GV.hasSection()) {
Chad Rosier75ec09c2011-08-12 16:45:18 +00001143 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001144 unsigned &Entry = SectionMap[GV.getSection()];
Chad Rosier75ec09c2011-08-12 16:45:18 +00001145 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001146 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001147 0 /*TODO*/);
Chad Rosier75ec09c2011-08-12 16:45:18 +00001148 Entry = SectionMap.size();
1149 }
1150 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001151 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001152 for (const Function &F : M) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001153 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
1154 if (F.hasSection()) {
Gordon Henriksen71183b62007-12-10 03:18:06 +00001155 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001156 unsigned &Entry = SectionMap[F.getSection()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001157 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001158 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001159 0 /*TODO*/);
Gordon Henriksen71183b62007-12-10 03:18:06 +00001160 Entry = SectionMap.size();
1161 }
1162 }
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001163 if (F.hasGC()) {
Gordon Henriksend930f912008-08-17 18:44:35 +00001164 // Same for GC names.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001165 unsigned &Entry = GCMap[F.getGC()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001166 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001167 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1168 0 /*TODO*/);
Gordon Henriksend930f912008-08-17 18:44:35 +00001169 Entry = GCMap.size();
Gordon Henriksen71183b62007-12-10 03:18:06 +00001170 }
1171 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001172 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001173
Chris Lattner4b00d922007-04-23 16:04:05 +00001174 // Emit abbrev for globals, now that we know # sections and max alignment.
1175 unsigned SimpleGVarAbbrev = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001176 if (!M.global_empty()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001177 // Add an abbrev for common globals with no visibility or thread localness.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001178 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner4b00d922007-04-23 16:04:05 +00001179 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001180 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1181 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Chris Lattner2eae59f2007-05-04 20:34:50 +00001182 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001183 Log2_32_Ceil(MaxGlobalType+1)));
David Blaikie1a848da2015-04-27 19:58:56 +00001184 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1185 //| explicitType << 1
1186 //| constant
1187 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1188 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1189 if (MaxAlignment == 0) // Alignment.
Chris Lattner4b00d922007-04-23 16:04:05 +00001190 Abbv->Add(BitCodeAbbrevOp(0));
1191 else {
1192 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
Chris Lattner2eae59f2007-05-04 20:34:50 +00001193 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001194 Log2_32_Ceil(MaxEncAlignment+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001195 }
1196 if (SectionMap.empty()) // Section.
1197 Abbv->Add(BitCodeAbbrevOp(0));
1198 else
Chris Lattner2eae59f2007-05-04 20:34:50 +00001199 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattner1e50c292007-04-24 03:29:47 +00001200 Log2_32_Ceil(SectionMap.size()+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001201 // Don't bother emitting vis + thread local.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001202 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Chris Lattner4b00d922007-04-23 16:04:05 +00001203 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001204
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001205 SmallVector<unsigned, 64> Vals;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001206 // Emit the module's source file name.
1207 {
David Blaikieb6b42e02017-06-02 17:24:26 +00001208 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001209 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1210 if (Bits == SE_Char6)
1211 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1212 else if (Bits == SE_Fixed7)
1213 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1214
1215 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1216 auto Abbv = std::make_shared<BitCodeAbbrev>();
1217 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1218 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1219 Abbv->Add(AbbrevOpToUse);
1220 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1221
1222 for (const auto P : M.getSourceFileName())
1223 Vals.push_back((unsigned char)P);
1224
1225 // Emit the finished record.
1226 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1227 Vals.clear();
1228 }
1229
1230 // Emit the global variable information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001231 for (const GlobalVariable &GV : M.globals()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001232 unsigned AbbrevToUse = 0;
1233
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001234 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00001235 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00001236 // unnamed_addr, externally_initialized, dllstorageclass,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001237 // comdat, attributes, DSO_Local]
Peter Collingbournec8556152017-07-06 17:56:01 +00001238 Vals.push_back(addToStrtab(GV.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001239 Vals.push_back(GV.getName().size());
David Blaikie1a848da2015-04-27 19:58:56 +00001240 Vals.push_back(VE.getTypeID(GV.getValueType()));
1241 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001242 Vals.push_back(GV.isDeclaration() ? 0 :
1243 (VE.getValueID(GV.getInitializer()) + 1));
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001244 Vals.push_back(getEncodedLinkage(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001245 Vals.push_back(Log2_32(GV.getAlignment())+1);
1246 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
1247 if (GV.isThreadLocal() ||
1248 GV.getVisibility() != GlobalValue::DefaultVisibility ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001249 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1250 GV.isExternallyInitialized() ||
David Majnemerdad0a642014-06-27 18:19:56 +00001251 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
Javed Absarf3d79042017-05-11 12:28:08 +00001252 GV.hasComdat() ||
Sean Fertilec70d28b2017-10-26 15:00:26 +00001253 GV.hasAttributes() ||
1254 GV.isDSOLocal()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001255 Vals.push_back(getEncodedVisibility(GV));
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001256 Vals.push_back(getEncodedThreadLocalMode(GV));
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001257 Vals.push_back(getEncodedUnnamedAddr(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001258 Vals.push_back(GV.isExternallyInitialized());
Nico Rieck7157bb72014-01-14 15:22:47 +00001259 Vals.push_back(getEncodedDLLStorageClass(GV));
David Majnemerdad0a642014-06-27 18:19:56 +00001260 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
Javed Absarf3d79042017-05-11 12:28:08 +00001261
1262 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1263 Vals.push_back(VE.getAttributeListID(AL));
Sean Fertilec70d28b2017-10-26 15:00:26 +00001264
1265 Vals.push_back(GV.isDSOLocal());
Chris Lattner4b00d922007-04-23 16:04:05 +00001266 } else {
1267 AbbrevToUse = SimpleGVarAbbrev;
1268 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001269
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001270 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001271 Vals.clear();
1272 }
1273
1274 // Emit the function proto information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001275 for (const Function &F : M) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001276 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1277 // linkage, paramattrs, alignment, section, visibility, gc,
1278 // unnamed_addr, prologuedata, dllstorageclass, comdat,
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001279 // prefixdata, personalityfn, DSO_Local, addrspace]
Peter Collingbournec8556152017-07-06 17:56:01 +00001280 Vals.push_back(addToStrtab(F.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001281 Vals.push_back(F.getName().size());
David Blaikie561a1572015-04-17 16:28:26 +00001282 Vals.push_back(VE.getTypeID(F.getFunctionType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001283 Vals.push_back(F.getCallingConv());
1284 Vals.push_back(F.isDeclaration());
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001285 Vals.push_back(getEncodedLinkage(F));
Reid Klecknerb4a2d182017-04-24 20:38:30 +00001286 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001287 Vals.push_back(Log2_32(F.getAlignment())+1);
1288 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001289 Vals.push_back(getEncodedVisibility(F));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001290 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001291 Vals.push_back(getEncodedUnnamedAddr(F));
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001292 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1293 : 0);
Nico Rieck7157bb72014-01-14 15:22:47 +00001294 Vals.push_back(getEncodedDLLStorageClass(F));
David Majnemerdad0a642014-06-27 18:19:56 +00001295 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001296 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1297 : 0);
David Majnemer7fddecc2015-06-17 20:52:32 +00001298 Vals.push_back(
1299 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001300
Sean Fertilec70d28b2017-10-26 15:00:26 +00001301 Vals.push_back(F.isDSOLocal());
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001302 Vals.push_back(F.getAddressSpace());
1303
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001304 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001305 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001306 Vals.clear();
1307 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001308
Chris Lattner44c17072007-04-26 02:46:40 +00001309 // Emit the alias information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001310 for (const GlobalAlias &A : M.aliases()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001311 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001312 // visibility, dllstorageclass, threadlocal, unnamed_addr,
1313 // DSO_Local]
Peter Collingbournec8556152017-07-06 17:56:01 +00001314 Vals.push_back(addToStrtab(A.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001315 Vals.push_back(A.getName().size());
David Blaikie6a51dbd2015-09-17 22:18:59 +00001316 Vals.push_back(VE.getTypeID(A.getValueType()));
1317 Vals.push_back(A.getType()->getAddressSpace());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001318 Vals.push_back(VE.getValueID(A.getAliasee()));
1319 Vals.push_back(getEncodedLinkage(A));
1320 Vals.push_back(getEncodedVisibility(A));
1321 Vals.push_back(getEncodedDLLStorageClass(A));
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001322 Vals.push_back(getEncodedThreadLocalMode(A));
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001323 Vals.push_back(getEncodedUnnamedAddr(A));
Sean Fertilec70d28b2017-10-26 15:00:26 +00001324 Vals.push_back(A.isDSOLocal());
1325
Chris Lattner44c17072007-04-26 02:46:40 +00001326 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001327 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
Chris Lattner44c17072007-04-26 02:46:40 +00001328 Vals.clear();
1329 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001330
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001331 // Emit the ifunc information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001332 for (const GlobalIFunc &I : M.ifuncs()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001333 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
Rafael Espindola3b9843f2018-01-12 17:03:43 +00001334 // val#, linkage, visibility, DSO_Local]
Peter Collingbournec8556152017-07-06 17:56:01 +00001335 Vals.push_back(addToStrtab(I.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001336 Vals.push_back(I.getName().size());
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001337 Vals.push_back(VE.getTypeID(I.getValueType()));
1338 Vals.push_back(I.getType()->getAddressSpace());
1339 Vals.push_back(VE.getValueID(I.getResolver()));
1340 Vals.push_back(getEncodedLinkage(I));
1341 Vals.push_back(getEncodedVisibility(I));
Rafael Espindola3b9843f2018-01-12 17:03:43 +00001342 Vals.push_back(I.isDSOLocal());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001343 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001344 Vals.clear();
1345 }
1346
Teresa Johnson37687f32016-04-23 04:30:47 +00001347 writeValueSymbolTableForwardDecl();
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001348}
1349
Teresa Johnson37687f32016-04-23 04:30:47 +00001350static uint64_t getOptimizationFlags(const Value *V) {
Dan Gohman0ebd6962009-07-20 21:19:07 +00001351 uint64_t Flags = 0;
1352
Sanjay Patelc00017d2014-10-15 17:45:13 +00001353 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
Dan Gohman16f54152009-08-20 17:11:38 +00001354 if (OBO->hasNoSignedWrap())
1355 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1356 if (OBO->hasNoUnsignedWrap())
1357 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001358 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
Chris Lattner35315d02011-02-06 21:44:57 +00001359 if (PEO->isExact())
1360 Flags |= 1 << bitc::PEO_EXACT;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001361 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
Sanjay Patel629c4112017-11-06 16:27:15 +00001362 if (FPMO->hasAllowReassoc())
Steven Wu545d34a2018-02-19 19:22:28 +00001363 Flags |= bitc::AllowReassoc;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001364 if (FPMO->hasNoNaNs())
Steven Wu545d34a2018-02-19 19:22:28 +00001365 Flags |= bitc::NoNaNs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001366 if (FPMO->hasNoInfs())
Steven Wu545d34a2018-02-19 19:22:28 +00001367 Flags |= bitc::NoInfs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001368 if (FPMO->hasNoSignedZeros())
Steven Wu545d34a2018-02-19 19:22:28 +00001369 Flags |= bitc::NoSignedZeros;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001370 if (FPMO->hasAllowReciprocal())
Steven Wu545d34a2018-02-19 19:22:28 +00001371 Flags |= bitc::AllowReciprocal;
Adam Nemetcd847a82017-03-28 20:11:52 +00001372 if (FPMO->hasAllowContract())
Steven Wu545d34a2018-02-19 19:22:28 +00001373 Flags |= bitc::AllowContract;
Sanjay Patel629c4112017-11-06 16:27:15 +00001374 if (FPMO->hasApproxFunc())
Steven Wu545d34a2018-02-19 19:22:28 +00001375 Flags |= bitc::ApproxFunc;
Dan Gohman0ebd6962009-07-20 21:19:07 +00001376 }
1377
1378 return Flags;
1379}
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001380
Teresa Johnson37687f32016-04-23 04:30:47 +00001381void ModuleBitcodeWriter::writeValueAsMetadata(
1382 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001383 // Mimic an MDNode with a value as one operand.
1384 Value *V = MD->getValue();
1385 Record.push_back(VE.getTypeID(V->getType()));
1386 Record.push_back(VE.getValueID(V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001387 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001388 Record.clear();
1389}
1390
Teresa Johnson37687f32016-04-23 04:30:47 +00001391void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1392 SmallVectorImpl<uint64_t> &Record,
1393 unsigned Abbrev) {
Chris Lattner9b493022009-12-31 01:22:29 +00001394 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001395 Metadata *MD = N->getOperand(i);
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001396 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1397 "Unexpected function-local metadata");
1398 Record.push_back(VE.getMetadataOrNullID(MD));
Devang Patel8cca7b42009-08-04 05:01:35 +00001399 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001400 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1401 : bitc::METADATA_NODE,
1402 Record, Abbrev);
Devang Patel8cca7b42009-08-04 05:01:35 +00001403 Record.clear();
1404}
Devang Patele059ba6e2009-07-23 01:07:34 +00001405
Teresa Johnson37687f32016-04-23 04:30:47 +00001406unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001407 // Assume the column is usually under 128, and always output the inlined-at
1408 // location (it's never more expensive than building an array size 1).
David Blaikie7ad9dc12017-01-04 22:36:33 +00001409 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001410 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1411 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1412 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1413 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1414 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1415 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
Calixte Denizeteb7f6022018-09-20 08:53:06 +00001416 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001417 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001418}
1419
Teresa Johnson37687f32016-04-23 04:30:47 +00001420void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1421 SmallVectorImpl<uint64_t> &Record,
1422 unsigned &Abbrev) {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001423 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001424 Abbrev = createDILocationAbbrev();
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001425
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001426 Record.push_back(N->isDistinct());
1427 Record.push_back(N->getLine());
1428 Record.push_back(N->getColumn());
1429 Record.push_back(VE.getMetadataID(N->getScope()));
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001430 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
Calixte Denizeteb7f6022018-09-20 08:53:06 +00001431 Record.push_back(N->isImplicitCode());
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001432
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001433 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001434 Record.clear();
1435}
1436
Teresa Johnson37687f32016-04-23 04:30:47 +00001437unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001438 // Assume the column is usually under 128, and always output the inlined-at
1439 // location (it's never more expensive than building an array size 1).
David Blaikie7ad9dc12017-01-04 22:36:33 +00001440 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001441 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1442 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1443 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1444 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1445 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1446 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1447 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001448 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001449}
1450
Teresa Johnson37687f32016-04-23 04:30:47 +00001451void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1452 SmallVectorImpl<uint64_t> &Record,
1453 unsigned &Abbrev) {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001454 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001455 Abbrev = createGenericDINodeAbbrev();
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001456
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001457 Record.push_back(N->isDistinct());
1458 Record.push_back(N->getTag());
1459 Record.push_back(0); // Per-tag version field; unused for now.
1460
1461 for (auto &I : N->operands())
1462 Record.push_back(VE.getMetadataOrNullID(I));
1463
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001464 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001465 Record.clear();
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001466}
1467
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001468static uint64_t rotateSign(int64_t I) {
1469 uint64_t U = I;
1470 return I < 0 ? ~(U << 1) : U << 1;
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001471}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001472
Teresa Johnson37687f32016-04-23 04:30:47 +00001473void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1474 SmallVectorImpl<uint64_t> &Record,
1475 unsigned Abbrev) {
Sander de Smalenfdf40912018-01-24 09:56:07 +00001476 const uint64_t Version = 1 << 1;
1477 Record.push_back((uint64_t)N->isDistinct() | Version);
1478 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
Duncan P. N. Exon Smith5dcf6212015-04-07 00:39:59 +00001479 Record.push_back(rotateSign(N->getLowerBound()));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001480
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001481 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001482 Record.clear();
1483}
1484
Teresa Johnson37687f32016-04-23 04:30:47 +00001485void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1486 SmallVectorImpl<uint64_t> &Record,
1487 unsigned Abbrev) {
Momchil Velikov08dc66e2018-02-12 16:10:09 +00001488 Record.push_back((N->isUnsigned() << 1) | N->isDistinct());
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001489 Record.push_back(rotateSign(N->getValue()));
1490 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1491
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001492 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001493 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001494}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001495
Teresa Johnson37687f32016-04-23 04:30:47 +00001496void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1497 SmallVectorImpl<uint64_t> &Record,
1498 unsigned Abbrev) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001499 Record.push_back(N->isDistinct());
1500 Record.push_back(N->getTag());
1501 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1502 Record.push_back(N->getSizeInBits());
1503 Record.push_back(N->getAlignInBits());
1504 Record.push_back(N->getEncoding());
Adrian Prantl55f42622018-08-14 19:35:34 +00001505 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001506
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001507 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001508 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001509}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001510
Teresa Johnson37687f32016-04-23 04:30:47 +00001511void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1512 SmallVectorImpl<uint64_t> &Record,
1513 unsigned Abbrev) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001514 Record.push_back(N->isDistinct());
1515 Record.push_back(N->getTag());
1516 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1517 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1518 Record.push_back(N->getLine());
1519 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001520 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001521 Record.push_back(N->getSizeInBits());
1522 Record.push_back(N->getAlignInBits());
1523 Record.push_back(N->getOffsetInBits());
1524 Record.push_back(N->getFlags());
1525 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1526
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00001527 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1528 // that there is no DWARF address space associated with DIDerivedType.
1529 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1530 Record.push_back(*DWARFAddressSpace + 1);
1531 else
1532 Record.push_back(0);
1533
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001534 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001535 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001536}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001537
Teresa Johnson37687f32016-04-23 04:30:47 +00001538void ModuleBitcodeWriter::writeDICompositeType(
1539 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1540 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001541 const unsigned IsNotUsedInOldTypeRef = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001542 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001543 Record.push_back(N->getTag());
1544 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1545 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1546 Record.push_back(N->getLine());
1547 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1548 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1549 Record.push_back(N->getSizeInBits());
1550 Record.push_back(N->getAlignInBits());
1551 Record.push_back(N->getOffsetInBits());
1552 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001553 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001554 Record.push_back(N->getRuntimeLang());
1555 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001556 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001557 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
Adrian Prantl8c599212018-02-06 23:45:59 +00001558 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001559
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001560 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001561 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001562}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001563
Teresa Johnson37687f32016-04-23 04:30:47 +00001564void ModuleBitcodeWriter::writeDISubroutineType(
1565 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1566 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001567 const unsigned HasNoOldTypeRefs = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001568 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001569 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001570 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001571 Record.push_back(N->getCC());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001572
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001573 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001574 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001575}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001576
Teresa Johnson37687f32016-04-23 04:30:47 +00001577void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1578 SmallVectorImpl<uint64_t> &Record,
1579 unsigned Abbrev) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001580 Record.push_back(N->isDistinct());
1581 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1582 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
Scott Linder71603842018-02-12 19:45:54 +00001583 if (N->getRawChecksum()) {
1584 Record.push_back(N->getRawChecksum()->Kind);
1585 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1586 } else {
1587 // Maintain backwards compatibility with the old internal representation of
1588 // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1589 Record.push_back(0);
1590 Record.push_back(VE.getMetadataOrNullID(nullptr));
1591 }
Scott Linder16c7bda2018-02-23 23:01:06 +00001592 auto Source = N->getRawSource();
1593 if (Source)
1594 Record.push_back(VE.getMetadataOrNullID(*Source));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001595
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001596 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001597 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001598}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001599
Teresa Johnson37687f32016-04-23 04:30:47 +00001600void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1601 SmallVectorImpl<uint64_t> &Record,
1602 unsigned Abbrev) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00001603 assert(N->isDistinct() && "Expected distinct compile units");
1604 Record.push_back(/* IsDistinct */ true);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001605 Record.push_back(N->getSourceLanguage());
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001606 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001607 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1608 Record.push_back(N->isOptimized());
1609 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1610 Record.push_back(N->getRuntimeVersion());
1611 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1612 Record.push_back(N->getEmissionKind());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001613 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1614 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
Adrian Prantl75819ae2016-04-15 15:57:41 +00001615 Record.push_back(/* subprograms */ 0);
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001616 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1617 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
Adrian Prantl1f599f92015-05-21 20:37:30 +00001618 Record.push_back(N->getDWOId());
Amjad Abouda9bcf162015-12-10 12:56:35 +00001619 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
David Blaikiea01f2952016-08-24 18:29:49 +00001620 Record.push_back(N->getSplitDebugInlining());
Dehao Chen0944a8c2017-02-01 22:45:09 +00001621 Record.push_back(N->getDebugInfoForProfiling());
David Blaikie66cf14d2018-08-16 21:29:55 +00001622 Record.push_back((unsigned)N->getNameTableKind());
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001623
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001624 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001625 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001626}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001627
Teresa Johnson37687f32016-04-23 04:30:47 +00001628void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1629 SmallVectorImpl<uint64_t> &Record,
1630 unsigned Abbrev) {
Adrian Prantl85338cb2016-05-06 22:53:06 +00001631 uint64_t HasUnitFlag = 1 << 1;
1632 Record.push_back(N->isDistinct() | HasUnitFlag);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001633 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1634 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1635 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1636 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1637 Record.push_back(N->getLine());
1638 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1639 Record.push_back(N->isLocalToUnit());
1640 Record.push_back(N->isDefinition());
1641 Record.push_back(N->getScopeLine());
1642 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1643 Record.push_back(N->getVirtuality());
1644 Record.push_back(N->getVirtualIndex());
1645 Record.push_back(N->getFlags());
1646 Record.push_back(N->isOptimized());
Adrian Prantl75819ae2016-04-15 15:57:41 +00001647 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001648 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001649 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
Shiva Chen2c864552018-05-09 02:40:45 +00001650 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001651 Record.push_back(N->getThisAdjustment());
Adrian Prantl1d12b882017-04-26 22:56:44 +00001652 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001653
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001654 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001655 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001656}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001657
Teresa Johnson37687f32016-04-23 04:30:47 +00001658void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1659 SmallVectorImpl<uint64_t> &Record,
1660 unsigned Abbrev) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001661 Record.push_back(N->isDistinct());
1662 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1663 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1664 Record.push_back(N->getLine());
1665 Record.push_back(N->getColumn());
1666
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001667 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001668 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001669}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001670
Teresa Johnson37687f32016-04-23 04:30:47 +00001671void ModuleBitcodeWriter::writeDILexicalBlockFile(
1672 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1673 unsigned Abbrev) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001674 Record.push_back(N->isDistinct());
1675 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1676 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1677 Record.push_back(N->getDiscriminator());
1678
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001679 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001680 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001681}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001682
Teresa Johnson37687f32016-04-23 04:30:47 +00001683void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1684 SmallVectorImpl<uint64_t> &Record,
1685 unsigned Abbrev) {
Adrian Prantldbfda632016-11-03 19:42:02 +00001686 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001687 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001688 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001689
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001690 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001691 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001692}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001693
Teresa Johnson37687f32016-04-23 04:30:47 +00001694void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1695 SmallVectorImpl<uint64_t> &Record,
1696 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001697 Record.push_back(N->isDistinct());
1698 Record.push_back(N->getMacinfoType());
1699 Record.push_back(N->getLine());
1700 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1701 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1702
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001703 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001704 Record.clear();
1705}
1706
Teresa Johnson37687f32016-04-23 04:30:47 +00001707void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1708 SmallVectorImpl<uint64_t> &Record,
1709 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001710 Record.push_back(N->isDistinct());
1711 Record.push_back(N->getMacinfoType());
1712 Record.push_back(N->getLine());
1713 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1714 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1715
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001716 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001717 Record.clear();
1718}
1719
Teresa Johnson37687f32016-04-23 04:30:47 +00001720void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1721 SmallVectorImpl<uint64_t> &Record,
1722 unsigned Abbrev) {
Adrian Prantlab1243f2015-06-29 23:03:47 +00001723 Record.push_back(N->isDistinct());
1724 for (auto &I : N->operands())
1725 Record.push_back(VE.getMetadataOrNullID(I));
1726
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001727 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
Adrian Prantlab1243f2015-06-29 23:03:47 +00001728 Record.clear();
1729}
1730
Teresa Johnson37687f32016-04-23 04:30:47 +00001731void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1732 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1733 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001734 Record.push_back(N->isDistinct());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001735 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1736 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1737
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001738 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001739 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001740}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001741
Teresa Johnson37687f32016-04-23 04:30:47 +00001742void ModuleBitcodeWriter::writeDITemplateValueParameter(
1743 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1744 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001745 Record.push_back(N->isDistinct());
1746 Record.push_back(N->getTag());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001747 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1748 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1749 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1750
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001751 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001752 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001753}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001754
Teresa Johnson37687f32016-04-23 04:30:47 +00001755void ModuleBitcodeWriter::writeDIGlobalVariable(
1756 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1757 unsigned Abbrev) {
Matthew Vossf8ab35a2018-10-03 18:44:53 +00001758 const uint64_t Version = 2 << 1;
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001759 Record.push_back((uint64_t)N->isDistinct() | Version);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001760 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1761 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1762 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1763 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1764 Record.push_back(N->getLine());
1765 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1766 Record.push_back(N->isLocalToUnit());
1767 Record.push_back(N->isDefinition());
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001768 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
Matthew Vossf8ab35a2018-10-03 18:44:53 +00001769 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
Victor Leschuk2ede1262016-10-20 00:13:12 +00001770 Record.push_back(N->getAlignInBits());
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001771
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001772 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001773 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001774}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001775
Teresa Johnson37687f32016-04-23 04:30:47 +00001776void ModuleBitcodeWriter::writeDILocalVariable(
1777 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1778 unsigned Abbrev) {
Victor Leschuk2ede1262016-10-20 00:13:12 +00001779 // In order to support all possible bitcode formats in BitcodeReader we need
Simon Pilgrim25059362016-10-20 10:42:14 +00001780 // to distinguish the following cases:
Victor Leschuk2ede1262016-10-20 00:13:12 +00001781 // 1) Record has no artificial tag (Record[1]),
1782 // has no obsolete inlinedAt field (Record[9]).
1783 // In this case Record size will be 8, HasAlignment flag is false.
1784 // 2) Record has artificial tag (Record[1]),
1785 // has no obsolete inlignedAt field (Record[9]).
1786 // In this case Record size will be 9, HasAlignment flag is false.
1787 // 3) Record has both artificial tag (Record[1]) and
1788 // obsolete inlignedAt field (Record[9]).
1789 // In this case Record size will be 10, HasAlignment flag is false.
1790 // 4) Record has neither artificial tag, nor inlignedAt field, but
1791 // HasAlignment flag is true and Record[8] contains alignment value.
1792 const uint64_t HasAlignmentFlag = 1 << 1;
Simon Pilgrim071da462016-10-20 10:37:58 +00001793 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001794 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1795 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1796 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1797 Record.push_back(N->getLine());
1798 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1799 Record.push_back(N->getArg());
1800 Record.push_back(N->getFlags());
Victor Leschuk2ede1262016-10-20 00:13:12 +00001801 Record.push_back(N->getAlignInBits());
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001802
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001803 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001804 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001805}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001806
Shiva Chen2c864552018-05-09 02:40:45 +00001807void ModuleBitcodeWriter::writeDILabel(
1808 const DILabel *N, SmallVectorImpl<uint64_t> &Record,
1809 unsigned Abbrev) {
1810 Record.push_back((uint64_t)N->isDistinct());
1811 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1812 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1813 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1814 Record.push_back(N->getLine());
1815
1816 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
1817 Record.clear();
1818}
1819
Teresa Johnson37687f32016-04-23 04:30:47 +00001820void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1821 SmallVectorImpl<uint64_t> &Record,
1822 unsigned Abbrev) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001823 Record.reserve(N->getElements().size() + 1);
Florian Hahnffc498d2017-06-14 13:14:38 +00001824 const uint64_t Version = 3 << 1;
Adrian Prantl6825fb62017-04-18 01:21:53 +00001825 Record.push_back((uint64_t)N->isDistinct() | Version);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001826 Record.append(N->elements_begin(), N->elements_end());
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001827
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001828 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001829 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001830}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001831
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001832void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1833 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1834 unsigned Abbrev) {
1835 Record.push_back(N->isDistinct());
1836 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1837 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
Charles Saternos75da10d2017-08-04 16:00:58 +00001838
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001839 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1840 Record.clear();
1841}
1842
Teresa Johnson37687f32016-04-23 04:30:47 +00001843void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1844 SmallVectorImpl<uint64_t> &Record,
1845 unsigned Abbrev) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001846 Record.push_back(N->isDistinct());
1847 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1848 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1849 Record.push_back(N->getLine());
1850 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1851 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1852 Record.push_back(N->getAttributes());
1853 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1854
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001855 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001856 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001857}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001858
Teresa Johnson37687f32016-04-23 04:30:47 +00001859void ModuleBitcodeWriter::writeDIImportedEntity(
1860 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1861 unsigned Abbrev) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001862 Record.push_back(N->isDistinct());
1863 Record.push_back(N->getTag());
1864 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1865 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1866 Record.push_back(N->getLine());
1867 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
Adrian Prantld63bfd22017-07-19 00:09:54 +00001868 Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001869
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001870 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001871 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001872}
1873
Teresa Johnson37687f32016-04-23 04:30:47 +00001874unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
David Blaikie7ad9dc12017-01-04 22:36:33 +00001875 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001876 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1877 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1878 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001879 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001880}
1881
Teresa Johnson37687f32016-04-23 04:30:47 +00001882void ModuleBitcodeWriter::writeNamedMetadata(
1883 SmallVectorImpl<uint64_t> &Record) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001884 if (M.named_metadata_empty())
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001885 return;
1886
Teresa Johnson37687f32016-04-23 04:30:47 +00001887 unsigned Abbrev = createNamedMetadataAbbrev();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001888 for (const NamedMDNode &NMD : M.named_metadata()) {
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001889 // Write name.
1890 StringRef Str = NMD.getName();
1891 Record.append(Str.bytes_begin(), Str.bytes_end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001892 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001893 Record.clear();
1894
1895 // Write named metadata operands.
1896 for (const MDNode *N : NMD.operands())
1897 Record.push_back(VE.getMetadataID(N));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001898 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001899 Record.clear();
1900 }
1901}
1902
Teresa Johnson37687f32016-04-23 04:30:47 +00001903unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
David Blaikie7ad9dc12017-01-04 22:36:33 +00001904 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001905 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1906 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1907 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1908 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001909 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001910}
1911
1912/// Write out a record for MDString.
1913///
1914/// All the metadata strings in a metadata block are emitted in a single
1915/// record. The sizes and strings themselves are shoved into a blob.
Teresa Johnson37687f32016-04-23 04:30:47 +00001916void ModuleBitcodeWriter::writeMetadataStrings(
1917 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001918 if (Strings.empty())
1919 return;
1920
1921 // Start the record with the number of strings.
1922 Record.push_back(bitc::METADATA_STRINGS);
1923 Record.push_back(Strings.size());
1924
1925 // Emit the sizes of the strings in the blob.
1926 SmallString<256> Blob;
1927 {
1928 BitstreamWriter W(Blob);
1929 for (const Metadata *MD : Strings)
1930 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1931 W.FlushToWord();
1932 }
1933
1934 // Add the offset to the strings to the record.
1935 Record.push_back(Blob.size());
1936
1937 // Add the strings to the blob.
1938 for (const Metadata *MD : Strings)
1939 Blob.append(cast<MDString>(MD)->getString());
1940
1941 // Emit the final record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001942 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001943 Record.clear();
1944}
1945
Mehdi Aminie98f9252016-12-28 22:30:28 +00001946// Generates an enum to use as an index in the Abbrev array of Metadata record.
1947enum MetadataAbbrev : unsigned {
1948#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1949#include "llvm/IR/Metadata.def"
1950 LastPlusOne
1951};
1952
Teresa Johnson37687f32016-04-23 04:30:47 +00001953void ModuleBitcodeWriter::writeMetadataRecords(
Mehdi Aminie98f9252016-12-28 22:30:28 +00001954 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
1955 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001956 if (MDs.empty())
Duncan P. N. Exon Smith2fcf60e2015-01-12 22:30:34 +00001957 return;
1958
Duncan P. N. Exon Smith6b7b6802015-02-04 21:54:12 +00001959 // Initialize MDNode abbreviations.
1960#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1961#include "llvm/IR/Metadata.def"
1962
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001963 for (const Metadata *MD : MDs) {
Mehdi Aminie98f9252016-12-28 22:30:28 +00001964 if (IndexPos)
1965 IndexPos->push_back(Stream.GetCurrentBitNo());
Duncan P. N. Exon Smith73d5aae2015-01-12 22:31:35 +00001966 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
Duncan P. N. Exon Smith79f8d112015-03-17 00:16:35 +00001967 assert(N->isResolved() && "Expected forward references to be resolved");
1968
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001969 switch (N->getMetadataID()) {
1970 default:
1971 llvm_unreachable("Invalid MDNode subclass");
1972#define HANDLE_MDNODE_LEAF(CLASS) \
1973 case Metadata::CLASS##Kind: \
Mehdi Aminie98f9252016-12-28 22:30:28 +00001974 if (MDAbbrevs) \
1975 write##CLASS(cast<CLASS>(N), Record, \
1976 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
1977 else \
1978 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001979 continue;
1980#include "llvm/IR/Metadata.def"
1981 }
Devang Patel8cca7b42009-08-04 05:01:35 +00001982 }
Teresa Johnson37687f32016-04-23 04:30:47 +00001983 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
Devang Patel8cca7b42009-08-04 05:01:35 +00001984 }
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001985}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001986
Teresa Johnson37687f32016-04-23 04:30:47 +00001987void ModuleBitcodeWriter::writeModuleMetadata() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001988 if (!VE.hasMDs() && M.named_metadata_empty())
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001989 return;
1990
Mehdi Aminie98f9252016-12-28 22:30:28 +00001991 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001992 SmallVector<uint64_t, 64> Record;
Mehdi Aminie98f9252016-12-28 22:30:28 +00001993
1994 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1995 // block and load any metadata.
1996 std::vector<unsigned> MDAbbrevs;
1997
1998 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
1999 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2000 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2001 createGenericDINodeAbbrev();
2002
David Blaikie7ad9dc12017-01-04 22:36:33 +00002003 auto Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminie98f9252016-12-28 22:30:28 +00002004 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
Mehdi Amini5022bb72016-12-28 23:45:54 +00002005 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2006 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002007 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminie98f9252016-12-28 22:30:28 +00002008
David Blaikie7ad9dc12017-01-04 22:36:33 +00002009 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminie98f9252016-12-28 22:30:28 +00002010 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
2011 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2012 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002013 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminie98f9252016-12-28 22:30:28 +00002014
2015 // Emit MDStrings together upfront.
Teresa Johnson37687f32016-04-23 04:30:47 +00002016 writeMetadataStrings(VE.getMDStrings(), Record);
Mehdi Aminie98f9252016-12-28 22:30:28 +00002017
2018 // We only emit an index for the metadata record if we have more than a given
2019 // (naive) threshold of metadatas, otherwise it is not worth it.
2020 if (VE.getNonMDStrings().size() > IndexThreshold) {
2021 // Write a placeholder value in for the offset of the metadata index,
2022 // which is written after the records, so that it can include
2023 // the offset of each entry. The placeholder offset will be
2024 // updated after all records are emitted.
Mehdi Amini5022bb72016-12-28 23:45:54 +00002025 uint64_t Vals[] = {0, 0};
Mehdi Aminie98f9252016-12-28 22:30:28 +00002026 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2027 }
2028
2029 // Compute and save the bit offset to the current position, which will be
2030 // patched when we emit the index later. We can simply subtract the 64-bit
2031 // fixed size from the current bit number to get the location to backpatch.
2032 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2033
2034 // This index will contain the bitpos for each individual record.
2035 std::vector<uint64_t> IndexPos;
2036 IndexPos.reserve(VE.getNonMDStrings().size());
2037
2038 // Write all the records
2039 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2040
2041 if (VE.getNonMDStrings().size() > IndexThreshold) {
2042 // Now that we have emitted all the records we will emit the index. But
2043 // first
2044 // backpatch the forward reference so that the reader can skip the records
2045 // efficiently.
2046 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2047 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2048
2049 // Delta encode the index.
2050 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2051 for (auto &Elt : IndexPos) {
2052 auto EltDelta = Elt - PreviousValue;
2053 PreviousValue = Elt;
2054 Elt = EltDelta;
2055 }
2056 // Emit the index record.
2057 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2058 IndexPos.clear();
2059 }
2060
2061 // Write the named metadata now.
Teresa Johnson37687f32016-04-23 04:30:47 +00002062 writeNamedMetadata(Record);
Peter Collingbourne21521892016-06-21 23:42:48 +00002063
2064 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2065 SmallVector<uint64_t, 4> Record;
2066 Record.push_back(VE.getValueID(&GO));
2067 pushGlobalMetadataAttachment(Record, GO);
2068 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
2069 };
2070 for (const Function &F : M)
2071 if (F.isDeclaration() && F.hasMetadata())
2072 AddDeclAttachedMetadata(F);
2073 // FIXME: Only store metadata for declarations here, and move data for global
2074 // variable definitions to a separate block (PR28134).
2075 for (const GlobalVariable &GV : M.globals())
2076 if (GV.hasMetadata())
2077 AddDeclAttachedMetadata(GV);
2078
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002079 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00002080}
2081
Teresa Johnson37687f32016-04-23 04:30:47 +00002082void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
Duncan P. N. Exon Smith93429112016-04-02 15:09:42 +00002083 if (!VE.hasMDs())
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00002084 return;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002085
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002086 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00002087 SmallVector<uint64_t, 64> Record;
Teresa Johnson37687f32016-04-23 04:30:47 +00002088 writeMetadataStrings(VE.getMDStrings(), Record);
2089 writeMetadataRecords(VE.getNonMDStrings(), Record);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002090 Stream.ExitBlock();
Victor Hernandezb00a6be2010-01-13 19:37:33 +00002091}
2092
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002093void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2094 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2095 // [n x [id, mdnode]]
2096 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2097 GO.getAllMetadata(MDs);
2098 for (const auto &I : MDs) {
2099 Record.push_back(I.first);
2100 Record.push_back(VE.getMetadataID(I.second));
2101 }
2102}
2103
2104void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002105 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
Chris Lattner07d09ed2010-04-03 02:17:50 +00002106
Devang Patelaf206b82009-09-18 19:26:43 +00002107 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002108
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002109 if (F.hasMetadata()) {
2110 pushGlobalMetadataAttachment(Record, F);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002111 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002112 Record.clear();
2113 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002114
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002115 // Write metadata attachments
2116 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2117 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00002118 for (const BasicBlock &BB : F)
2119 for (const Instruction &I : BB) {
Devang Patel6da5dbf2009-10-22 18:55:16 +00002120 MDs.clear();
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00002121 I.getAllMetadataOtherThanDebugLoc(MDs);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002122
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002123 // If no metadata, ignore instruction.
2124 if (MDs.empty()) continue;
2125
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00002126 Record.push_back(VE.getInstructionID(&I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002127
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002128 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2129 Record.push_back(MDs[i].first);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002130 Record.push_back(VE.getMetadataID(MDs[i].second));
Devang Patelaf206b82009-09-18 19:26:43 +00002131 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002132 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002133 Record.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00002134 }
2135
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002136 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00002137}
2138
Peter Collingbourne21521892016-06-21 23:42:48 +00002139void ModuleBitcodeWriter::writeModuleMetadataKinds() {
Devang Patelaf206b82009-09-18 19:26:43 +00002140 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002141
Devang Patelaf206b82009-09-18 19:26:43 +00002142 // Write metadata kinds
2143 // METADATA_KIND - [n x [id, name]]
Michael Ilseman979dfbb2012-12-03 22:57:47 +00002144 SmallVector<StringRef, 8> Names;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002145 M.getMDKindNames(Names);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002146
Dan Gohman43aa8f02010-07-20 21:42:28 +00002147 if (Names.empty()) return;
Chris Lattnerc9558df2009-12-28 20:10:43 +00002148
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002149 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002150
Dan Gohman43aa8f02010-07-20 21:42:28 +00002151 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
Chris Lattnerc9558df2009-12-28 20:10:43 +00002152 Record.push_back(MDKindID);
2153 StringRef KName = Names[MDKindID];
2154 Record.append(KName.begin(), KName.end());
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002155
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002156 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
Devang Patelaf206b82009-09-18 19:26:43 +00002157 Record.clear();
2158 }
2159
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002160 Stream.ExitBlock();
Devang Patel8cca7b42009-08-04 05:01:35 +00002161}
2162
Teresa Johnson37687f32016-04-23 04:30:47 +00002163void ModuleBitcodeWriter::writeOperandBundleTags() {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002164 // Write metadata kinds
2165 //
2166 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2167 //
2168 // OPERAND_BUNDLE_TAG - [strchr x N]
2169
2170 SmallVector<StringRef, 8> Tags;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002171 M.getOperandBundleTags(Tags);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002172
2173 if (Tags.empty())
2174 return;
2175
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002176 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002177
2178 SmallVector<uint64_t, 64> Record;
2179
2180 for (auto Tag : Tags) {
2181 Record.append(Tag.begin(), Tag.end());
2182
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002183 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002184 Record.clear();
2185 }
2186
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002187 Stream.ExitBlock();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002188}
2189
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002190void ModuleBitcodeWriter::writeSyncScopeNames() {
2191 SmallVector<StringRef, 8> SSNs;
2192 M.getContext().getSyncScopeNames(SSNs);
2193 if (SSNs.empty())
2194 return;
2195
2196 Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
2197
2198 SmallVector<uint64_t, 64> Record;
2199 for (auto SSN : SSNs) {
2200 Record.append(SSN.begin(), SSN.end());
2201 Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2202 Record.clear();
2203 }
2204
2205 Stream.ExitBlock();
2206}
2207
Jan Wen Voungafaced02012-10-11 20:20:40 +00002208static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2209 if ((int64_t)V >= 0)
2210 Vals.push_back(V << 1);
2211 else
2212 Vals.push_back((-V << 1) | 1);
2213}
2214
Teresa Johnson37687f32016-04-23 04:30:47 +00002215void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2216 bool isGlobal) {
Devang Patel8cca7b42009-08-04 05:01:35 +00002217 if (FirstVal == LastVal) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002218
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002219 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
Devang Patel8cca7b42009-08-04 05:01:35 +00002220
2221 unsigned AggregateAbbrev = 0;
2222 unsigned String8Abbrev = 0;
2223 unsigned CString7Abbrev = 0;
2224 unsigned CString6Abbrev = 0;
2225 // If this is a constant pool for the module, emit module-specific abbrevs.
2226 if (isGlobal) {
2227 // Abbrev for CST_CODE_AGGREGATE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002228 auto Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002229 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2230 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2231 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002232 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002233
2234 // Abbrev for CST_CODE_STRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002235 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002236 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2237 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2238 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002239 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002240 // Abbrev for CST_CODE_CSTRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002241 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002242 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2243 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002245 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002246 // Abbrev for CST_CODE_CSTRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002247 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002248 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2249 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2250 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002251 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002252 }
2253
Devang Patel8cca7b42009-08-04 05:01:35 +00002254 SmallVector<uint64_t, 64> Record;
2255
2256 const ValueEnumerator::ValueList &Vals = VE.getValues();
Craig Topper2617dcc2014-04-15 06:32:26 +00002257 Type *LastTy = nullptr;
Devang Patel8cca7b42009-08-04 05:01:35 +00002258 for (unsigned i = FirstVal; i != LastVal; ++i) {
2259 const Value *V = Vals[i].first;
Chris Lattner52523562007-04-24 00:16:04 +00002260 // If we need to switch types, do so now.
2261 if (V->getType() != LastTy) {
2262 LastTy = V->getType();
2263 Record.push_back(VE.getTypeID(LastTy));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002264 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2265 CONSTANTS_SETTYPE_ABBREV);
Chris Lattner52523562007-04-24 00:16:04 +00002266 Record.clear();
2267 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002268
Chris Lattner52523562007-04-24 00:16:04 +00002269 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
Dale Johannesenfd04c742009-10-13 20:46:56 +00002270 Record.push_back(unsigned(IA->hasSideEffects()) |
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002271 unsigned(IA->isAlignStack()) << 1 |
2272 unsigned(IA->getDialect()&1) << 2);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002273
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002274 // Add the asm string.
2275 const std::string &AsmStr = IA->getAsmString();
2276 Record.push_back(AsmStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002277 Record.append(AsmStr.begin(), AsmStr.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002278
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002279 // Add the constraint string.
2280 const std::string &ConstraintStr = IA->getConstraintString();
2281 Record.push_back(ConstraintStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002282 Record.append(ConstraintStr.begin(), ConstraintStr.end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002283 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002284 Record.clear();
Chris Lattner52523562007-04-24 00:16:04 +00002285 continue;
2286 }
2287 const Constant *C = cast<Constant>(V);
2288 unsigned Code = -1U;
2289 unsigned AbbrevToUse = 0;
2290 if (C->isNullValue()) {
2291 Code = bitc::CST_CODE_NULL;
2292 } else if (isa<UndefValue>(C)) {
2293 Code = bitc::CST_CODE_UNDEF;
2294 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
Bob Wilsone4077362013-09-09 19:14:35 +00002295 if (IV->getBitWidth() <= 64) {
2296 uint64_t V = IV->getSExtValue();
2297 emitSignedInt64(Record, V);
2298 Code = bitc::CST_CODE_INTEGER;
2299 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2300 } else { // Wide integers, > 64 bits in size.
2301 // We have an arbitrary precision integer value to write whose
2302 // bit width is > 64. However, in canonical unsigned integer
2303 // format it is likely that the high bits are going to be zero.
2304 // So, we only write the number of active words.
2305 unsigned NWords = IV->getValue().getActiveWords();
2306 const uint64_t *RawWords = IV->getValue().getRawData();
2307 for (unsigned i = 0; i != NWords; ++i) {
2308 emitSignedInt64(Record, RawWords[i]);
2309 }
2310 Code = bitc::CST_CODE_WIDE_INTEGER;
2311 }
Chris Lattner52523562007-04-24 00:16:04 +00002312 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2313 Code = bitc::CST_CODE_FLOAT;
Chris Lattner229907c2011-07-18 04:54:35 +00002314 Type *Ty = CFP->getType();
Dan Gohman518cda42011-12-17 00:04:22 +00002315 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002316 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
Chris Lattnerfdd87902009-10-05 05:54:46 +00002317 } else if (Ty->isX86_FP80Ty()) {
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002318 // api needed to prevent premature destruction
Dale Johannesen93eefa02009-03-23 21:16:53 +00002319 // bits are not in the same order as a normal i80 APInt, compensate.
Dale Johannesen54306fe2008-10-09 18:53:47 +00002320 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002321 const uint64_t *p = api.getRawData();
Dale Johannesen93eefa02009-03-23 21:16:53 +00002322 Record.push_back((p[1] << 48) | (p[0] >> 16));
2323 Record.push_back(p[0] & 0xffffLL);
Chris Lattnerfdd87902009-10-05 05:54:46 +00002324 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002325 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002326 const uint64_t *p = api.getRawData();
Dale Johannesen245dceb2007-09-11 18:32:33 +00002327 Record.push_back(p[0]);
2328 Record.push_back(p[1]);
Dale Johannesenbdad8092007-08-09 22:51:36 +00002329 } else {
Eugene Zelenko975293f2017-09-07 23:28:24 +00002330 assert(0 && "Unknown FP type!");
Chris Lattner52523562007-04-24 00:16:04 +00002331 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002332 } else if (isa<ConstantDataSequential>(C) &&
2333 cast<ConstantDataSequential>(C)->isString()) {
2334 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2335 // Emit constant strings specially.
2336 unsigned NumElts = Str->getNumElements();
2337 // If this is a null-terminated string, use the denser CSTRING encoding.
2338 if (Str->isCString()) {
2339 Code = bitc::CST_CODE_CSTRING;
2340 --NumElts; // Don't encode the null, which isn't allowed by char6.
2341 } else {
2342 Code = bitc::CST_CODE_STRING;
2343 AbbrevToUse = String8Abbrev;
2344 }
2345 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2346 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2347 for (unsigned i = 0; i != NumElts; ++i) {
2348 unsigned char V = Str->getElementAsInteger(i);
2349 Record.push_back(V);
2350 isCStr7 &= (V & 128) == 0;
2351 if (isCStrChar6)
2352 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2353 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002354
Chris Lattner372dd1e2012-01-30 00:51:16 +00002355 if (isCStrChar6)
2356 AbbrevToUse = CString6Abbrev;
2357 else if (isCStr7)
2358 AbbrevToUse = CString7Abbrev;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002359 } else if (const ConstantDataSequential *CDS =
Chris Lattner372dd1e2012-01-30 00:51:16 +00002360 dyn_cast<ConstantDataSequential>(C)) {
Chris Lattner5d917072012-01-30 07:36:01 +00002361 Code = bitc::CST_CODE_DATA;
Chris Lattner372dd1e2012-01-30 00:51:16 +00002362 Type *EltTy = CDS->getType()->getElementType();
2363 if (isa<IntegerType>(EltTy)) {
2364 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2365 Record.push_back(CDS->getElementAsInteger(i));
Chris Lattner372dd1e2012-01-30 00:51:16 +00002366 } else {
Justin Bognera43eacb2016-01-06 22:31:32 +00002367 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2368 Record.push_back(
2369 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002370 }
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00002371 } else if (isa<ConstantAggregate>(C)) {
Chris Lattner52523562007-04-24 00:16:04 +00002372 Code = bitc::CST_CODE_AGGREGATE;
Pete Cooper125ad172015-06-25 20:51:38 +00002373 for (const Value *Op : C->operands())
2374 Record.push_back(VE.getValueID(Op));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002375 AbbrevToUse = AggregateAbbrev;
Chris Lattner52523562007-04-24 00:16:04 +00002376 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002377 switch (CE->getOpcode()) {
2378 default:
2379 if (Instruction::isCast(CE->getOpcode())) {
2380 Code = bitc::CST_CODE_CE_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002381 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002382 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2383 Record.push_back(VE.getValueID(C->getOperand(0)));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002384 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002385 } else {
2386 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2387 Code = bitc::CST_CODE_CE_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002388 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002389 Record.push_back(VE.getValueID(C->getOperand(0)));
2390 Record.push_back(VE.getValueID(C->getOperand(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002391 uint64_t Flags = getOptimizationFlags(CE);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002392 if (Flags != 0)
2393 Record.push_back(Flags);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002394 }
2395 break;
Cameron McInallycbde0d92018-11-13 18:15:47 +00002396 case Instruction::FNeg: {
2397 assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2398 Code = bitc::CST_CODE_CE_UNOP;
2399 Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2400 Record.push_back(VE.getValueID(C->getOperand(0)));
2401 uint64_t Flags = getOptimizationFlags(CE);
2402 if (Flags != 0)
2403 Record.push_back(Flags);
2404 break;
2405 }
David Blaikieb9263572015-03-13 21:03:36 +00002406 case Instruction::GetElementPtr: {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002407 Code = bitc::CST_CODE_CE_GEP;
David Blaikieb9263572015-03-13 21:03:36 +00002408 const auto *GO = cast<GEPOperator>(C);
David Blaikieb9263572015-03-13 21:03:36 +00002409 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
Peter Collingbourned93620b2016-11-10 22:34:55 +00002410 if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2411 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2412 Record.push_back((*Idx << 1) | GO->isInBounds());
2413 } else if (GO->isInBounds())
2414 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002415 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2416 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2417 Record.push_back(VE.getValueID(C->getOperand(i)));
2418 }
2419 break;
David Blaikieb9263572015-03-13 21:03:36 +00002420 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002421 case Instruction::Select:
2422 Code = bitc::CST_CODE_CE_SELECT;
2423 Record.push_back(VE.getValueID(C->getOperand(0)));
2424 Record.push_back(VE.getValueID(C->getOperand(1)));
2425 Record.push_back(VE.getValueID(C->getOperand(2)));
2426 break;
2427 case Instruction::ExtractElement:
2428 Code = bitc::CST_CODE_CE_EXTRACTELT;
2429 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2430 Record.push_back(VE.getValueID(C->getOperand(0)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002431 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002432 Record.push_back(VE.getValueID(C->getOperand(1)));
2433 break;
2434 case Instruction::InsertElement:
2435 Code = bitc::CST_CODE_CE_INSERTELT;
2436 Record.push_back(VE.getValueID(C->getOperand(0)));
2437 Record.push_back(VE.getValueID(C->getOperand(1)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002438 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002439 Record.push_back(VE.getValueID(C->getOperand(2)));
2440 break;
2441 case Instruction::ShuffleVector:
Nate Begeman94aa38d2009-02-12 21:28:33 +00002442 // If the return type and argument types are the same, this is a
2443 // standard shufflevector instruction. If the types are different,
2444 // then the shuffle is widening or truncating the input vectors, and
2445 // the argument type must also be encoded.
2446 if (C->getType() == C->getOperand(0)->getType()) {
2447 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2448 } else {
2449 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2450 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2451 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002452 Record.push_back(VE.getValueID(C->getOperand(0)));
2453 Record.push_back(VE.getValueID(C->getOperand(1)));
2454 Record.push_back(VE.getValueID(C->getOperand(2)));
2455 break;
2456 case Instruction::ICmp:
2457 case Instruction::FCmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002458 Code = bitc::CST_CODE_CE_CMP;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002459 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2460 Record.push_back(VE.getValueID(C->getOperand(0)));
2461 Record.push_back(VE.getValueID(C->getOperand(1)));
2462 Record.push_back(CE->getPredicate());
2463 break;
2464 }
Chris Lattnerf540d742009-10-28 05:24:40 +00002465 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
Chris Lattnerf540d742009-10-28 05:24:40 +00002466 Code = bitc::CST_CODE_BLOCKADDRESS;
2467 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2468 Record.push_back(VE.getValueID(BA->getFunction()));
2469 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
Chris Lattner52523562007-04-24 00:16:04 +00002470 } else {
Dan Gohman47dc8fd2010-07-21 21:18:37 +00002471#ifndef NDEBUG
2472 C->dump();
2473#endif
Torok Edwinfbcc6632009-07-14 16:55:14 +00002474 llvm_unreachable("Unknown constant!");
Chris Lattner52523562007-04-24 00:16:04 +00002475 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002476 Stream.EmitRecord(Code, Record, AbbrevToUse);
Chris Lattner52523562007-04-24 00:16:04 +00002477 Record.clear();
2478 }
2479
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002480 Stream.ExitBlock();
Chris Lattner52523562007-04-24 00:16:04 +00002481}
2482
Teresa Johnson37687f32016-04-23 04:30:47 +00002483void ModuleBitcodeWriter::writeModuleConstants() {
Chris Lattner52523562007-04-24 00:16:04 +00002484 const ValueEnumerator::ValueList &Vals = VE.getValues();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002485
Chris Lattner52523562007-04-24 00:16:04 +00002486 // Find the first constant to emit, which is the first non-globalvalue value.
2487 // We know globalvalues have been emitted by WriteModuleInfo.
2488 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2489 if (!isa<GlobalValue>(Vals[i].first)) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002490 writeConstants(i, Vals.size(), true);
Chris Lattner52523562007-04-24 00:16:04 +00002491 return;
2492 }
2493 }
2494}
Chris Lattner215e9cd2007-04-23 20:35:01 +00002495
Teresa Johnson37687f32016-04-23 04:30:47 +00002496/// pushValueAndType - The file has to encode both the value and type id for
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002497/// many values, because we need to know what type to create for forward
2498/// references. However, most operands are not forward references, so this type
2499/// field is not needed.
2500///
2501/// This function adds V's value ID to Vals. If the value ID is higher than the
2502/// instruction ID, then it is a forward reference, and it also includes the
Jan Wen Voungafaced02012-10-11 20:20:40 +00002503/// type ID. The value ID that is written is encoded relative to the InstID.
Teresa Johnson37687f32016-04-23 04:30:47 +00002504bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2505 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002506 unsigned ValID = VE.getValueID(V);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002507 // Make encoding relative to the InstID.
2508 Vals.push_back(InstID - ValID);
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002509 if (ValID >= InstID) {
2510 Vals.push_back(VE.getTypeID(V->getType()));
2511 return true;
2512 }
2513 return false;
2514}
2515
Teresa Johnson37687f32016-04-23 04:30:47 +00002516void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2517 unsigned InstID) {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002518 SmallVector<unsigned, 64> Record;
2519 LLVMContext &C = CS.getInstruction()->getContext();
2520
2521 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
Sanjoy Das54c3ca62015-11-07 01:56:04 +00002522 const auto &Bundle = CS.getOperandBundleAt(i);
Sanjoy Dasb9ca6dc2015-11-10 20:13:15 +00002523 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002524
2525 for (auto &Input : Bundle.Inputs)
Teresa Johnson37687f32016-04-23 04:30:47 +00002526 pushValueAndType(Input, InstID, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002527
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002528 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002529 Record.clear();
2530 }
2531}
2532
Teresa Johnson37687f32016-04-23 04:30:47 +00002533/// pushValue - Like pushValueAndType, but where the type of the value is
Jan Wen Voungafaced02012-10-11 20:20:40 +00002534/// omitted (perhaps it was already encoded in an earlier operand).
Teresa Johnson37687f32016-04-23 04:30:47 +00002535void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2536 SmallVectorImpl<unsigned> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002537 unsigned ValID = VE.getValueID(V);
2538 Vals.push_back(InstID - ValID);
2539}
2540
Teresa Johnson37687f32016-04-23 04:30:47 +00002541void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2542 SmallVectorImpl<uint64_t> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002543 unsigned ValID = VE.getValueID(V);
2544 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2545 emitSignedInt64(Vals, diff);
2546}
2547
Chris Lattnere6e364c2007-04-26 05:53:54 +00002548/// WriteInstruction - Emit an instruction to the specified stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00002549void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2550 unsigned InstID,
2551 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnere6e364c2007-04-26 05:53:54 +00002552 unsigned Code = 0;
2553 unsigned AbbrevToUse = 0;
Devang Patelaf206b82009-09-18 19:26:43 +00002554 VE.setInstructionID(&I);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002555 switch (I.getOpcode()) {
2556 default:
2557 if (Instruction::isCast(I.getOpcode())) {
Chris Lattner0a603252007-05-01 02:13:26 +00002558 Code = bitc::FUNC_CODE_INST_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002559 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002560 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002561 Vals.push_back(VE.getTypeID(I.getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002562 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
Chris Lattnere6e364c2007-04-26 05:53:54 +00002563 } else {
2564 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
Chris Lattner9f35f912007-05-02 04:26:36 +00002565 Code = bitc::FUNC_CODE_INST_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002566 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002567 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
Teresa Johnson37687f32016-04-23 04:30:47 +00002568 pushValue(I.getOperand(1), InstID, Vals);
2569 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2570 uint64_t Flags = getOptimizationFlags(&I);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002571 if (Flags != 0) {
2572 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2573 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2574 Vals.push_back(Flags);
2575 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002576 }
2577 break;
Cameron McInallycbde0d92018-11-13 18:15:47 +00002578 case Instruction::FNeg: {
2579 Code = bitc::FUNC_CODE_INST_UNOP;
2580 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2581 AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
2582 Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
2583 uint64_t Flags = getOptimizationFlags(&I);
2584 if (Flags != 0) {
2585 if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
2586 AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
2587 Vals.push_back(Flags);
2588 }
2589 break;
2590 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00002591 case Instruction::GetElementPtr: {
Chris Lattner0a603252007-05-01 02:13:26 +00002592 Code = bitc::FUNC_CODE_INST_GEP;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002593 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2594 auto &GEPInst = cast<GetElementPtrInst>(I);
2595 Vals.push_back(GEPInst.isInBounds());
2596 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002597 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002598 pushValueAndType(I.getOperand(i), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002599 break;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002600 }
Dan Gohmanca0256a2008-05-31 19:11:15 +00002601 case Instruction::ExtractValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002602 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002603 pushValueAndType(I.getOperand(0), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002604 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002605 Vals.append(EVI->idx_begin(), EVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002606 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002607 }
2608 case Instruction::InsertValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002609 Code = bitc::FUNC_CODE_INST_INSERTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002610 pushValueAndType(I.getOperand(0), InstID, Vals);
2611 pushValueAndType(I.getOperand(1), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002612 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002613 Vals.append(IVI->idx_begin(), IVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002614 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002615 }
Chris Lattner0a603252007-05-01 02:13:26 +00002616 case Instruction::Select:
Dan Gohmanc5d28922008-09-16 01:01:33 +00002617 Code = bitc::FUNC_CODE_INST_VSELECT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002618 pushValueAndType(I.getOperand(1), InstID, Vals);
2619 pushValue(I.getOperand(2), InstID, Vals);
2620 pushValueAndType(I.getOperand(0), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002621 break;
2622 case Instruction::ExtractElement:
2623 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002624 pushValueAndType(I.getOperand(0), InstID, Vals);
2625 pushValueAndType(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002626 break;
2627 case Instruction::InsertElement:
2628 Code = bitc::FUNC_CODE_INST_INSERTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002629 pushValueAndType(I.getOperand(0), InstID, Vals);
2630 pushValue(I.getOperand(1), InstID, Vals);
2631 pushValueAndType(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002632 break;
2633 case Instruction::ShuffleVector:
2634 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002635 pushValueAndType(I.getOperand(0), InstID, Vals);
2636 pushValue(I.getOperand(1), InstID, Vals);
2637 pushValue(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002638 break;
2639 case Instruction::ICmp:
James Molloy88eb5352015-07-10 12:52:00 +00002640 case Instruction::FCmp: {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002641 // compare returning Int1Ty or vector of Int1Ty
2642 Code = bitc::FUNC_CODE_INST_CMP2;
Teresa Johnson37687f32016-04-23 04:30:47 +00002643 pushValueAndType(I.getOperand(0), InstID, Vals);
2644 pushValue(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002645 Vals.push_back(cast<CmpInst>(I).getPredicate());
Teresa Johnson37687f32016-04-23 04:30:47 +00002646 uint64_t Flags = getOptimizationFlags(&I);
James Molloy88eb5352015-07-10 12:52:00 +00002647 if (Flags != 0)
2648 Vals.push_back(Flags);
Chris Lattner0a603252007-05-01 02:13:26 +00002649 break;
James Molloy88eb5352015-07-10 12:52:00 +00002650 }
Chris Lattner0a603252007-05-01 02:13:26 +00002651
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002652 case Instruction::Ret:
Devang Patelbbfd8742008-02-26 01:29:32 +00002653 {
2654 Code = bitc::FUNC_CODE_INST_RET;
2655 unsigned NumOperands = I.getNumOperands();
Devang Patelbbfd8742008-02-26 01:29:32 +00002656 if (NumOperands == 0)
2657 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2658 else if (NumOperands == 1) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002659 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Devang Patelbbfd8742008-02-26 01:29:32 +00002660 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2661 } else {
2662 for (unsigned i = 0, e = NumOperands; i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002663 pushValueAndType(I.getOperand(i), InstID, Vals);
Devang Patelbbfd8742008-02-26 01:29:32 +00002664 }
2665 }
Chris Lattner0a603252007-05-01 02:13:26 +00002666 break;
2667 case Instruction::Br:
Gabor Greif1933b002009-01-30 18:27:21 +00002668 {
2669 Code = bitc::FUNC_CODE_INST_BR;
David Blaikieb78e9e52013-02-11 01:16:51 +00002670 const BranchInst &II = cast<BranchInst>(I);
Gabor Greif1933b002009-01-30 18:27:21 +00002671 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2672 if (II.isConditional()) {
2673 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002674 pushValue(II.getCondition(), InstID, Vals);
Gabor Greif1933b002009-01-30 18:27:21 +00002675 }
Chris Lattner0a603252007-05-01 02:13:26 +00002676 }
2677 break;
2678 case Instruction::Switch:
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002679 {
2680 Code = bitc::FUNC_CODE_INST_SWITCH;
David Blaikieb78e9e52013-02-11 01:16:51 +00002681 const SwitchInst &SI = cast<SwitchInst>(I);
Bob Wilsone4077362013-09-09 19:14:35 +00002682 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002683 pushValue(SI.getCondition(), InstID, Vals);
Bob Wilsone4077362013-09-09 19:14:35 +00002684 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
Chandler Carruth927d8e62017-04-12 07:27:28 +00002685 for (auto Case : SI.cases()) {
Sanjay Patel225d65f2015-11-13 16:21:23 +00002686 Vals.push_back(VE.getValueID(Case.getCaseValue()));
2687 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002688 }
2689 }
Chris Lattner0a603252007-05-01 02:13:26 +00002690 break;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00002691 case Instruction::IndirectBr:
2692 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
Chris Lattner3ed871f2009-10-27 19:13:16 +00002693 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Jan Wen Voungafaced02012-10-11 20:20:40 +00002694 // Encode the address operand as relative, but not the basic blocks.
Teresa Johnson37687f32016-04-23 04:30:47 +00002695 pushValue(I.getOperand(0), InstID, Vals);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002696 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
Chris Lattner3ed871f2009-10-27 19:13:16 +00002697 Vals.push_back(VE.getValueID(I.getOperand(i)));
2698 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002699
Chris Lattnerb811e952007-05-01 07:03:37 +00002700 case Instruction::Invoke: {
Gabor Greif4b79e472009-01-16 18:40:27 +00002701 const InvokeInst *II = cast<InvokeInst>(&I);
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002702 const Value *Callee = II->getCalledValue();
2703 FunctionType *FTy = II->getFunctionType();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002704
2705 if (II->hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002706 writeOperandBundles(II, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002707
Chris Lattner0a603252007-05-01 02:13:26 +00002708 Code = bitc::FUNC_CODE_INST_INVOKE;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002709
Reid Klecknerb4a2d182017-04-24 20:38:30 +00002710 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002711 Vals.push_back(II->getCallingConv() | 1 << 13);
Gabor Greif6ecd6f42009-01-07 22:39:29 +00002712 Vals.push_back(VE.getValueID(II->getNormalDest()));
2713 Vals.push_back(VE.getValueID(II->getUnwindDest()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002714 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002715 pushValueAndType(Callee, InstID, Vals);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002716
Chris Lattner0a603252007-05-01 02:13:26 +00002717 // Emit value #'s for the fixed parameters.
Chris Lattner0a603252007-05-01 02:13:26 +00002718 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002719 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
Chris Lattner0a603252007-05-01 02:13:26 +00002720
2721 // Emit type/value pairs for varargs params.
2722 if (FTy->isVarArg()) {
Mehdi Amini7cf63822016-09-19 21:27:04 +00002723 for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002724 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002725 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
Chris Lattner0a603252007-05-01 02:13:26 +00002726 }
2727 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002728 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00002729 case Instruction::Resume:
2730 Code = bitc::FUNC_CODE_INST_RESUME;
Teresa Johnson37687f32016-04-23 04:30:47 +00002731 pushValueAndType(I.getOperand(0), InstID, Vals);
Bill Wendlingf891bf82011-07-31 06:30:59 +00002732 break;
David Majnemer654e1302015-07-31 17:58:14 +00002733 case Instruction::CleanupRet: {
2734 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2735 const auto &CRI = cast<CleanupReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002736 pushValue(CRI.getCleanupPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002737 if (CRI.hasUnwindDest())
2738 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2739 break;
2740 }
2741 case Instruction::CatchRet: {
2742 Code = bitc::FUNC_CODE_INST_CATCHRET;
2743 const auto &CRI = cast<CatchReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002744 pushValue(CRI.getCatchPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002745 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2746 break;
2747 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00002748 case Instruction::CleanupPad:
David Majnemer654e1302015-07-31 17:58:14 +00002749 case Instruction::CatchPad: {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002750 const auto &FuncletPad = cast<FuncletPadInst>(I);
2751 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2752 : bitc::FUNC_CODE_INST_CLEANUPPAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002753 pushValue(FuncletPad.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002754
2755 unsigned NumArgOperands = FuncletPad.getNumArgOperands();
David Majnemer654e1302015-07-31 17:58:14 +00002756 Vals.push_back(NumArgOperands);
2757 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
Teresa Johnson37687f32016-04-23 04:30:47 +00002758 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002759 break;
2760 }
2761 case Instruction::CatchSwitch: {
2762 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2763 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2764
Teresa Johnson37687f32016-04-23 04:30:47 +00002765 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002766
2767 unsigned NumHandlers = CatchSwitch.getNumHandlers();
2768 Vals.push_back(NumHandlers);
2769 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2770 Vals.push_back(VE.getValueID(CatchPadBB));
2771
2772 if (CatchSwitch.hasUnwindDest())
2773 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
David Majnemer654e1302015-07-31 17:58:14 +00002774 break;
2775 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002776 case Instruction::Unreachable:
2777 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
Chris Lattnercc6d4c92007-05-06 01:28:01 +00002778 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002779 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002780
Jay Foad372ad642011-06-20 14:18:48 +00002781 case Instruction::PHI: {
2782 const PHINode &PN = cast<PHINode>(I);
Chris Lattner0a603252007-05-01 02:13:26 +00002783 Code = bitc::FUNC_CODE_INST_PHI;
Jan Wen Voungafaced02012-10-11 20:20:40 +00002784 // With the newer instruction encoding, forward references could give
2785 // negative valued IDs. This is most common for PHIs, so we use
2786 // signed VBRs.
2787 SmallVector<uint64_t, 128> Vals64;
2788 Vals64.push_back(VE.getTypeID(PN.getType()));
Jay Foad372ad642011-06-20 14:18:48 +00002789 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002790 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002791 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
Jay Foad372ad642011-06-20 14:18:48 +00002792 }
Jan Wen Voungafaced02012-10-11 20:20:40 +00002793 // Emit a Vals64 vector and exit.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002794 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002795 Vals64.clear();
2796 return;
Jay Foad372ad642011-06-20 14:18:48 +00002797 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002798
Bill Wendlingfae14752011-08-12 20:24:12 +00002799 case Instruction::LandingPad: {
2800 const LandingPadInst &LP = cast<LandingPadInst>(I);
2801 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2802 Vals.push_back(VE.getTypeID(LP.getType()));
Bill Wendlingfae14752011-08-12 20:24:12 +00002803 Vals.push_back(LP.isCleanup());
2804 Vals.push_back(LP.getNumClauses());
2805 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2806 if (LP.isCatch(I))
2807 Vals.push_back(LandingPadInst::Catch);
2808 else
2809 Vals.push_back(LandingPadInst::Filter);
Teresa Johnson37687f32016-04-23 04:30:47 +00002810 pushValueAndType(LP.getClause(I), InstID, Vals);
Bill Wendlingfae14752011-08-12 20:24:12 +00002811 }
2812 break;
2813 }
2814
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002815 case Instruction::Alloca: {
Chris Lattner0a603252007-05-01 02:13:26 +00002816 Code = bitc::FUNC_CODE_INST_ALLOCA;
David Blaikiebdb49102015-04-28 16:51:01 +00002817 const AllocaInst &AI = cast<AllocaInst>(I);
2818 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
Dan Gohman9da5bb02010-05-28 01:38:28 +00002819 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002820 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002821 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2822 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2823 "not enough bits for maximum alignment");
2824 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2825 AlignRecord |= AI.isUsedWithInAlloca() << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00002826 AlignRecord |= 1 << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00002827 AlignRecord |= AI.isSwiftError() << 7;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002828 Vals.push_back(AlignRecord);
Chris Lattner0a603252007-05-01 02:13:26 +00002829 break;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002830 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002831
Chris Lattner0a603252007-05-01 02:13:26 +00002832 case Instruction::Load:
Eli Friedman59b66882011-08-09 23:02:53 +00002833 if (cast<LoadInst>(I).isAtomic()) {
2834 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002835 pushValueAndType(I.getOperand(0), InstID, Vals);
Eli Friedman59b66882011-08-09 23:02:53 +00002836 } else {
2837 Code = bitc::FUNC_CODE_INST_LOAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002838 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
Eli Friedman59b66882011-08-09 23:02:53 +00002839 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2840 }
David Blaikie85035652015-02-25 01:07:20 +00002841 Vals.push_back(VE.getTypeID(I.getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002842 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2843 Vals.push_back(cast<LoadInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002844 if (cast<LoadInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002845 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002846 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
Eli Friedman59b66882011-08-09 23:02:53 +00002847 }
Chris Lattner0a603252007-05-01 02:13:26 +00002848 break;
2849 case Instruction::Store:
Eli Friedman59b66882011-08-09 23:02:53 +00002850 if (cast<StoreInst>(I).isAtomic())
2851 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2852 else
2853 Code = bitc::FUNC_CODE_INST_STORE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002854 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2855 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
Chris Lattner0a603252007-05-01 02:13:26 +00002856 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2857 Vals.push_back(cast<StoreInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002858 if (cast<StoreInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002859 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002860 Vals.push_back(
2861 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
Eli Friedman59b66882011-08-09 23:02:53 +00002862 }
Chris Lattner0a603252007-05-01 02:13:26 +00002863 break;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002864 case Instruction::AtomicCmpXchg:
2865 Code = bitc::FUNC_CODE_INST_CMPXCHG;
Teresa Johnson37687f32016-04-23 04:30:47 +00002866 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2867 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2868 pushValue(I.getOperand(2), InstID, Vals); // newval.
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002869 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002870 Vals.push_back(
2871 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2872 Vals.push_back(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002873 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002874 Vals.push_back(
2875 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
Tim Northover420a2162014-06-13 14:24:07 +00002876 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002877 break;
2878 case Instruction::AtomicRMW:
2879 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
Teresa Johnson37687f32016-04-23 04:30:47 +00002880 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2881 pushValue(I.getOperand(1), InstID, Vals); // val.
2882 Vals.push_back(
2883 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002884 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002885 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2886 Vals.push_back(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002887 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002888 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002889 case Instruction::Fence:
2890 Code = bitc::FUNC_CODE_INST_FENCE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002891 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002892 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
Eli Friedmanfee02c62011-07-25 23:16:38 +00002893 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002894 case Instruction::Call: {
Gabor Greife9afee22010-06-26 09:35:09 +00002895 const CallInst &CI = cast<CallInst>(I);
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002896 FunctionType *FTy = CI.getFunctionType();
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002897
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002898 if (CI.hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002899 writeOperandBundles(&CI, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002900
Chris Lattnerc44070802011-06-17 18:17:37 +00002901 Code = bitc::FUNC_CODE_INST_CALL;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002902
Reid Klecknerb4a2d182017-04-24 20:38:30 +00002903 Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002904
Teresa Johnson37687f32016-04-23 04:30:47 +00002905 unsigned Flags = getOptimizationFlags(&I);
Akira Hatanaka97cb3972015-11-07 02:48:49 +00002906 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2907 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2908 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2909 1 << bitc::CALL_EXPLICIT_TYPE |
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002910 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2911 unsigned(Flags != 0) << bitc::CALL_FMF);
2912 if (Flags != 0)
2913 Vals.push_back(Flags);
2914
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002915 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002916 pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002917
Chris Lattner0a603252007-05-01 02:13:26 +00002918 // Emit value #'s for the fixed parameters.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002919 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2920 // Check for labels (can happen with asm labels).
2921 if (FTy->getParamType(i)->isLabelTy())
2922 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2923 else
Teresa Johnson37687f32016-04-23 04:30:47 +00002924 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002925 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002926
Chris Lattnerb811e952007-05-01 07:03:37 +00002927 // Emit type/value pairs for varargs params.
2928 if (FTy->isVarArg()) {
Gabor Greife9afee22010-06-26 09:35:09 +00002929 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002930 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002931 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
Chris Lattner0a603252007-05-01 02:13:26 +00002932 }
2933 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002934 }
Chris Lattner0a603252007-05-01 02:13:26 +00002935 case Instruction::VAArg:
2936 Code = bitc::FUNC_CODE_INST_VAARG;
2937 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
Teresa Johnson37687f32016-04-23 04:30:47 +00002938 pushValue(I.getOperand(0), InstID, Vals); // valist.
Chris Lattner0a603252007-05-01 02:13:26 +00002939 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2940 break;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002941 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002942
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002943 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002944 Vals.clear();
2945}
2946
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002947/// Write a GlobalValue VST to the module. The purpose of this data structure is
2948/// to allow clients to efficiently find the function body.
2949void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
2950 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
2951 // Get the offset of the VST we are writing, and backpatch it into
2952 // the VST forward declaration record.
2953 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2954 // The BitcodeStartBit was the stream offset of the identification block.
2955 VSTOffset -= bitcodeStartBit();
2956 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2957 // Note that we add 1 here because the offset is relative to one word
2958 // before the start of the identification block, which was historically
2959 // always the start of the regular bitcode header.
2960 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002961
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002962 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
Chris Lattner2eae59f2007-05-04 20:34:50 +00002963
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002964 auto Abbv = std::make_shared<BitCodeAbbrev>();
2965 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2966 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2967 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2968 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnsonff642b92015-09-17 20:12:00 +00002969
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002970 for (const Function &F : M) {
2971 uint64_t Record[2];
Teresa Johnsonff642b92015-09-17 20:12:00 +00002972
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002973 if (F.isDeclaration())
2974 continue;
Teresa Johnsoncd21a642016-07-17 14:47:01 +00002975
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002976 Record[0] = VE.getValueID(&F);
2977
2978 // Save the word offset of the function (from the start of the
2979 // actual bitcode written to the stream).
2980 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
2981 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2982 // Note that we add 1 here because the offset is relative to one word
2983 // before the start of the identification block, which was historically
2984 // always the start of the regular bitcode header.
2985 Record[1] = BitcodeIndex / 32 + 1;
2986
2987 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002988 }
2989
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002990 Stream.ExitBlock();
2991}
2992
2993/// Emit names for arguments, instructions and basic blocks in a function.
2994void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
2995 const ValueSymbolTable &VST) {
2996 if (VST.empty())
2997 return;
2998
2999 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3000
Chris Lattnerfb6f9402007-05-01 02:14:57 +00003001 // FIXME: Set up the abbrev, we know how many values there are!
3002 // FIXME: We know if the type names can use 7-bit ascii.
Teresa Johnsoncd21a642016-07-17 14:47:01 +00003003 SmallVector<uint64_t, 64> NameVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003004
Yaron Keren001e2e42015-08-10 07:04:29 +00003005 for (const ValueName &Name : VST) {
Chris Lattner4d925982007-05-04 20:52:02 +00003006 // Figure out the encoding to use for the name.
David Blaikieb6b42e02017-06-02 17:24:26 +00003007 StringEncoding Bits = getStringEncoding(Name.getKey());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003008
Chris Lattnera0987962007-05-04 21:31:13 +00003009 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003010 NameVals.push_back(VE.getValueID(Name.getValue()));
3011
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003012 // VST_CODE_ENTRY: [valueid, namechar x N]
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003013 // VST_CODE_BBENTRY: [bbid, namechar x N]
Chris Lattner6be58c62007-05-03 22:18:21 +00003014 unsigned Code;
Yaron Keren001e2e42015-08-10 07:04:29 +00003015 if (isa<BasicBlock>(Name.getValue())) {
Bill Wendling35a9c3c2011-04-10 23:18:04 +00003016 Code = bitc::VST_CODE_BBENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00003017 if (Bits == SE_Char6)
Bill Wendling35a9c3c2011-04-10 23:18:04 +00003018 AbbrevToUse = VST_BBENTRY_6_ABBREV;
Chris Lattner6be58c62007-05-03 22:18:21 +00003019 } else {
3020 Code = bitc::VST_CODE_ENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00003021 if (Bits == SE_Char6)
Chris Lattnere760d6f2007-05-05 01:26:50 +00003022 AbbrevToUse = VST_ENTRY_6_ABBREV;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00003023 else if (Bits == SE_Fixed7)
Chris Lattnere760d6f2007-05-05 01:26:50 +00003024 AbbrevToUse = VST_ENTRY_7_ABBREV;
Chris Lattner6be58c62007-05-03 22:18:21 +00003025 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003026
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003027 for (const auto P : Name.getKey())
3028 NameVals.push_back((unsigned char)P);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003029
Chris Lattnerfb6f9402007-05-01 02:14:57 +00003030 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003031 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
Chris Lattnerfb6f9402007-05-01 02:14:57 +00003032 NameVals.clear();
3033 }
Chris Lattnerfb6f9402007-05-01 02:14:57 +00003034
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003035 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003036}
3037
Teresa Johnson37687f32016-04-23 04:30:47 +00003038void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003039 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3040 unsigned Code;
3041 if (isa<BasicBlock>(Order.V))
3042 Code = bitc::USELIST_CODE_BB;
3043 else
3044 Code = bitc::USELIST_CODE_DEFAULT;
3045
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00003046 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003047 Record.push_back(VE.getValueID(Order.V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003048 Stream.EmitRecord(Code, Record);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003049}
3050
Teresa Johnson37687f32016-04-23 04:30:47 +00003051void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00003052 assert(VE.shouldPreserveUseListOrder() &&
3053 "Expected to be preserving use-list order");
3054
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003055 auto hasMore = [&]() {
3056 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3057 };
3058 if (!hasMore())
3059 // Nothing to do.
3060 return;
3061
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003062 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003063 while (hasMore()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00003064 writeUseList(std::move(VE.UseListOrders.back()));
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003065 VE.UseListOrders.pop_back();
3066 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003067 Stream.ExitBlock();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003068}
3069
Teresa Johnson403a7872015-10-04 14:33:43 +00003070/// Emit a function body to the module stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00003071void ModuleBitcodeWriter::writeFunction(
3072 const Function &F,
3073 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00003074 // Save the bitcode index of the start of this function block for recording
3075 // in the VST.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003076 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003077
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003078 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
Chad Rosier6a11b642011-06-03 17:02:19 +00003079 VE.incorporateFunction(F);
Chris Lattnere6e364c2007-04-26 05:53:54 +00003080
3081 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003082
Chris Lattnere6e364c2007-04-26 05:53:54 +00003083 // Emit the number of basic blocks, so the reader can create them ahead of
3084 // time.
3085 Vals.push_back(VE.getBasicBlocks().size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003086 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
Chris Lattnere6e364c2007-04-26 05:53:54 +00003087 Vals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003088
Chris Lattnere6e364c2007-04-26 05:53:54 +00003089 // If there are function-local constants, emit them now.
3090 unsigned CstStart, CstEnd;
3091 VE.getFunctionConstantRange(CstStart, CstEnd);
Teresa Johnson37687f32016-04-23 04:30:47 +00003092 writeConstants(CstStart, CstEnd, false);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003093
Victor Hernandez6c730de2010-01-14 01:50:08 +00003094 // If there is function-local metadata, emit it now.
Teresa Johnson37687f32016-04-23 04:30:47 +00003095 writeFunctionMetadata(F);
Victor Hernandez6c730de2010-01-14 01:50:08 +00003096
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003097 // Keep a running idea of what the instruction ID is.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003098 unsigned InstID = CstEnd;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003099
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003100 bool NeedsMetadataAttachment = F.hasMetadata();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003101
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003102 DILocation *LastDL = nullptr;
Chris Lattnere6e364c2007-04-26 05:53:54 +00003103 // Finally, emit all the instructions, in order.
Nick Lewycky4d43d3c2008-04-25 16:53:59 +00003104 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003105 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
3106 I != E; ++I) {
Teresa Johnson37687f32016-04-23 04:30:47 +00003107 writeInstruction(*I, InstID, Vals);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003108
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00003109 if (!I->getType()->isVoidTy())
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003110 ++InstID;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003111
Chris Lattner07d09ed2010-04-03 02:17:50 +00003112 // If the instruction has metadata, write a metadata attachment later.
3113 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003114
Chris Lattner07d09ed2010-04-03 02:17:50 +00003115 // If the instruction has a debug location, emit it.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003116 DILocation *DL = I->getDebugLoc();
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00003117 if (!DL)
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003118 continue;
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003119
3120 if (DL == LastDL) {
Chris Lattner07d09ed2010-04-03 02:17:50 +00003121 // Just repeat the same debug loc as last time.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003122 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003123 continue;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003124 }
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003125
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00003126 Vals.push_back(DL->getLine());
3127 Vals.push_back(DL->getColumn());
3128 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3129 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
Calixte Denizeteb7f6022018-09-20 08:53:06 +00003130 Vals.push_back(DL->isImplicitCode());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003131 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003132 Vals.clear();
Duncan P. N. Exon Smith538ef562015-05-06 22:51:12 +00003133
3134 LastDL = DL;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003135 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003136
Chris Lattnerfb6f9402007-05-01 02:14:57 +00003137 // Emit names for all the instructions etc.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00003138 if (auto *Symtab = F.getValueSymbolTable())
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003139 writeFunctionLevelValueSymbolTable(*Symtab);
Devang Patelaf206b82009-09-18 19:26:43 +00003140
Chris Lattner07d09ed2010-04-03 02:17:50 +00003141 if (NeedsMetadataAttachment)
Peter Collingbournecceae7f2016-05-31 23:01:54 +00003142 writeFunctionMetadataAttachment(F);
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00003143 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00003144 writeUseListBlock(&F);
Chad Rosier6a11b642011-06-03 17:02:19 +00003145 VE.purgeFunction();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003146 Stream.ExitBlock();
Chris Lattner831d4202007-04-26 03:27:58 +00003147}
3148
Chris Lattner702658c2007-05-04 18:26:27 +00003149// Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00003150void ModuleBitcodeWriter::writeBlockInfo() {
Chris Lattner702658c2007-05-04 18:26:27 +00003151 // We only want to emit block info records for blocks that have multiple
Jan Wen Voungafaced02012-10-11 20:20:40 +00003152 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
Jan Wen Voung8c9e9412012-10-11 21:45:16 +00003153 // Other blocks can define their abbrevs inline.
Peter Collingbourned3a6c702016-11-01 01:18:57 +00003154 Stream.EnterBlockInfoBlock();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003155
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003156 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003157 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00003158 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3159 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3160 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3161 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003162 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003163 VST_ENTRY_8_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003164 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00003165 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003166
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003167 { // 7-bit fixed width VST_CODE_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003168 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00003169 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3171 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3172 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003173 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003174 VST_ENTRY_7_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003175 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00003176 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003177 { // 6-bit char6 VST_CODE_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003178 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnere760d6f2007-05-05 01:26:50 +00003179 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3180 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3181 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3182 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003183 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003184 VST_ENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003185 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnere760d6f2007-05-05 01:26:50 +00003186 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003187 { // 6-bit char6 VST_CODE_BBENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003188 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00003189 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3190 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3191 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chris Lattnere760d6f2007-05-05 01:26:50 +00003192 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003193 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003194 VST_BBENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003195 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00003196 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00003197
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003198 { // SETTYPE abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003199 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003200 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3201 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
David Blaikie7b028102015-02-25 00:51:52 +00003202 VE.computeBitsRequiredForTypeIndicies()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003203 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003204 CONSTANTS_SETTYPE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003205 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003206 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003207
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003208 { // INTEGER abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003209 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003210 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003212 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003213 CONSTANTS_INTEGER_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003214 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003215 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003216
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003217 { // CE_CAST abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003218 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003219 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3220 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3221 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
David Blaikie7b028102015-02-25 00:51:52 +00003222 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003223 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3224
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003225 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003226 CONSTANTS_CE_CAST_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003227 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003228 }
3229 { // NULL abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003230 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003231 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003232 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003233 CONSTANTS_NULL_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003234 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003235 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003236
Chris Lattnerb80751d2007-05-05 07:44:49 +00003237 // FIXME: This should only use space for first class types!
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003238
Chris Lattnerb80751d2007-05-05 07:44:49 +00003239 { // INST_LOAD abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003240 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb80751d2007-05-05 07:44:49 +00003241 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
Chris Lattnerb80751d2007-05-05 07:44:49 +00003242 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
David Blaikie85035652015-02-25 01:07:20 +00003243 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3244 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerb80751d2007-05-05 07:44:49 +00003245 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3246 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003247 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003248 FUNCTION_INST_LOAD_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003249 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerb80751d2007-05-05 07:44:49 +00003250 }
Cameron McInallycbde0d92018-11-13 18:15:47 +00003251 { // INST_UNOP abbrev for FUNCTION_BLOCK.
3252 auto Abbv = std::make_shared<BitCodeAbbrev>();
3253 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
3254 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3255 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3256 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3257 FUNCTION_INST_UNOP_ABBREV)
3258 llvm_unreachable("Unexpected abbrev ordering!");
3259 }
3260 { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3261 auto Abbv = std::make_shared<BitCodeAbbrev>();
3262 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNOP));
3263 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3264 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3265 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3266 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3267 FUNCTION_INST_UNOP_FLAGS_ABBREV)
3268 llvm_unreachable("Unexpected abbrev ordering!");
3269 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003270 { // INST_BINOP abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003271 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003272 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3273 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3274 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3275 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003276 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003277 FUNCTION_INST_BINOP_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003278 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003279 }
Dan Gohman0ebd6962009-07-20 21:19:07 +00003280 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003281 auto Abbv = std::make_shared<BitCodeAbbrev>();
Dan Gohman0ebd6962009-07-20 21:19:07 +00003282 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3283 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3284 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3285 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Steven Wu545d34a2018-02-19 19:22:28 +00003286 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003287 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003288 FUNCTION_INST_BINOP_FLAGS_ABBREV)
Dan Gohman0ebd6962009-07-20 21:19:07 +00003289 llvm_unreachable("Unexpected abbrev ordering!");
3290 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003291 { // INST_CAST abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003292 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003293 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3294 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3295 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
David Blaikie7b028102015-02-25 00:51:52 +00003296 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003297 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003298 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003299 FUNCTION_INST_CAST_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003300 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003301 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003302
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003303 { // INST_RET abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003304 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003305 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003306 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003307 FUNCTION_INST_RET_VOID_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003308 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003309 }
3310 { // INST_RET abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003311 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003312 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3313 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003314 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003315 FUNCTION_INST_RET_VAL_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003316 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003317 }
3318 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003319 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003320 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003321 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003322 FUNCTION_INST_UNREACHABLE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003323 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003324 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00003325 {
David Blaikie7ad9dc12017-01-04 22:36:33 +00003326 auto Abbv = std::make_shared<BitCodeAbbrev>();
David Blaikieb5b5efd2015-02-25 01:08:52 +00003327 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3328 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3329 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3330 Log2_32_Ceil(VE.getTypes().size() + 1)));
3331 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3332 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003333 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
David Blaikieb5b5efd2015-02-25 01:08:52 +00003334 FUNCTION_INST_GEP_ABBREV)
3335 llvm_unreachable("Unexpected abbrev ordering!");
3336 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003337
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003338 Stream.ExitBlock();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003339}
3340
Teresa Johnson403a7872015-10-04 14:33:43 +00003341/// Write the module path strings, currently only used when generating
3342/// a combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003343void IndexBitcodeWriter::writeModStrings() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003344 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
Teresa Johnson403a7872015-10-04 14:33:43 +00003345
3346 // TODO: See which abbrev sizes we actually need to emit
3347
3348 // 8-bit fixed-width MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003349 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003350 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3351 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3352 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3353 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003354 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003355
3356 // 7-bit fixed width MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003357 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003358 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3359 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3360 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3361 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003362 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003363
3364 // 6-bit char6 MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003365 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003366 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3367 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3369 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003370 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003371
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003372 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003373 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003374 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3375 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3376 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3377 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3378 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3379 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003380 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003381
3382 SmallVector<unsigned, 64> Vals;
Teresa Johnson7a27b132017-06-02 01:56:02 +00003383 forEachModule(
3384 [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
David Blaikieb6b42e02017-06-02 17:24:26 +00003385 StringRef Key = MPSE.getKey();
3386 const auto &Value = MPSE.getValue();
3387 StringEncoding Bits = getStringEncoding(Key);
Teresa Johnson7a27b132017-06-02 01:56:02 +00003388 unsigned AbbrevToUse = Abbrev8Bit;
3389 if (Bits == SE_Char6)
3390 AbbrevToUse = Abbrev6Bit;
3391 else if (Bits == SE_Fixed7)
3392 AbbrevToUse = Abbrev7Bit;
Teresa Johnson403a7872015-10-04 14:33:43 +00003393
David Blaikieb6b42e02017-06-02 17:24:26 +00003394 Vals.push_back(Value.first);
3395 Vals.append(Key.begin(), Key.end());
Teresa Johnson403a7872015-10-04 14:33:43 +00003396
Teresa Johnson7a27b132017-06-02 01:56:02 +00003397 // Emit the finished record.
3398 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003399
Teresa Johnson7a27b132017-06-02 01:56:02 +00003400 // Emit an optional hash for the module now
David Blaikieb6b42e02017-06-02 17:24:26 +00003401 const auto &Hash = Value.second;
3402 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3403 Vals.assign(Hash.begin(), Hash.end());
Teresa Johnson7a27b132017-06-02 01:56:02 +00003404 // Emit the hash record.
3405 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3406 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003407
Teresa Johnson7a27b132017-06-02 01:56:02 +00003408 Vals.clear();
3409 });
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003410 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003411}
3412
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003413/// Write the function type metadata related records that need to appear before
3414/// a function summary entry (whether per-module or combined).
Vitaly Buka7e880a42018-09-19 18:51:25 +00003415static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3416 FunctionSummary *FS) {
3417 if (!FS->type_tests().empty())
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003418 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3419
3420 SmallVector<uint64_t, 64> Record;
3421
3422 auto WriteVFuncIdVec = [&](uint64_t Ty,
3423 ArrayRef<FunctionSummary::VFuncId> VFs) {
3424 if (VFs.empty())
3425 return;
3426 Record.clear();
3427 for (auto &VF : VFs) {
3428 Record.push_back(VF.GUID);
3429 Record.push_back(VF.Offset);
3430 }
3431 Stream.EmitRecord(Ty, Record);
3432 };
3433
3434 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3435 FS->type_test_assume_vcalls());
3436 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3437 FS->type_checked_load_vcalls());
3438
3439 auto WriteConstVCallVec = [&](uint64_t Ty,
3440 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3441 for (auto &VC : VCs) {
3442 Record.clear();
3443 Record.push_back(VC.VFunc.GUID);
3444 Record.push_back(VC.VFunc.Offset);
3445 Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
3446 Stream.EmitRecord(Ty, Record);
3447 }
3448 };
3449
3450 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3451 FS->type_test_assume_const_vcalls());
3452 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3453 FS->type_checked_load_const_vcalls());
3454}
3455
Vitaly Buka7e880a42018-09-19 18:51:25 +00003456/// Collect type IDs from type tests used by function.
3457static void
3458getReferencedTypeIds(FunctionSummary *FS,
3459 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
3460 if (!FS->type_tests().empty())
3461 for (auto &TT : FS->type_tests())
3462 ReferencedTypeIds.insert(TT);
3463
3464 auto GetReferencedTypesFromVFuncIdVec =
3465 [&](ArrayRef<FunctionSummary::VFuncId> VFs) {
3466 for (auto &VF : VFs)
3467 ReferencedTypeIds.insert(VF.GUID);
3468 };
3469
3470 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
3471 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
3472
3473 auto GetReferencedTypesFromConstVCallVec =
3474 [&](ArrayRef<FunctionSummary::ConstVCall> VCs) {
3475 for (auto &VC : VCs)
3476 ReferencedTypeIds.insert(VC.VFunc.GUID);
3477 };
3478
3479 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
3480 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
3481}
3482
Vitaly Buka44396fa2018-02-14 22:41:15 +00003483static void writeWholeProgramDevirtResolutionByArg(
3484 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
3485 const WholeProgramDevirtResolution::ByArg &ByArg) {
3486 NameVals.push_back(args.size());
3487 NameVals.insert(NameVals.end(), args.begin(), args.end());
3488
3489 NameVals.push_back(ByArg.TheKind);
3490 NameVals.push_back(ByArg.Info);
3491 NameVals.push_back(ByArg.Byte);
3492 NameVals.push_back(ByArg.Bit);
3493}
3494
3495static void writeWholeProgramDevirtResolution(
3496 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3497 uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
3498 NameVals.push_back(Id);
3499
3500 NameVals.push_back(Wpd.TheKind);
3501 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
3502 NameVals.push_back(Wpd.SingleImplName.size());
3503
3504 NameVals.push_back(Wpd.ResByArg.size());
3505 for (auto &A : Wpd.ResByArg)
3506 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
3507}
3508
3509static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
3510 StringTableBuilder &StrtabBuilder,
3511 const std::string &Id,
3512 const TypeIdSummary &Summary) {
3513 NameVals.push_back(StrtabBuilder.add(Id));
3514 NameVals.push_back(Id.size());
3515
3516 NameVals.push_back(Summary.TTRes.TheKind);
3517 NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
3518 NameVals.push_back(Summary.TTRes.AlignLog2);
3519 NameVals.push_back(Summary.TTRes.SizeM1);
3520 NameVals.push_back(Summary.TTRes.BitMask);
3521 NameVals.push_back(Summary.TTRes.InlineBits);
3522
3523 for (auto &W : Summary.WPDRes)
3524 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
3525 W.second);
3526}
3527
Teresa Johnson403a7872015-10-04 14:33:43 +00003528// Helper to emit a single function summary record.
Haojie Wang1dec57d2017-07-21 17:25:20 +00003529void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
Teresa Johnson28e457b2016-04-24 14:57:11 +00003530 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
Teresa Johnson37687f32016-04-23 04:30:47 +00003531 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3532 const Function &F) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003533 NameVals.push_back(ValueID);
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003534
Teresa Johnson28e457b2016-04-24 14:57:11 +00003535 FunctionSummary *FS = cast<FunctionSummary>(Summary);
Vitaly Buka7e880a42018-09-19 18:51:25 +00003536 writeFunctionTypeMetadataRecords(Stream, FS);
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00003537
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003538 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
Teresa Johnson403a7872015-10-04 14:33:43 +00003539 NameVals.push_back(FS->instCount());
Charles Saternos75da10d2017-08-04 16:00:58 +00003540 NameVals.push_back(getEncodedFFlags(FS->fflags()));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003541 NameVals.push_back(FS->refs().size());
3542
3543 for (auto &RI : FS->refs())
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003544 NameVals.push_back(VE.getValueID(RI.getValue()));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003545
Teresa Johnsondb83ace2018-03-31 00:18:08 +00003546 bool HasProfileData =
3547 F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None;
Peter Collingbourne0c30f082016-12-20 21:12:28 +00003548 for (auto &ECI : FS->calls()) {
Teresa Johnsoncd21a642016-07-17 14:47:01 +00003549 NameVals.push_back(getValueId(ECI.first));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003550 if (HasProfileData)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003551 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
Easwaran Ramanc73cec82018-01-25 19:27:17 +00003552 else if (WriteRelBFToSummary)
3553 NameVals.push_back(ECI.second.RelBlockFreq);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003554 }
3555
3556 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3557 unsigned Code =
Easwaran Ramanc73cec82018-01-25 19:27:17 +00003558 (HasProfileData ? bitc::FS_PERMODULE_PROFILE
3559 : (WriteRelBFToSummary ? bitc::FS_PERMODULE_RELBF
3560 : bitc::FS_PERMODULE));
Teresa Johnson403a7872015-10-04 14:33:43 +00003561
3562 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003563 Stream.EmitRecord(Code, NameVals, FSAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003564 NameVals.clear();
3565}
3566
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003567// Collect the global value references in the given variable's initializer,
3568// and emit them in a summary record.
Haojie Wang1dec57d2017-07-21 17:25:20 +00003569void ModuleBitcodeWriterBase::writeModuleLevelReferences(
Teresa Johnson37687f32016-04-23 04:30:47 +00003570 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3571 unsigned FSModRefsAbbrev) {
Teresa Johnson7bea1aa2018-06-26 00:20:49 +00003572 auto VI = Index->getValueInfo(V.getGUID());
Peter Collingbourne9667b912017-05-04 18:03:25 +00003573 if (!VI || VI.getSummaryList().empty()) {
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003574 // Only declarations should not have a summary (a declaration might however
3575 // have a summary if the def was in module level asm).
3576 assert(V.isDeclaration());
Teresa Johnson13968092016-03-15 19:35:45 +00003577 return;
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003578 }
Peter Collingbourne9667b912017-05-04 18:03:25 +00003579 auto *Summary = VI.getSummaryList()[0].get();
Teresa Johnson13968092016-03-15 19:35:45 +00003580 NameVals.push_back(VE.getValueID(&V));
Teresa Johnson28e457b2016-04-24 14:57:11 +00003581 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
Teresa Johnson7c31cb12016-10-28 19:36:00 +00003582 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003583
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003584 unsigned SizeBeforeRefs = NameVals.size();
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003585 for (auto &RI : VS->refs())
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003586 NameVals.push_back(VE.getValueID(RI.getValue()));
3587 // Sort the refs for determinism output, the vector returned by FS->refs() has
3588 // been initialized from a DenseSet.
Mandeep Singh Grang176c3ef2018-04-05 19:27:04 +00003589 llvm::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003590
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003591 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3592 FSModRefsAbbrev);
Teresa Johnson13968092016-03-15 19:35:45 +00003593 NameVals.clear();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003594}
Teresa Johnson403a7872015-10-04 14:33:43 +00003595
Mehdi Amini8fe69362016-04-24 03:18:11 +00003596// Current version for the summary.
3597// This is bumped whenever we introduce changes in the way some record are
3598// interpreted, like flags for instance.
Steven Wufa438922018-11-13 17:35:04 +00003599static const uint64_t INDEX_VERSION = 4;
Mehdi Amini8fe69362016-04-24 03:18:11 +00003600
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003601/// Emit the per-module summary section alongside the rest of
3602/// the module's bitcode.
Haojie Wang1dec57d2017-07-21 17:25:20 +00003603void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
Peter Collingbournee357fbd2017-06-08 23:01:49 +00003604 // By default we compile with ThinLTO if the module has a summary, but the
3605 // client can request full LTO with a module flag.
3606 bool IsThinLTO = true;
3607 if (auto *MD =
3608 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3609 IsThinLTO = MD->getZExtValue();
3610 Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
3611 : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
3612 4);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003613
Mehdi Amini8fe69362016-04-24 03:18:11 +00003614 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3615
Teresa Johnson620c1402016-09-20 23:07:17 +00003616 if (Index->begin() == Index->end()) {
3617 Stream.ExitBlock();
3618 return;
3619 }
3620
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003621 for (const auto &GVI : valueIds()) {
3622 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3623 ArrayRef<uint64_t>{GVI.second, GVI.first});
3624 }
3625
Easwaran Ramanbf38dee2018-01-24 18:15:29 +00003626 // Abbrev for FS_PERMODULE_PROFILE.
Easwaran Ramanc73cec82018-01-25 19:27:17 +00003627 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003628 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3629 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003630 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003631 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Charles Saternos75da10d2017-08-04 16:00:58 +00003632 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003633 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003634 // numrefs x valueid, n x (valueid, hotness)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003635 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3636 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003637 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003638
Easwaran Ramanc73cec82018-01-25 19:27:17 +00003639 // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
3640 Abbv = std::make_shared<BitCodeAbbrev>();
3641 if (WriteRelBFToSummary)
3642 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));
3643 else
3644 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3645 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3646 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3647 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3648 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
3649 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3650 // numrefs x valueid, n x (valueid [, rel_block_freq])
3651 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3652 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3653 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3654
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003655 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003656 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003657 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3658 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003659 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003660 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3661 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003662 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003663
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003664 // Abbrev for FS_ALIAS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003665 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003666 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3667 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003668 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003669 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
David Blaikie7ad9dc12017-01-04 22:36:33 +00003670 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003671
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003672 SmallVector<uint64_t, 64> NameVals;
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003673 // Iterate over the list of functions instead of the Index to
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003674 // ensure the ordering is stable.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003675 for (const Function &F : M) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003676 // Summary emission does not support anonymous functions, they have to
3677 // renamed using the anonymous function renaming pass.
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003678 if (!F.hasName())
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003679 report_fatal_error("Unexpected anonymous function when writing summary");
Teresa Johnson403a7872015-10-04 14:33:43 +00003680
Teresa Johnson7bea1aa2018-06-26 00:20:49 +00003681 ValueInfo VI = Index->getValueInfo(F.getGUID());
Peter Collingbourne9667b912017-05-04 18:03:25 +00003682 if (!VI || VI.getSummaryList().empty()) {
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003683 // Only declarations should not have a summary (a declaration might
3684 // however have a summary if the def was in module level asm).
3685 assert(F.isDeclaration());
3686 continue;
3687 }
Peter Collingbourne9667b912017-05-04 18:03:25 +00003688 auto *Summary = VI.getSummaryList()[0].get();
Peter Collingbourne832e7fa2016-05-06 02:41:23 +00003689 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3690 FSCallsAbbrev, FSCallsProfileAbbrev, F);
Teresa Johnson403a7872015-10-04 14:33:43 +00003691 }
3692
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003693 // Capture references from GlobalVariable initializers, which are outside
3694 // of a function scope.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003695 for (const GlobalVariable &G : M.globals())
Teresa Johnson37687f32016-04-23 04:30:47 +00003696 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003697
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003698 for (const GlobalAlias &A : M.aliases()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003699 auto *Aliasee = A.getBaseObject();
3700 if (!Aliasee->hasName())
3701 // Nameless function don't have an entry in the summary, skip it.
3702 continue;
3703 auto AliasId = VE.getValueID(&A);
3704 auto AliaseeId = VE.getValueID(Aliasee);
3705 NameVals.push_back(AliasId);
Teresa Johnson02563cd2016-10-28 02:39:38 +00003706 auto *Summary = Index->getGlobalValueSummary(A);
3707 AliasSummary *AS = cast<AliasSummary>(Summary);
3708 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003709 NameVals.push_back(AliaseeId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003710 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003711 NameVals.clear();
3712 }
3713
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003714 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003715}
3716
Teresa Johnson26ab5772016-03-15 00:04:37 +00003717/// Emit the combined summary section into the combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003718void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003719 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
Mehdi Amini8fe69362016-04-24 03:18:11 +00003720 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
Teresa Johnson403a7872015-10-04 14:33:43 +00003721
Vitaly Buka769134d2018-02-16 23:38:22 +00003722 // Write the index flags.
3723 uint64_t Flags = 0;
3724 if (Index.withGlobalValueDeadStripping())
3725 Flags |= 0x1;
3726 if (Index.skipModuleByDistributedBackend())
3727 Flags |= 0x2;
3728 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
Teresa Johnsonf3681012018-02-07 04:05:59 +00003729
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003730 for (const auto &GVI : valueIds()) {
3731 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3732 ArrayRef<uint64_t>{GVI.second, GVI.first});
3733 }
3734
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003735 // Abbrev for FS_COMBINED.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003736 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003737 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
Teresa Johnson02e98332016-04-27 13:28:35 +00003738 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003739 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003740 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003741 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Charles Saternos75da10d2017-08-04 16:00:58 +00003742 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003743 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003744 // numrefs x valueid, n x (valueid)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003745 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3746 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003747 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003748
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003749 // Abbrev for FS_COMBINED_PROFILE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003750 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003751 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
Teresa Johnson02e98332016-04-27 13:28:35 +00003752 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003753 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003754 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003755 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Charles Saternos75da10d2017-08-04 16:00:58 +00003756 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003757 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003758 // numrefs x valueid, n x (valueid, hotness)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003759 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3760 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003761 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003762
3763 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003764 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003765 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003766 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003767 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003768 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003769 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3770 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003771 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003772
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003773 // Abbrev for FS_COMBINED_ALIAS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003774 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003775 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003776 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003777 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003778 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson02e98332016-04-27 13:28:35 +00003779 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
David Blaikie7ad9dc12017-01-04 22:36:33 +00003780 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003781
Teresa Johnson02e98332016-04-27 13:28:35 +00003782 // The aliases are emitted as a post-pass, and will point to the value
3783 // id of the aliasee. Save them in a vector for post-processing.
Teresa Johnson28e457b2016-04-24 14:57:11 +00003784 SmallVector<AliasSummary *, 64> Aliases;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003785
Teresa Johnson02e98332016-04-27 13:28:35 +00003786 // Save the value id for each summary for alias emission.
3787 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3788
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003789 SmallVector<uint64_t, 64> NameVals;
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003790
Teresa Johnson0c432b12018-07-19 22:25:56 +00003791 // Set that will be populated during call to writeFunctionTypeMetadataRecords
3792 // with the type ids referenced by this index file.
3793 std::set<GlobalValue::GUID> ReferencedTypeIds;
3794
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003795 // For local linkage, we also emit the original name separately
3796 // immediately after the record.
3797 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3798 if (!GlobalValue::isLocalLinkage(S.linkage()))
3799 return;
3800 NameVals.push_back(S.getOriginalName());
3801 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3802 NameVals.clear();
3803 };
3804
Teresa Johnson81bbf742017-12-16 00:18:12 +00003805 forEachSummary([&](GVInfo I, bool IsAliasee) {
Teresa Johnson84174c32016-05-10 13:48:23 +00003806 GlobalValueSummary *S = I.second;
3807 assert(S);
Teresa Johnson02e98332016-04-27 13:28:35 +00003808
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003809 auto ValueId = getValueId(I.first);
3810 assert(ValueId);
3811 SummaryToValueIdMap[S] = *ValueId;
Teresa Johnson02e98332016-04-27 13:28:35 +00003812
Teresa Johnson81bbf742017-12-16 00:18:12 +00003813 // If this is invoked for an aliasee, we want to record the above
3814 // mapping, but then not emit a summary entry (if the aliasee is
3815 // to be imported, we will invoke this separately with IsAliasee=false).
3816 if (IsAliasee)
3817 return;
3818
Teresa Johnson84174c32016-05-10 13:48:23 +00003819 if (auto *AS = dyn_cast<AliasSummary>(S)) {
3820 // Will process aliases as a post-pass because the reader wants all
3821 // global to be loaded first.
3822 Aliases.push_back(AS);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003823 return;
Teresa Johnson84174c32016-05-10 13:48:23 +00003824 }
Teresa Johnson403a7872015-10-04 14:33:43 +00003825
Teresa Johnson84174c32016-05-10 13:48:23 +00003826 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003827 NameVals.push_back(*ValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003828 NameVals.push_back(Index.getModuleId(VS->modulePath()));
3829 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3830 for (auto &RI : VS->refs()) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003831 auto RefValueId = getValueId(RI.getGUID());
3832 if (!RefValueId)
3833 continue;
3834 NameVals.push_back(*RefValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003835 }
3836
Teresa Johnson403a7872015-10-04 14:33:43 +00003837 // Emit the finished record.
Teresa Johnson84174c32016-05-10 13:48:23 +00003838 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3839 FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003840 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003841 MaybeEmitOriginalName(*S);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003842 return;
Teresa Johnson403a7872015-10-04 14:33:43 +00003843 }
Teresa Johnson84174c32016-05-10 13:48:23 +00003844
3845 auto *FS = cast<FunctionSummary>(S);
Vitaly Buka7e880a42018-09-19 18:51:25 +00003846 writeFunctionTypeMetadataRecords(Stream, FS);
3847 getReferencedTypeIds(FS, ReferencedTypeIds);
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00003848
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003849 NameVals.push_back(*ValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003850 NameVals.push_back(Index.getModuleId(FS->modulePath()));
3851 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3852 NameVals.push_back(FS->instCount());
Charles Saternos75da10d2017-08-04 16:00:58 +00003853 NameVals.push_back(getEncodedFFlags(FS->fflags()));
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003854 // Fill in below
Steven Wufa438922018-11-13 17:35:04 +00003855 NameVals.push_back(0);
Teresa Johnson84174c32016-05-10 13:48:23 +00003856
Steven Wufa438922018-11-13 17:35:04 +00003857 unsigned Count = 0;
Teresa Johnson84174c32016-05-10 13:48:23 +00003858 for (auto &RI : FS->refs()) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003859 auto RefValueId = getValueId(RI.getGUID());
3860 if (!RefValueId)
3861 continue;
3862 NameVals.push_back(*RefValueId);
3863 Count++;
Teresa Johnson84174c32016-05-10 13:48:23 +00003864 }
Charles Saternos75da10d2017-08-04 16:00:58 +00003865 NameVals[5] = Count;
Teresa Johnson84174c32016-05-10 13:48:23 +00003866
3867 bool HasProfileData = false;
3868 for (auto &EI : FS->calls()) {
Easwaran Ramanc73cec82018-01-25 19:27:17 +00003869 HasProfileData |=
3870 EI.second.getHotness() != CalleeInfo::HotnessType::Unknown;
Teresa Johnson84174c32016-05-10 13:48:23 +00003871 if (HasProfileData)
3872 break;
3873 }
3874
3875 for (auto &EI : FS->calls()) {
3876 // If this GUID doesn't have a value id, it doesn't have a function
3877 // summary and we don't need to record any calls to it.
Dehao Chen4a435e02017-03-14 17:33:01 +00003878 GlobalValue::GUID GUID = EI.first.getGUID();
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003879 auto CallValueId = getValueId(GUID);
3880 if (!CallValueId) {
Dehao Chen4a435e02017-03-14 17:33:01 +00003881 // For SamplePGO, the indirect call targets for local functions will
3882 // have its original name annotated in profile. We try to find the
3883 // corresponding PGOFuncName as the GUID.
3884 GUID = Index.getGUIDFromOriginalID(GUID);
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003885 if (GUID == 0)
3886 continue;
3887 CallValueId = getValueId(GUID);
3888 if (!CallValueId)
Dehao Chen4a435e02017-03-14 17:33:01 +00003889 continue;
Xinliang David Li71ecaa12017-08-16 17:18:01 +00003890 // The mapping from OriginalId to GUID may return a GUID
Xinliang David Li5a57b842017-08-16 17:33:43 +00003891 // that corresponds to a static variable. Filter it out here.
Fangrui Songf78650a2018-07-30 19:41:25 +00003892 // This can happen when
Xinliang David Li5a57b842017-08-16 17:33:43 +00003893 // 1) There is a call to a library function which does not have
3894 // a CallValidId;
3895 // 2) There is a static variable with the OriginalGUID identical
3896 // to the GUID of the library function in 1);
3897 // When this happens, the logic for SamplePGO kicks in and
Mandeep Singh Grang1be19e62017-09-15 20:01:43 +00003898 // the static variable in 2) will be found, which needs to be
Xinliang David Li5a57b842017-08-16 17:33:43 +00003899 // filtered out.
Xinliang David Li71ecaa12017-08-16 17:18:01 +00003900 auto *GVSum = Index.getGlobalValueSummary(GUID, false);
3901 if (GVSum &&
3902 GVSum->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
3903 continue;
Dehao Chen4a435e02017-03-14 17:33:01 +00003904 }
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003905 NameVals.push_back(*CallValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003906 if (HasProfileData)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003907 NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
Teresa Johnson84174c32016-05-10 13:48:23 +00003908 }
3909
3910 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3911 unsigned Code =
3912 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3913
3914 // Emit the finished record.
3915 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3916 NameVals.clear();
3917 MaybeEmitOriginalName(*S);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003918 });
Teresa Johnson403a7872015-10-04 14:33:43 +00003919
Teresa Johnson28e457b2016-04-24 14:57:11 +00003920 for (auto *AS : Aliases) {
Teresa Johnson02e98332016-04-27 13:28:35 +00003921 auto AliasValueId = SummaryToValueIdMap[AS];
3922 assert(AliasValueId);
3923 NameVals.push_back(AliasValueId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003924 NameVals.push_back(Index.getModuleId(AS->modulePath()));
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003925 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
Teresa Johnson02e98332016-04-27 13:28:35 +00003926 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3927 assert(AliaseeValueId);
3928 NameVals.push_back(AliaseeValueId);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003929
3930 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003931 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003932 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003933 MaybeEmitOriginalName(*AS);
Vitaly Buka84d912b2018-09-19 18:51:42 +00003934
3935 if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
3936 getReferencedTypeIds(FS, ReferencedTypeIds);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003937 }
3938
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00003939 if (!Index.cfiFunctionDefs().empty()) {
3940 for (auto &S : Index.cfiFunctionDefs()) {
3941 NameVals.push_back(StrtabBuilder.add(S));
3942 NameVals.push_back(S.size());
3943 }
3944 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
3945 NameVals.clear();
3946 }
3947
3948 if (!Index.cfiFunctionDecls().empty()) {
3949 for (auto &S : Index.cfiFunctionDecls()) {
3950 NameVals.push_back(StrtabBuilder.add(S));
3951 NameVals.push_back(S.size());
3952 }
3953 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
3954 NameVals.clear();
3955 }
3956
Teresa Johnson7fb39df2018-09-25 20:14:40 +00003957 // Walk the GUIDs that were referenced, and write the
3958 // corresponding type id records.
3959 for (auto &T : ReferencedTypeIds) {
3960 auto TidIter = Index.typeIds().equal_range(T);
3961 for (auto It = TidIter.first; It != TidIter.second; ++It) {
3962 writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,
3963 It->second.second);
Vitaly Buka44396fa2018-02-14 22:41:15 +00003964 Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
3965 NameVals.clear();
3966 }
3967 }
3968
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003969 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003970}
3971
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003972/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3973/// current llvm version, and a record for the epoch number.
Benjamin Kramerefcf06f2017-02-11 11:06:55 +00003974static void writeIdentificationBlock(BitstreamWriter &Stream) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003975 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
Mehdi Amini5d303282015-10-26 18:37:00 +00003976
3977 // Write the "user readable" string identifying the bitcode producer
David Blaikie7ad9dc12017-01-04 22:36:33 +00003978 auto Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini5d303282015-10-26 18:37:00 +00003979 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3980 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3981 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003982 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003983 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
Teresa Johnson37687f32016-04-23 04:30:47 +00003984 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
Mehdi Amini5d303282015-10-26 18:37:00 +00003985
3986 // Write the epoch version
David Blaikie7ad9dc12017-01-04 22:36:33 +00003987 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini5d303282015-10-26 18:37:00 +00003988 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3989 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003990 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini5d303282015-10-26 18:37:00 +00003991 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003992 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3993 Stream.ExitBlock();
Mehdi Amini5d303282015-10-26 18:37:00 +00003994}
3995
Teresa Johnson37687f32016-04-23 04:30:47 +00003996void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003997 // Emit the module's hash.
3998 // MODULE_CODE_HASH: [5*i32]
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003999 if (GenerateHash) {
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004000 uint32_t Vals[5];
4001 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
4002 Buffer.size() - BlockStartPos));
4003 StringRef Hash = Hasher.result();
4004 for (int Pos = 0; Pos < 20; Pos += 4) {
4005 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
4006 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00004007
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004008 // Emit the finished record.
4009 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
4010
4011 if (ModHash)
4012 // Save the written hash value.
4013 std::copy(std::begin(Vals), std::end(Vals), std::begin(*ModHash));
Haojie Wang1dec57d2017-07-21 17:25:20 +00004014 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00004015}
4016
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004017void ModuleBitcodeWriter::write() {
4018 writeIdentificationBlock(Stream);
Teresa Johnson37687f32016-04-23 04:30:47 +00004019
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00004020 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4021 size_t BlockStartPos = Buffer.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004022
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004023 writeModuleVersion();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00004024
4025 // Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00004026 writeBlockInfo();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004027
Bill Wendlingdc095552013-02-10 23:09:32 +00004028 // Emit information about attribute groups.
Teresa Johnson37687f32016-04-23 04:30:47 +00004029 writeAttributeGroupTable();
Bill Wendlingdc095552013-02-10 23:09:32 +00004030
Chris Lattnerda5e5d22007-05-05 07:36:14 +00004031 // Emit information about parameter attributes.
Teresa Johnson37687f32016-04-23 04:30:47 +00004032 writeAttributeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004033
Chris Lattnerda5e5d22007-05-05 07:36:14 +00004034 // Emit information describing all of the types in the module.
Teresa Johnson37687f32016-04-23 04:30:47 +00004035 writeTypeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004036
Teresa Johnson37687f32016-04-23 04:30:47 +00004037 writeComdats();
David Majnemerdad0a642014-06-27 18:19:56 +00004038
Chris Lattnerda5e5d22007-05-05 07:36:14 +00004039 // Emit top-level description of module, including target triple, inline asm,
4040 // descriptors for global variables, and function prototype info.
Teresa Johnson37687f32016-04-23 04:30:47 +00004041 writeModuleInfo();
Devang Patel7428d8a2009-07-22 17:43:22 +00004042
Devang Patele059ba6e2009-07-23 01:07:34 +00004043 // Emit constants.
Teresa Johnson37687f32016-04-23 04:30:47 +00004044 writeModuleConstants();
Devang Patele059ba6e2009-07-23 01:07:34 +00004045
Peter Collingbourne21521892016-06-21 23:42:48 +00004046 // Emit metadata kind names.
4047 writeModuleMetadataKinds();
Devang Patel8cca7b42009-08-04 05:01:35 +00004048
Devang Patelaf206b82009-09-18 19:26:43 +00004049 // Emit metadata.
Peter Collingbourne21521892016-06-21 23:42:48 +00004050 writeModuleMetadata();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004051
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004052 // Emit module-level use-lists.
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00004053 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00004054 writeUseListBlock(nullptr);
Chad Rosierca2567b2011-12-07 21:44:12 +00004055
Teresa Johnson37687f32016-04-23 04:30:47 +00004056 writeOperandBundleTags();
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004057 writeSyncScopeNames();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004058
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004059 // Emit function bodies.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00004060 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00004061 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004062 if (!F->isDeclaration())
Teresa Johnson37687f32016-04-23 04:30:47 +00004063 writeFunction(*F, FunctionToBitcodeIndex);
Teresa Johnson403a7872015-10-04 14:33:43 +00004064
4065 // Need to write after the above call to WriteFunction which populates
4066 // the summary information in the index.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00004067 if (Index)
Teresa Johnson37687f32016-04-23 04:30:47 +00004068 writePerModuleGlobalValueSummary();
Teresa Johnsonff642b92015-09-17 20:12:00 +00004069
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004070 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004071
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004072 writeModuleHash(BlockStartPos);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00004073
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00004074 Stream.ExitBlock();
Chris Lattner702658c2007-05-04 18:26:27 +00004075}
4076
Teresa Johnson37687f32016-04-23 04:30:47 +00004077static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
4078 uint32_t &Position) {
4079 support::endian::write32le(&Buffer[Position], Value);
4080 Position += 4;
4081}
4082
4083/// If generating a bc file on darwin, we have to emit a
Chris Lattnera660f4b2008-07-09 05:14:23 +00004084/// header and trailer to make it compatible with the system archiver. To do
4085/// this we emit the following header, and then emit a trailer that pads the
4086/// file out to be a multiple of 16 bytes.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004087///
Chris Lattnera660f4b2008-07-09 05:14:23 +00004088/// struct bc_header {
4089/// uint32_t Magic; // 0x0B17C0DE
4090/// uint32_t Version; // Version, currently always 0.
4091/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
4092/// uint32_t BitcodeSize; // Size of traditional bitcode file.
4093/// uint32_t CPUType; // CPU specifier.
4094/// ... potentially more later ...
4095/// };
Teresa Johnson37687f32016-04-23 04:30:47 +00004096static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004097 const Triple &TT) {
Chris Lattnera660f4b2008-07-09 05:14:23 +00004098 unsigned CPUType = ~0U;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004099
Evan Cheng9aa30fb2010-02-12 20:13:44 +00004100 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
Evan Cheng545d3602010-02-12 20:39:35 +00004101 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
4102 // number from /usr/include/mach/machine.h. It is ok to reproduce the
4103 // specific constants here because they are implicitly part of the Darwin ABI.
Chris Lattnera660f4b2008-07-09 05:14:23 +00004104 enum {
4105 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
4106 DARWIN_CPU_TYPE_X86 = 7,
Evan Cheng9aa30fb2010-02-12 20:13:44 +00004107 DARWIN_CPU_TYPE_ARM = 12,
Chris Lattnera660f4b2008-07-09 05:14:23 +00004108 DARWIN_CPU_TYPE_POWERPC = 18
4109 };
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004110
Evan Chengcffdcae2011-06-14 01:51:33 +00004111 Triple::ArchType Arch = TT.getArch();
4112 if (Arch == Triple::x86_64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00004113 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00004114 else if (Arch == Triple::x86)
Chris Lattnera660f4b2008-07-09 05:14:23 +00004115 CPUType = DARWIN_CPU_TYPE_X86;
Evan Chengcffdcae2011-06-14 01:51:33 +00004116 else if (Arch == Triple::ppc)
Chris Lattnera660f4b2008-07-09 05:14:23 +00004117 CPUType = DARWIN_CPU_TYPE_POWERPC;
Evan Chengcffdcae2011-06-14 01:51:33 +00004118 else if (Arch == Triple::ppc64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00004119 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00004120 else if (Arch == Triple::arm || Arch == Triple::thumb)
Evan Cheng9aa30fb2010-02-12 20:13:44 +00004121 CPUType = DARWIN_CPU_TYPE_ARM;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004122
Chris Lattnera660f4b2008-07-09 05:14:23 +00004123 // Traditional Bitcode starts after header.
Akira Hatanaka4f472a882016-01-29 05:55:09 +00004124 assert(Buffer.size() >= BWH_HeaderSize &&
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004125 "Expected header size to be reserved");
Akira Hatanaka4f472a882016-01-29 05:55:09 +00004126 unsigned BCOffset = BWH_HeaderSize;
4127 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004128
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004129 // Write the magic and version.
4130 unsigned Position = 0;
Teresa Johnson37687f32016-04-23 04:30:47 +00004131 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
4132 writeInt32ToBuffer(0, Buffer, Position); // Version.
4133 writeInt32ToBuffer(BCOffset, Buffer, Position);
4134 writeInt32ToBuffer(BCSize, Buffer, Position);
4135 writeInt32ToBuffer(CPUType, Buffer, Position);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004136
Chris Lattnera660f4b2008-07-09 05:14:23 +00004137 // If the file is not a multiple of 16 bytes, insert dummy padding.
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004138 while (Buffer.size() & 15)
4139 Buffer.push_back(0);
Chris Lattnera660f4b2008-07-09 05:14:23 +00004140}
4141
Teresa Johnson403a7872015-10-04 14:33:43 +00004142/// Helper to write the header common to all bitcode files.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004143static void writeBitcodeHeader(BitstreamWriter &Stream) {
Teresa Johnson403a7872015-10-04 14:33:43 +00004144 // Emit the file header.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00004145 Stream.Emit((unsigned)'B', 8);
4146 Stream.Emit((unsigned)'C', 8);
4147 Stream.Emit(0x0, 4);
4148 Stream.Emit(0xC, 4);
4149 Stream.Emit(0xE, 4);
4150 Stream.Emit(0xD, 4);
Teresa Johnson403a7872015-10-04 14:33:43 +00004151}
4152
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004153BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
4154 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
4155 writeBitcodeHeader(*Stream);
4156}
4157
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004158BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
4159
4160void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
4161 Stream->EnterSubblock(Block, 3);
4162
4163 auto Abbv = std::make_shared<BitCodeAbbrev>();
4164 Abbv->Add(BitCodeAbbrevOp(Record));
4165 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4166 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
4167
4168 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
4169
4170 Stream->ExitBlock();
4171}
4172
Peter Collingbourne92648c22017-06-27 23:50:11 +00004173void BitcodeWriter::writeSymtab() {
4174 assert(!WroteStrtab && !WroteSymtab);
4175
4176 // If any module has module-level inline asm, we will require a registered asm
4177 // parser for the target so that we can create an accurate symbol table for
4178 // the module.
4179 for (Module *M : Mods) {
4180 if (M->getModuleInlineAsm().empty())
4181 continue;
4182
4183 std::string Err;
4184 const Triple TT(M->getTargetTriple());
4185 const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
4186 if (!T || !T->hasMCAsmParser())
4187 return;
4188 }
4189
4190 WroteSymtab = true;
4191 SmallVector<char, 0> Symtab;
4192 // The irsymtab::build function may be unable to create a symbol table if the
4193 // module is malformed (e.g. it contains an invalid alias). Writing a symbol
4194 // table is not required for correctness, but we still want to be able to
4195 // write malformed modules to bitcode files, so swallow the error.
4196 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
4197 consumeError(std::move(E));
4198 return;
4199 }
4200
4201 writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
4202 {Symtab.data(), Symtab.size()});
4203}
4204
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004205void BitcodeWriter::writeStrtab() {
4206 assert(!WroteStrtab);
4207
4208 std::vector<char> Strtab;
4209 StrtabBuilder.finalizeInOrder();
4210 Strtab.resize(StrtabBuilder.getSize());
4211 StrtabBuilder.write((uint8_t *)Strtab.data());
4212
4213 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
4214 {Strtab.data(), Strtab.size()});
4215
4216 WroteStrtab = true;
4217}
4218
4219void BitcodeWriter::copyStrtab(StringRef Strtab) {
4220 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
4221 WroteStrtab = true;
4222}
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004223
Rafael Espindola6a86e252018-02-14 19:11:32 +00004224void BitcodeWriter::writeModule(const Module &M,
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004225 bool ShouldPreserveUseListOrder,
4226 const ModuleSummaryIndex *Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004227 bool GenerateHash, ModuleHash *ModHash) {
Peter Collingbourne92648c22017-06-27 23:50:11 +00004228 assert(!WroteStrtab);
4229
4230 // The Mods vector is used by irsymtab::build, which requires non-const
4231 // Modules in case it needs to materialize metadata. But the bitcode writer
4232 // requires that the module is materialized, so we can cast to non-const here,
4233 // after checking that it is in fact materialized.
Rafael Espindola6a86e252018-02-14 19:11:32 +00004234 assert(M.isMaterialized());
4235 Mods.push_back(const_cast<Module *>(&M));
Peter Collingbourne92648c22017-06-27 23:50:11 +00004236
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004237 ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004238 ShouldPreserveUseListOrder, Index,
4239 GenerateHash, ModHash);
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004240 ModuleWriter.write();
4241}
4242
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00004243void BitcodeWriter::writeIndex(
4244 const ModuleSummaryIndex *Index,
4245 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4246 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
4247 ModuleToSummariesForIndex);
4248 IndexWriter.write();
4249}
4250
Rafael Espindola6a86e252018-02-14 19:11:32 +00004251/// Write the specified module to the specified output stream.
4252void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,
Teresa Johnson403a7872015-10-04 14:33:43 +00004253 bool ShouldPreserveUseListOrder,
Teresa Johnson2d5487c2016-04-11 13:58:45 +00004254 const ModuleSummaryIndex *Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004255 bool GenerateHash, ModuleHash *ModHash) {
Michael Ilsemane26658d2012-12-03 21:29:36 +00004256 SmallVector<char, 0> Buffer;
Chris Lattnerc1d10d62007-04-22 06:24:45 +00004257 Buffer.reserve(256*1024);
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00004258
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004259 // If this is darwin or another generic macho target, reserve space for the
4260 // header.
Rafael Espindola6a86e252018-02-14 19:11:32 +00004261 Triple TT(M.getTargetTriple());
Akira Hatanaka1235d282016-01-23 16:02:10 +00004262 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Akira Hatanaka4f472a882016-01-29 05:55:09 +00004263 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004264
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004265 BitcodeWriter Writer(Buffer);
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004266 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
4267 ModHash);
Peter Collingbourne92648c22017-06-27 23:50:11 +00004268 Writer.writeSymtab();
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004269 Writer.writeStrtab();
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004270
Akira Hatanaka1235d282016-01-23 16:02:10 +00004271 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Teresa Johnson37687f32016-04-23 04:30:47 +00004272 emitDarwinBCHeaderAndTrailer(Buffer, TT);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004273
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00004274 // Write the generated bitstream to "Out".
4275 Out.write((char*)&Buffer.front(), Buffer.size());
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00004276}
Teresa Johnson403a7872015-10-04 14:33:43 +00004277
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004278void IndexBitcodeWriter::write() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00004279 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
Teresa Johnson37687f32016-04-23 04:30:47 +00004280
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004281 writeModuleVersion();
Teresa Johnson37687f32016-04-23 04:30:47 +00004282
4283 // Write the module paths in the combined index.
4284 writeModStrings();
4285
4286 // Write the summary combined index records.
4287 writeCombinedGlobalValueSummary();
4288
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00004289 Stream.ExitBlock();
Teresa Johnson37687f32016-04-23 04:30:47 +00004290}
4291
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004292// Write the specified module summary index to the given raw output stream,
Teresa Johnson403a7872015-10-04 14:33:43 +00004293// where it will be written in a new bitcode block. This is used when
Teresa Johnson84174c32016-05-10 13:48:23 +00004294// writing the combined index file for ThinLTO. When writing a subset of the
4295// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
4296void llvm::WriteIndexToFile(
4297 const ModuleSummaryIndex &Index, raw_ostream &Out,
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +00004298 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
Teresa Johnson403a7872015-10-04 14:33:43 +00004299 SmallVector<char, 0> Buffer;
4300 Buffer.reserve(256 * 1024);
4301
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00004302 BitcodeWriter Writer(Buffer);
4303 Writer.writeIndex(&Index, ModuleToSummariesForIndex);
4304 Writer.writeStrtab();
Teresa Johnson403a7872015-10-04 14:33:43 +00004305
4306 Out.write((char *)&Buffer.front(), Buffer.size());
4307}
Haojie Wang1dec57d2017-07-21 17:25:20 +00004308
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00004309namespace {
Eugene Zelenko975293f2017-09-07 23:28:24 +00004310
Haojie Wang1dec57d2017-07-21 17:25:20 +00004311/// Class to manage the bitcode writing for a thin link bitcode file.
4312class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
4313 /// ModHash is for use in ThinLTO incremental build, generated while writing
4314 /// the module bitcode file.
4315 const ModuleHash *ModHash;
4316
4317public:
Rafael Espindola6a86e252018-02-14 19:11:32 +00004318 ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
Haojie Wang1dec57d2017-07-21 17:25:20 +00004319 BitstreamWriter &Stream,
4320 const ModuleSummaryIndex &Index,
4321 const ModuleHash &ModHash)
4322 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
4323 /*ShouldPreserveUseListOrder=*/false, &Index),
4324 ModHash(&ModHash) {}
4325
4326 void write();
4327
4328private:
4329 void writeSimplifiedModuleInfo();
4330};
Eugene Zelenko975293f2017-09-07 23:28:24 +00004331
4332} // end anonymous namespace
Haojie Wang1dec57d2017-07-21 17:25:20 +00004333
4334// This function writes a simpilified module info for thin link bitcode file.
4335// It only contains the source file name along with the name(the offset and
4336// size in strtab) and linkage for global values. For the global value info
4337// entry, in order to keep linkage at offset 5, there are three zeros used
4338// as padding.
4339void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
4340 SmallVector<unsigned, 64> Vals;
4341 // Emit the module's source file name.
4342 {
4343 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
4344 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
4345 if (Bits == SE_Char6)
4346 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
4347 else if (Bits == SE_Fixed7)
4348 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
4349
4350 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4351 auto Abbv = std::make_shared<BitCodeAbbrev>();
4352 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
4353 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4354 Abbv->Add(AbbrevOpToUse);
4355 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4356
4357 for (const auto P : M.getSourceFileName())
4358 Vals.push_back((unsigned char)P);
4359
4360 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
4361 Vals.clear();
4362 }
4363
4364 // Emit the global variable information.
4365 for (const GlobalVariable &GV : M.globals()) {
4366 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
4367 Vals.push_back(StrtabBuilder.add(GV.getName()));
4368 Vals.push_back(GV.getName().size());
4369 Vals.push_back(0);
4370 Vals.push_back(0);
4371 Vals.push_back(0);
4372 Vals.push_back(getEncodedLinkage(GV));
4373
4374 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
4375 Vals.clear();
4376 }
4377
4378 // Emit the function proto information.
4379 for (const Function &F : M) {
4380 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
4381 Vals.push_back(StrtabBuilder.add(F.getName()));
4382 Vals.push_back(F.getName().size());
4383 Vals.push_back(0);
4384 Vals.push_back(0);
4385 Vals.push_back(0);
4386 Vals.push_back(getEncodedLinkage(F));
4387
4388 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
4389 Vals.clear();
4390 }
4391
4392 // Emit the alias information.
4393 for (const GlobalAlias &A : M.aliases()) {
4394 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
4395 Vals.push_back(StrtabBuilder.add(A.getName()));
4396 Vals.push_back(A.getName().size());
4397 Vals.push_back(0);
4398 Vals.push_back(0);
4399 Vals.push_back(0);
4400 Vals.push_back(getEncodedLinkage(A));
4401
4402 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
4403 Vals.clear();
4404 }
4405
4406 // Emit the ifunc information.
4407 for (const GlobalIFunc &I : M.ifuncs()) {
4408 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
4409 Vals.push_back(StrtabBuilder.add(I.getName()));
4410 Vals.push_back(I.getName().size());
4411 Vals.push_back(0);
4412 Vals.push_back(0);
4413 Vals.push_back(0);
4414 Vals.push_back(getEncodedLinkage(I));
4415
4416 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
4417 Vals.clear();
4418 }
4419}
4420
4421void ThinLinkBitcodeWriter::write() {
4422 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4423
4424 writeModuleVersion();
4425
4426 writeSimplifiedModuleInfo();
4427
4428 writePerModuleGlobalValueSummary();
4429
4430 // Write module hash.
4431 Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
4432
4433 Stream.ExitBlock();
4434}
4435
Rafael Espindola6a86e252018-02-14 19:11:32 +00004436void BitcodeWriter::writeThinLinkBitcode(const Module &M,
Haojie Wang1dec57d2017-07-21 17:25:20 +00004437 const ModuleSummaryIndex &Index,
4438 const ModuleHash &ModHash) {
4439 assert(!WroteStrtab);
4440
4441 // The Mods vector is used by irsymtab::build, which requires non-const
4442 // Modules in case it needs to materialize metadata. But the bitcode writer
4443 // requires that the module is materialized, so we can cast to non-const here,
4444 // after checking that it is in fact materialized.
Rafael Espindola6a86e252018-02-14 19:11:32 +00004445 assert(M.isMaterialized());
4446 Mods.push_back(const_cast<Module *>(&M));
Haojie Wang1dec57d2017-07-21 17:25:20 +00004447
4448 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
4449 ModHash);
4450 ThinLinkWriter.write();
4451}
4452
4453// Write the specified thin link bitcode file to the given raw output stream,
4454// where it will be written in a new bitcode block. This is used when
4455// writing the per-module index file for ThinLTO.
Rafael Espindola6a86e252018-02-14 19:11:32 +00004456void llvm::WriteThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,
Haojie Wang1dec57d2017-07-21 17:25:20 +00004457 const ModuleSummaryIndex &Index,
4458 const ModuleHash &ModHash) {
4459 SmallVector<char, 0> Buffer;
4460 Buffer.reserve(256 * 1024);
4461
4462 BitcodeWriter Writer(Buffer);
4463 Writer.writeThinLinkBitcode(M, Index, ModHash);
4464 Writer.writeSymtab();
4465 Writer.writeStrtab();
4466
4467 Out.write((char *)&Buffer.front(), Buffer.size());
4468}