blob: 1ee7b7b25e45e4f4f9ea8baf59af0cd927cd90a7 [file] [log] [blame]
Chris Lattner87351e22007-04-29 05:31:57 +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
Chandler Carruthed0881b2012-12-03 16:50:05 +000014#include "ValueEnumerator.h"
Mehdi Aminid7ad2212016-04-01 05:33:11 +000015#include "llvm/ADT/StringExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/Triple.h"
Chris Lattnerc1d10d62007-04-22 06:24:45 +000017#include "llvm/Bitcode/BitstreamWriter.h"
Chris Lattner362b4a12007-04-23 01:01:37 +000018#include "llvm/Bitcode/LLVMBitCodes.h"
Teresa Johnson76a1c1d2016-03-11 18:52:24 +000019#include "llvm/Bitcode/ReaderWriter.h"
Sanjoy Dasb513a9f2015-09-24 23:34:52 +000020#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000022#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/InlineAsm.h"
25#include "llvm/IR/Instructions.h"
Teresa Johnson76a1c1d2016-03-11 18:52:24 +000026#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Module.h"
28#include "llvm/IR/Operator.h"
Duncan P. N. Exon Smith6b6fdc92014-07-25 14:49:26 +000029#include "llvm/IR/UseListOrder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/ValueSymbolTable.h"
Torok Edwin56d06592009-07-11 20:10:48 +000031#include "llvm/Support/ErrorHandling.h"
Chris Lattnerc1d10d62007-04-22 06:24:45 +000032#include "llvm/Support/MathExtras.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000033#include "llvm/Support/Program.h"
Mehdi Aminid7ad2212016-04-01 05:33:11 +000034#include "llvm/Support/SHA1.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000035#include "llvm/Support/raw_ostream.h"
Nick Lewycky0de20af2010-12-19 20:43:38 +000036#include <cctype>
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000037#include <map>
Chris Lattnerc1d10d62007-04-22 06:24:45 +000038using namespace llvm;
39
Benjamin Kramera65b6102016-05-15 15:18:11 +000040namespace {
Chris Lattner4d925982007-05-04 20:52:02 +000041/// These are manifest constants used by the bitcode writer. They do not need to
42/// be kept in sync with the reader, but need to be consistent within this file.
43enum {
Chris Lattner4d925982007-05-04 20:52:02 +000044 // VALUE_SYMTAB_BLOCK abbrev id's.
45 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
Chris Lattnerfd1ad102007-05-04 20:58:35 +000046 VST_ENTRY_7_ABBREV,
Chris Lattnere760d6f2007-05-05 01:26:50 +000047 VST_ENTRY_6_ABBREV,
Chris Lattnerda5e5d22007-05-05 07:36:14 +000048 VST_BBENTRY_6_ABBREV,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000049
Chris Lattnerda5e5d22007-05-05 07:36:14 +000050 // CONSTANTS_BLOCK abbrev id's.
51 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
52 CONSTANTS_INTEGER_ABBREV,
53 CONSTANTS_CE_CAST_Abbrev,
Chris Lattnerb80751d2007-05-05 07:44:49 +000054 CONSTANTS_NULL_Abbrev,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000055
Chris Lattnerb80751d2007-05-05 07:44:49 +000056 // FUNCTION_BLOCK abbrev id's.
Chris Lattnercc6d4c92007-05-06 01:28:01 +000057 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
Chris Lattnerc67e6d92007-05-06 02:38:57 +000058 FUNCTION_INST_BINOP_ABBREV,
Dan Gohman0ebd6962009-07-20 21:19:07 +000059 FUNCTION_INST_BINOP_FLAGS_ABBREV,
Chris Lattnerc67e6d92007-05-06 02:38:57 +000060 FUNCTION_INST_CAST_ABBREV,
Chris Lattnercc6d4c92007-05-06 01:28:01 +000061 FUNCTION_INST_RET_VOID_ABBREV,
62 FUNCTION_INST_RET_VAL_ABBREV,
David Blaikieb5b5efd2015-02-25 01:08:52 +000063 FUNCTION_INST_UNREACHABLE_ABBREV,
64 FUNCTION_INST_GEP_ABBREV,
Chris Lattner4d925982007-05-04 20:52:02 +000065};
66
Teresa Johnsonc814e0c2016-04-23 04:31:20 +000067/// Abstract class to manage the bitcode writing, subclassed for each bitcode
68/// file type. Owns the BitstreamWriter, and includes the main entry point for
Teresa Johnson37687f32016-04-23 04:30:47 +000069/// writing.
70class BitcodeWriter {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +000071protected:
Teresa Johnson37687f32016-04-23 04:30:47 +000072 /// Pointer to the buffer allocated by caller for bitcode writing.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +000073 const SmallVectorImpl<char> &Buffer;
Teresa Johnson37687f32016-04-23 04:30:47 +000074
75 /// The stream created and owned by the BitodeWriter.
76 BitstreamWriter Stream;
77
78 /// Saves the offset of the VSTOffset record that must eventually be
79 /// backpatched with the offset of the actual VST.
80 uint64_t VSTOffsetPlaceholder = 0;
81
82public:
83 /// Constructs a BitcodeWriter object, and initializes a BitstreamRecord,
84 /// writing to the provided \p Buffer.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +000085 BitcodeWriter(SmallVectorImpl<char> &Buffer)
86 : Buffer(Buffer), Stream(Buffer) {}
Teresa Johnson37687f32016-04-23 04:30:47 +000087
88 virtual ~BitcodeWriter() = default;
89
90 /// Main entry point to write the bitcode file, which writes the bitcode
91 /// header and will then invoke the virtual writeBlocks() method.
92 void write();
93
94private:
95 /// Derived classes must implement this to write the corresponding blocks for
96 /// that bitcode file type.
97 virtual void writeBlocks() = 0;
98
99protected:
100 bool hasVSTOffsetPlaceholder() { return VSTOffsetPlaceholder != 0; }
Teresa Johnson37687f32016-04-23 04:30:47 +0000101 void writeValueSymbolTableForwardDecl();
102 void writeBitcodeHeader();
103};
104
105/// Class to manage the bitcode writing for a module.
106class ModuleBitcodeWriter : public BitcodeWriter {
107 /// The Module to write to bitcode.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000108 const Module &M;
Teresa Johnson37687f32016-04-23 04:30:47 +0000109
110 /// Enumerates ids for all values in the module.
111 ValueEnumerator VE;
112
113 /// Optional per-module index to write for ThinLTO.
114 const ModuleSummaryIndex *Index;
115
116 /// True if a module hash record should be written.
117 bool GenerateHash;
118
119 /// The start bit of the module block, for use in generating a module hash
120 uint64_t BitcodeStartBit = 0;
121
122public:
123 /// Constructs a ModuleBitcodeWriter object for the given Module,
124 /// writing to the provided \p Buffer.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000125 ModuleBitcodeWriter(const Module *M, SmallVectorImpl<char> &Buffer,
Teresa Johnson37687f32016-04-23 04:30:47 +0000126 bool ShouldPreserveUseListOrder,
127 const ModuleSummaryIndex *Index, bool GenerateHash)
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000128 : BitcodeWriter(Buffer), M(*M), VE(*M, ShouldPreserveUseListOrder),
Teresa Johnson37687f32016-04-23 04:30:47 +0000129 Index(Index), GenerateHash(GenerateHash) {
130 // Save the start bit of the actual bitcode, in case there is space
131 // saved at the start for the darwin header above. The reader stream
132 // will start at the bitcode, and we need the offset of the VST
133 // to line up.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000134 BitcodeStartBit = Stream.GetCurrentBitNo();
Teresa Johnson37687f32016-04-23 04:30:47 +0000135 }
136
137private:
138 /// Main entry point for writing a module to bitcode, invoked by
139 /// BitcodeWriter::write() after it writes the header.
140 void writeBlocks() override;
141
142 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
143 /// current llvm version, and a record for the epoch number.
144 void writeIdentificationBlock();
145
146 /// Emit the current module to the bitstream.
147 void writeModule();
148
149 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
150
151 void writeStringRecord(unsigned Code, StringRef Str, unsigned AbbrevToUse);
152 void writeAttributeGroupTable();
153 void writeAttributeTable();
154 void writeTypeTable();
155 void writeComdats();
156 void writeModuleInfo();
157 void writeValueAsMetadata(const ValueAsMetadata *MD,
158 SmallVectorImpl<uint64_t> &Record);
159 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
160 unsigned Abbrev);
161 unsigned createDILocationAbbrev();
162 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
163 unsigned &Abbrev);
164 unsigned createGenericDINodeAbbrev();
165 void writeGenericDINode(const GenericDINode *N,
166 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
167 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
168 unsigned Abbrev);
169 void writeDIEnumerator(const DIEnumerator *N,
170 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
171 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
172 unsigned Abbrev);
173 void writeDIDerivedType(const DIDerivedType *N,
174 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
175 void writeDICompositeType(const DICompositeType *N,
176 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
177 void writeDISubroutineType(const DISubroutineType *N,
178 SmallVectorImpl<uint64_t> &Record,
179 unsigned Abbrev);
180 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
181 unsigned Abbrev);
182 void writeDICompileUnit(const DICompileUnit *N,
183 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
184 void writeDISubprogram(const DISubprogram *N,
185 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
186 void writeDILexicalBlock(const DILexicalBlock *N,
187 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
188 void writeDILexicalBlockFile(const DILexicalBlockFile *N,
189 SmallVectorImpl<uint64_t> &Record,
190 unsigned Abbrev);
191 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
192 unsigned Abbrev);
193 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
194 unsigned Abbrev);
195 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
196 unsigned Abbrev);
197 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
198 unsigned Abbrev);
199 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
200 SmallVectorImpl<uint64_t> &Record,
201 unsigned Abbrev);
202 void writeDITemplateValueParameter(const DITemplateValueParameter *N,
203 SmallVectorImpl<uint64_t> &Record,
204 unsigned Abbrev);
205 void writeDIGlobalVariable(const DIGlobalVariable *N,
206 SmallVectorImpl<uint64_t> &Record,
207 unsigned Abbrev);
208 void writeDILocalVariable(const DILocalVariable *N,
209 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
210 void writeDIExpression(const DIExpression *N,
211 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
212 void writeDIObjCProperty(const DIObjCProperty *N,
213 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
214 void writeDIImportedEntity(const DIImportedEntity *N,
215 SmallVectorImpl<uint64_t> &Record,
216 unsigned Abbrev);
217 unsigned createNamedMetadataAbbrev();
218 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
219 unsigned createMetadataStringsAbbrev();
220 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
221 SmallVectorImpl<uint64_t> &Record);
222 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
223 SmallVectorImpl<uint64_t> &Record);
224 void writeModuleMetadata();
225 void writeFunctionMetadata(const Function &F);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000226 void writeFunctionMetadataAttachment(const Function &F);
227 void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
228 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
229 const GlobalObject &GO);
Peter Collingbourne21521892016-06-21 23:42:48 +0000230 void writeModuleMetadataKinds();
Teresa Johnson37687f32016-04-23 04:30:47 +0000231 void writeOperandBundleTags();
232 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
233 void writeModuleConstants();
234 bool pushValueAndType(const Value *V, unsigned InstID,
235 SmallVectorImpl<unsigned> &Vals);
236 void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
237 void pushValue(const Value *V, unsigned InstID,
238 SmallVectorImpl<unsigned> &Vals);
239 void pushValueSigned(const Value *V, unsigned InstID,
240 SmallVectorImpl<uint64_t> &Vals);
241 void writeInstruction(const Instruction &I, unsigned InstID,
242 SmallVectorImpl<unsigned> &Vals);
243 void writeValueSymbolTable(
244 const ValueSymbolTable &VST, bool IsModuleLevel = false,
245 DenseMap<const Function *, uint64_t> *FunctionToBitcodeIndex = nullptr);
246 void writeUseList(UseListOrder &&Order);
247 void writeUseListBlock(const Function *F);
248 void
249 writeFunction(const Function &F,
250 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
251 void writeBlockInfo();
252 void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
Teresa Johnson28e457b2016-04-24 14:57:11 +0000253 GlobalValueSummary *Summary,
Teresa Johnson37687f32016-04-23 04:30:47 +0000254 unsigned ValueID,
255 unsigned FSCallsAbbrev,
256 unsigned FSCallsProfileAbbrev,
257 const Function &F);
258 void writeModuleLevelReferences(const GlobalVariable &V,
259 SmallVector<uint64_t, 64> &NameVals,
260 unsigned FSModRefsAbbrev);
261 void writePerModuleGlobalValueSummary();
262 void writeModuleHash(size_t BlockStartPos);
263};
264
265/// Class to manage the bitcode writing for a combined index.
266class IndexBitcodeWriter : public BitcodeWriter {
267 /// The combined index to write to bitcode.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000268 const ModuleSummaryIndex &Index;
Teresa Johnson37687f32016-04-23 04:30:47 +0000269
Teresa Johnson84174c32016-05-10 13:48:23 +0000270 /// When writing a subset of the index for distributed backends, client
271 /// provides a map of modules to the corresponding GUIDs/summaries to write.
272 std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
273
Teresa Johnson37687f32016-04-23 04:30:47 +0000274 /// Map that holds the correspondence between the GUID used in the combined
275 /// index and a value id generated by this class to use in references.
276 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
277
278 /// Tracks the last value id recorded in the GUIDToValueMap.
279 unsigned GlobalValueId = 0;
280
281public:
282 /// Constructs a IndexBitcodeWriter object for the given combined index,
Teresa Johnson84174c32016-05-10 13:48:23 +0000283 /// writing to the provided \p Buffer. When writing a subset of the index
284 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000285 IndexBitcodeWriter(SmallVectorImpl<char> &Buffer,
Teresa Johnson84174c32016-05-10 13:48:23 +0000286 const ModuleSummaryIndex &Index,
287 std::map<std::string, GVSummaryMapTy>
288 *ModuleToSummariesForIndex = nullptr)
289 : BitcodeWriter(Buffer), Index(Index),
290 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
291 // Assign unique value ids to all summaries to be written, for use
Teresa Johnson37687f32016-04-23 04:30:47 +0000292 // in writing out the call graph edges. Save the mapping from GUID
293 // to the new global value id to use when writing those edges, which
294 // are currently saved in the index in terms of GUID.
Teresa Johnson84174c32016-05-10 13:48:23 +0000295 for (const auto &I : *this)
296 GUIDToValueIdMap[I.first] = ++GlobalValueId;
Teresa Johnson37687f32016-04-23 04:30:47 +0000297 }
298
Teresa Johnson84174c32016-05-10 13:48:23 +0000299 /// The below iterator returns the GUID and associated summary.
300 typedef std::pair<GlobalValue::GUID, GlobalValueSummary *> GVInfo;
301
302 /// Iterator over the value GUID and summaries to be written to bitcode,
303 /// hides the details of whether they are being pulled from the entire
304 /// index or just those in a provided ModuleToSummariesForIndex map.
305 class iterator
306 : public llvm::iterator_facade_base<iterator, std::forward_iterator_tag,
307 GVInfo> {
308 /// Enables access to parent class.
309 const IndexBitcodeWriter &Writer;
310
311 // Iterators used when writing only those summaries in a provided
312 // ModuleToSummariesForIndex map:
313
314 /// Points to the last element in outer ModuleToSummariesForIndex map.
315 std::map<std::string, GVSummaryMapTy>::iterator ModuleSummariesBack;
316 /// Iterator on outer ModuleToSummariesForIndex map.
317 std::map<std::string, GVSummaryMapTy>::iterator ModuleSummariesIter;
318 /// Iterator on an inner global variable summary map.
319 GVSummaryMapTy::iterator ModuleGVSummariesIter;
320
321 // Iterators used when writing all summaries in the index:
322
323 /// Points to the last element in the Index outer GlobalValueMap.
324 const_gvsummary_iterator IndexSummariesBack;
325 /// Iterator on outer GlobalValueMap.
326 const_gvsummary_iterator IndexSummariesIter;
327 /// Iterator on an inner GlobalValueSummaryList.
328 GlobalValueSummaryList::const_iterator IndexGVSummariesIter;
329
330 public:
331 /// Construct iterator from parent \p Writer and indicate if we are
332 /// constructing the end iterator.
333 iterator(const IndexBitcodeWriter &Writer, bool IsAtEnd) : Writer(Writer) {
334 // Set up the appropriate set of iterators given whether we are writing
335 // the full index or just a subset.
336 // Can't setup the Back or inner iterators if the corresponding map
337 // is empty. This will be handled specially in operator== as well.
338 if (Writer.ModuleToSummariesForIndex &&
339 !Writer.ModuleToSummariesForIndex->empty()) {
Teresa Johnson84174c32016-05-10 13:48:23 +0000340 for (ModuleSummariesBack = Writer.ModuleToSummariesForIndex->begin();
341 std::next(ModuleSummariesBack) !=
342 Writer.ModuleToSummariesForIndex->end();
343 ModuleSummariesBack++)
344 ;
Teresa Johnsone518c802016-05-11 20:46:22 +0000345 ModuleSummariesIter = !IsAtEnd
346 ? Writer.ModuleToSummariesForIndex->begin()
347 : ModuleSummariesBack;
Teresa Johnson84174c32016-05-10 13:48:23 +0000348 ModuleGVSummariesIter = !IsAtEnd ? ModuleSummariesIter->second.begin()
349 : ModuleSummariesBack->second.end();
350 } else if (!Writer.ModuleToSummariesForIndex &&
351 Writer.Index.begin() != Writer.Index.end()) {
Teresa Johnson84174c32016-05-10 13:48:23 +0000352 for (IndexSummariesBack = Writer.Index.begin();
353 std::next(IndexSummariesBack) != Writer.Index.end();
354 IndexSummariesBack++)
355 ;
Teresa Johnsone518c802016-05-11 20:46:22 +0000356 IndexSummariesIter =
357 !IsAtEnd ? Writer.Index.begin() : IndexSummariesBack;
Teresa Johnson84174c32016-05-10 13:48:23 +0000358 IndexGVSummariesIter = !IsAtEnd ? IndexSummariesIter->second.begin()
359 : IndexSummariesBack->second.end();
360 }
361 }
362
363 /// Increment the appropriate set of iterators.
364 iterator &operator++() {
365 // First the inner iterator is incremented, then if it is at the end
366 // and there are more outer iterations to go, the inner is reset to
367 // the start of the next inner list.
368 if (Writer.ModuleToSummariesForIndex) {
369 ++ModuleGVSummariesIter;
370 if (ModuleGVSummariesIter == ModuleSummariesIter->second.end() &&
371 ModuleSummariesIter != ModuleSummariesBack) {
372 ++ModuleSummariesIter;
373 ModuleGVSummariesIter = ModuleSummariesIter->second.begin();
374 }
375 } else {
376 ++IndexGVSummariesIter;
377 if (IndexGVSummariesIter == IndexSummariesIter->second.end() &&
378 IndexSummariesIter != IndexSummariesBack) {
379 ++IndexSummariesIter;
380 IndexGVSummariesIter = IndexSummariesIter->second.begin();
381 }
382 }
383 return *this;
384 }
385
386 /// Access the <GUID,GlobalValueSummary*> pair corresponding to the current
387 /// outer and inner iterator positions.
388 GVInfo operator*() {
389 if (Writer.ModuleToSummariesForIndex)
390 return std::make_pair(ModuleGVSummariesIter->first,
391 ModuleGVSummariesIter->second);
392 return std::make_pair(IndexSummariesIter->first,
393 IndexGVSummariesIter->get());
394 }
395
396 /// Checks if the iterators are equal, with special handling for empty
397 /// indexes.
398 bool operator==(const iterator &RHS) const {
399 if (Writer.ModuleToSummariesForIndex) {
400 // First ensure that both are writing the same subset.
401 if (Writer.ModuleToSummariesForIndex !=
402 RHS.Writer.ModuleToSummariesForIndex)
403 return false;
404 // Already determined above that maps are the same, so if one is
405 // empty, they both are.
406 if (Writer.ModuleToSummariesForIndex->empty())
407 return true;
Teresa Johnsone518c802016-05-11 20:46:22 +0000408 // Ensure the ModuleGVSummariesIter are iterating over the same
409 // container before checking them below.
410 if (ModuleSummariesIter != RHS.ModuleSummariesIter)
411 return false;
Teresa Johnson84174c32016-05-10 13:48:23 +0000412 return ModuleGVSummariesIter == RHS.ModuleGVSummariesIter;
413 }
414 // First ensure RHS also writing the full index, and that both are
415 // writing the same full index.
416 if (RHS.Writer.ModuleToSummariesForIndex ||
417 &Writer.Index != &RHS.Writer.Index)
418 return false;
419 // Already determined above that maps are the same, so if one is
420 // empty, they both are.
421 if (Writer.Index.begin() == Writer.Index.end())
422 return true;
Teresa Johnsone518c802016-05-11 20:46:22 +0000423 // Ensure the IndexGVSummariesIter are iterating over the same
424 // container before checking them below.
425 if (IndexSummariesIter != RHS.IndexSummariesIter)
426 return false;
Teresa Johnson84174c32016-05-10 13:48:23 +0000427 return IndexGVSummariesIter == RHS.IndexGVSummariesIter;
428 }
429 };
430
431 /// Obtain the start iterator over the summaries to be written.
432 iterator begin() { return iterator(*this, /*IsAtEnd=*/false); }
433 /// Obtain the end iterator over the summaries to be written.
434 iterator end() { return iterator(*this, /*IsAtEnd=*/true); }
435
Teresa Johnson37687f32016-04-23 04:30:47 +0000436private:
437 /// Main entry point for writing a combined index to bitcode, invoked by
438 /// BitcodeWriter::write() after it writes the header.
439 void writeBlocks() override;
440
441 void writeIndex();
442 void writeModStrings();
443 void writeCombinedValueSymbolTable();
444 void writeCombinedGlobalValueSummary();
445
Teresa Johnson84174c32016-05-10 13:48:23 +0000446 /// Indicates whether the provided \p ModulePath should be written into
447 /// the module string table, e.g. if full index written or if it is in
448 /// the provided subset.
449 bool doIncludeModule(StringRef ModulePath) {
450 return !ModuleToSummariesForIndex ||
451 ModuleToSummariesForIndex->count(ModulePath);
452 }
453
Teresa Johnson37687f32016-04-23 04:30:47 +0000454 bool hasValueId(GlobalValue::GUID ValGUID) {
455 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
456 return VMI != GUIDToValueIdMap.end();
457 }
458 unsigned getValueId(GlobalValue::GUID ValGUID) {
459 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
460 // If this GUID doesn't have an entry, assign one.
461 if (VMI == GUIDToValueIdMap.end()) {
462 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
463 return GlobalValueId;
464 } else {
465 return VMI->second;
466 }
467 }
Teresa Johnson37687f32016-04-23 04:30:47 +0000468 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
469};
Benjamin Kramera65b6102016-05-15 15:18:11 +0000470} // end anonymous namespace
Teresa Johnson37687f32016-04-23 04:30:47 +0000471
472static unsigned getEncodedCastOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000473 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000474 default: llvm_unreachable("Unknown cast instruction!");
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000475 case Instruction::Trunc : return bitc::CAST_TRUNC;
476 case Instruction::ZExt : return bitc::CAST_ZEXT;
477 case Instruction::SExt : return bitc::CAST_SEXT;
478 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
479 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
480 case Instruction::UIToFP : return bitc::CAST_UITOFP;
481 case Instruction::SIToFP : return bitc::CAST_SITOFP;
482 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
483 case Instruction::FPExt : return bitc::CAST_FPEXT;
484 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
485 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
486 case Instruction::BitCast : return bitc::CAST_BITCAST;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000487 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000488 }
489}
490
Teresa Johnson37687f32016-04-23 04:30:47 +0000491static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000492 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000493 default: llvm_unreachable("Unknown binary instruction!");
Dan Gohmana5b96452009-06-04 22:49:04 +0000494 case Instruction::Add:
495 case Instruction::FAdd: return bitc::BINOP_ADD;
496 case Instruction::Sub:
497 case Instruction::FSub: return bitc::BINOP_SUB;
498 case Instruction::Mul:
499 case Instruction::FMul: return bitc::BINOP_MUL;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000500 case Instruction::UDiv: return bitc::BINOP_UDIV;
501 case Instruction::FDiv:
502 case Instruction::SDiv: return bitc::BINOP_SDIV;
503 case Instruction::URem: return bitc::BINOP_UREM;
504 case Instruction::FRem:
505 case Instruction::SRem: return bitc::BINOP_SREM;
506 case Instruction::Shl: return bitc::BINOP_SHL;
507 case Instruction::LShr: return bitc::BINOP_LSHR;
508 case Instruction::AShr: return bitc::BINOP_ASHR;
509 case Instruction::And: return bitc::BINOP_AND;
510 case Instruction::Or: return bitc::BINOP_OR;
511 case Instruction::Xor: return bitc::BINOP_XOR;
512 }
513}
514
Teresa Johnson37687f32016-04-23 04:30:47 +0000515static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000516 switch (Op) {
517 default: llvm_unreachable("Unknown RMW operation!");
518 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
519 case AtomicRMWInst::Add: return bitc::RMW_ADD;
520 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
521 case AtomicRMWInst::And: return bitc::RMW_AND;
522 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
523 case AtomicRMWInst::Or: return bitc::RMW_OR;
524 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
525 case AtomicRMWInst::Max: return bitc::RMW_MAX;
526 case AtomicRMWInst::Min: return bitc::RMW_MIN;
527 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
528 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
529 }
530}
531
Teresa Johnson37687f32016-04-23 04:30:47 +0000532static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000533 switch (Ordering) {
JF Bastien800f87a2016-04-06 21:19:33 +0000534 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
535 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
536 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
537 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
538 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
539 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
540 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000541 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000542 llvm_unreachable("Invalid ordering");
Eli Friedmanfee02c62011-07-25 23:16:38 +0000543}
544
Teresa Johnson37687f32016-04-23 04:30:47 +0000545static unsigned getEncodedSynchScope(SynchronizationScope SynchScope) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000546 switch (SynchScope) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000547 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
548 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
549 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000550 llvm_unreachable("Invalid synch scope");
Eli Friedmanfee02c62011-07-25 23:16:38 +0000551}
552
Teresa Johnson37687f32016-04-23 04:30:47 +0000553void ModuleBitcodeWriter::writeStringRecord(unsigned Code, StringRef Str,
554 unsigned AbbrevToUse) {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000555 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000556
Chris Lattnere14cb882007-05-04 19:11:41 +0000557 // Code: [strchar x N]
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000558 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
559 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
560 AbbrevToUse = 0;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000561 Vals.push_back(Str[i]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000562 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000563
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000564 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000565 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000566}
567
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000568static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
569 switch (Kind) {
570 case Attribute::Alignment:
571 return bitc::ATTR_KIND_ALIGNMENT;
George Burgess IV278199f2016-04-12 01:05:35 +0000572 case Attribute::AllocSize:
573 return bitc::ATTR_KIND_ALLOC_SIZE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000574 case Attribute::AlwaysInline:
575 return bitc::ATTR_KIND_ALWAYS_INLINE;
Igor Laevsky39d662f2015-07-11 10:30:36 +0000576 case Attribute::ArgMemOnly:
577 return bitc::ATTR_KIND_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000578 case Attribute::Builtin:
579 return bitc::ATTR_KIND_BUILTIN;
580 case Attribute::ByVal:
581 return bitc::ATTR_KIND_BY_VAL;
Owen Anderson85fa7d52015-05-26 23:48:40 +0000582 case Attribute::Convergent:
583 return bitc::ATTR_KIND_CONVERGENT;
Reid Klecknera534a382013-12-19 02:14:12 +0000584 case Attribute::InAlloca:
585 return bitc::ATTR_KIND_IN_ALLOCA;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000586 case Attribute::Cold:
587 return bitc::ATTR_KIND_COLD;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +0000588 case Attribute::InaccessibleMemOnly:
589 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
590 case Attribute::InaccessibleMemOrArgMemOnly:
591 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000592 case Attribute::InlineHint:
593 return bitc::ATTR_KIND_INLINE_HINT;
594 case Attribute::InReg:
595 return bitc::ATTR_KIND_IN_REG;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000596 case Attribute::JumpTable:
597 return bitc::ATTR_KIND_JUMP_TABLE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000598 case Attribute::MinSize:
599 return bitc::ATTR_KIND_MIN_SIZE;
600 case Attribute::Naked:
601 return bitc::ATTR_KIND_NAKED;
602 case Attribute::Nest:
603 return bitc::ATTR_KIND_NEST;
604 case Attribute::NoAlias:
605 return bitc::ATTR_KIND_NO_ALIAS;
606 case Attribute::NoBuiltin:
607 return bitc::ATTR_KIND_NO_BUILTIN;
608 case Attribute::NoCapture:
609 return bitc::ATTR_KIND_NO_CAPTURE;
610 case Attribute::NoDuplicate:
611 return bitc::ATTR_KIND_NO_DUPLICATE;
612 case Attribute::NoImplicitFloat:
613 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
614 case Attribute::NoInline:
615 return bitc::ATTR_KIND_NO_INLINE;
James Molloye6f87ca2015-11-06 10:32:53 +0000616 case Attribute::NoRecurse:
617 return bitc::ATTR_KIND_NO_RECURSE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000618 case Attribute::NonLazyBind:
619 return bitc::ATTR_KIND_NON_LAZY_BIND;
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000620 case Attribute::NonNull:
621 return bitc::ATTR_KIND_NON_NULL;
Hal Finkelb0407ba2014-07-18 15:51:28 +0000622 case Attribute::Dereferenceable:
623 return bitc::ATTR_KIND_DEREFERENCEABLE;
Sanjoy Das31ea6d12015-04-16 20:29:50 +0000624 case Attribute::DereferenceableOrNull:
625 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000626 case Attribute::NoRedZone:
627 return bitc::ATTR_KIND_NO_RED_ZONE;
628 case Attribute::NoReturn:
629 return bitc::ATTR_KIND_NO_RETURN;
630 case Attribute::NoUnwind:
631 return bitc::ATTR_KIND_NO_UNWIND;
632 case Attribute::OptimizeForSize:
633 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000634 case Attribute::OptimizeNone:
635 return bitc::ATTR_KIND_OPTIMIZE_NONE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000636 case Attribute::ReadNone:
637 return bitc::ATTR_KIND_READ_NONE;
638 case Attribute::ReadOnly:
639 return bitc::ATTR_KIND_READ_ONLY;
640 case Attribute::Returned:
641 return bitc::ATTR_KIND_RETURNED;
642 case Attribute::ReturnsTwice:
643 return bitc::ATTR_KIND_RETURNS_TWICE;
644 case Attribute::SExt:
645 return bitc::ATTR_KIND_S_EXT;
646 case Attribute::StackAlignment:
647 return bitc::ATTR_KIND_STACK_ALIGNMENT;
648 case Attribute::StackProtect:
649 return bitc::ATTR_KIND_STACK_PROTECT;
650 case Attribute::StackProtectReq:
651 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
652 case Attribute::StackProtectStrong:
653 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000654 case Attribute::SafeStack:
655 return bitc::ATTR_KIND_SAFESTACK;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000656 case Attribute::StructRet:
657 return bitc::ATTR_KIND_STRUCT_RET;
658 case Attribute::SanitizeAddress:
659 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
660 case Attribute::SanitizeThread:
661 return bitc::ATTR_KIND_SANITIZE_THREAD;
662 case Attribute::SanitizeMemory:
663 return bitc::ATTR_KIND_SANITIZE_MEMORY;
Manman Ren9bfd0d02016-04-01 21:41:15 +0000664 case Attribute::SwiftError:
665 return bitc::ATTR_KIND_SWIFT_ERROR;
Manman Renf46262e2016-03-29 17:37:21 +0000666 case Attribute::SwiftSelf:
667 return bitc::ATTR_KIND_SWIFT_SELF;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000668 case Attribute::UWTable:
669 return bitc::ATTR_KIND_UW_TABLE;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +0000670 case Attribute::WriteOnly:
671 return bitc::ATTR_KIND_WRITEONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000672 case Attribute::ZExt:
673 return bitc::ATTR_KIND_Z_EXT;
674 case Attribute::EndAttrKinds:
675 llvm_unreachable("Can not encode end-attribute kinds marker.");
676 case Attribute::None:
677 llvm_unreachable("Can not encode none-attribute.");
678 }
679
680 llvm_unreachable("Trying to encode unknown attribute");
681}
682
Teresa Johnson37687f32016-04-23 04:30:47 +0000683void ModuleBitcodeWriter::writeAttributeGroupTable() {
Bill Wendling92ed7002013-02-11 22:33:26 +0000684 const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
685 if (AttrGrps.empty()) return;
Bill Wendlingdc095552013-02-10 23:09:32 +0000686
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000687 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
Bill Wendlingdc095552013-02-10 23:09:32 +0000688
689 SmallVector<uint64_t, 64> Record;
Bill Wendling92ed7002013-02-11 22:33:26 +0000690 for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
691 AttributeSet AS = AttrGrps[i];
Bill Wendlingdc095552013-02-10 23:09:32 +0000692 for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
693 AttributeSet A = AS.getSlotAttributes(i);
694
Bill Wendling92ed7002013-02-11 22:33:26 +0000695 Record.push_back(VE.getAttributeGroupID(A));
Bill Wendlingdc095552013-02-10 23:09:32 +0000696 Record.push_back(AS.getSlotIndex(i));
697
698 for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
699 I != E; ++I) {
700 Attribute Attr = *I;
701 if (Attr.isEnumAttribute()) {
702 Record.push_back(0);
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000703 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
Hal Finkele15442c2014-07-18 06:51:55 +0000704 } else if (Attr.isIntAttribute()) {
Bill Wendlingdc095552013-02-10 23:09:32 +0000705 Record.push_back(1);
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000706 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
Bill Wendlingdc095552013-02-10 23:09:32 +0000707 Record.push_back(Attr.getValueAsInt());
708 } else {
709 StringRef Kind = Attr.getKindAsString();
710 StringRef Val = Attr.getValueAsString();
711
712 Record.push_back(Val.empty() ? 3 : 4);
713 Record.append(Kind.begin(), Kind.end());
714 Record.push_back(0);
715 if (!Val.empty()) {
716 Record.append(Val.begin(), Val.end());
717 Record.push_back(0);
718 }
719 }
720 }
721
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000722 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
Bill Wendlingdc095552013-02-10 23:09:32 +0000723 Record.clear();
724 }
725 }
726
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000727 Stream.ExitBlock();
Bill Wendlingdc095552013-02-10 23:09:32 +0000728}
729
Teresa Johnson37687f32016-04-23 04:30:47 +0000730void ModuleBitcodeWriter::writeAttributeTable() {
Bill Wendlinge94d8432012-12-07 23:16:57 +0000731 const std::vector<AttributeSet> &Attrs = VE.getAttributes();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000732 if (Attrs.empty()) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000733
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000734 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000735
736 SmallVector<uint64_t, 64> Record;
737 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
Bill Wendlinge94d8432012-12-07 23:16:57 +0000738 const AttributeSet &A = Attrs[i];
Bill Wendling0dc08912013-02-12 08:13:50 +0000739 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
740 Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000741
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000742 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000743 Record.clear();
744 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000745
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000746 Stream.ExitBlock();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000747}
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000748
749/// WriteTypeTable - Write out the type table for a module.
Teresa Johnson37687f32016-04-23 04:30:47 +0000750void ModuleBitcodeWriter::writeTypeTable() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000751 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000752
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000753 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000754 SmallVector<uint64_t, 64> TypeVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000755
David Blaikie7b028102015-02-25 00:51:52 +0000756 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
Chad Rosier9646c0d2011-12-08 00:38:45 +0000757
Chris Lattnerccee7062007-05-05 06:30:12 +0000758 // Abbrev for TYPE_CODE_POINTER.
759 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
760 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000761 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
Christopher Lamb25f50762007-12-12 08:44:39 +0000762 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000763 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000764
Chris Lattnerccee7062007-05-05 06:30:12 +0000765 // Abbrev for TYPE_CODE_FUNCTION.
766 Abbv = new BitCodeAbbrev();
767 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
768 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
Chris Lattnerccee7062007-05-05 06:30:12 +0000769 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000770 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
771
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000772 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000773
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000774 // Abbrev for TYPE_CODE_STRUCT_ANON.
Chris Lattnerccee7062007-05-05 06:30:12 +0000775 Abbv = new BitCodeAbbrev();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000776 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
Chris Lattnerccee7062007-05-05 06:30:12 +0000777 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
778 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000779 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
780
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000781 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000782
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000783 // Abbrev for TYPE_CODE_STRUCT_NAME.
784 Abbv = new BitCodeAbbrev();
785 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
786 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
787 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000788 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000789
790 // Abbrev for TYPE_CODE_STRUCT_NAMED.
791 Abbv = new BitCodeAbbrev();
792 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
793 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
794 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000795 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
796
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000797 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000798
Chris Lattnerccee7062007-05-05 06:30:12 +0000799 // Abbrev for TYPE_CODE_ARRAY.
800 Abbv = new BitCodeAbbrev();
801 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
802 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
Chad Rosier9646c0d2011-12-08 00:38:45 +0000803 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
804
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000805 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000806
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000807 // Emit an entry count so the reader can reserve space.
808 TypeVals.push_back(TypeList.size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000809 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000810 TypeVals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000811
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000812 // Loop over all of the types, emitting each in turn.
813 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +0000814 Type *T = TypeList[i];
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000815 int AbbrevToUse = 0;
816 unsigned Code = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000817
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000818 switch (T->getTypeID()) {
Joe Abbey2ad8df22012-11-25 15:23:39 +0000819 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
820 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
821 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
822 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
823 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
824 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000825 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
Joe Abbey2ad8df22012-11-25 15:23:39 +0000826 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
827 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
828 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
David Majnemerb611e3f2015-08-14 05:09:07 +0000829 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000830 case Type::IntegerTyID:
831 // INTEGER: [width]
832 Code = bitc::TYPE_CODE_INTEGER;
833 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
834 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000835 case Type::PointerTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000836 PointerType *PTy = cast<PointerType>(T);
Christopher Lamb25f50762007-12-12 08:44:39 +0000837 // POINTER: [pointee type, address space]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000838 Code = bitc::TYPE_CODE_POINTER;
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000839 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
Christopher Lamb25f50762007-12-12 08:44:39 +0000840 unsigned AddressSpace = PTy->getAddressSpace();
841 TypeVals.push_back(AddressSpace);
842 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000843 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000844 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000845 case Type::FunctionTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000846 FunctionType *FT = cast<FunctionType>(T);
Chad Rosier95898722011-11-03 00:14:01 +0000847 // FUNCTION: [isvararg, retty, paramty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000848 Code = bitc::TYPE_CODE_FUNCTION;
849 TypeVals.push_back(FT->isVarArg());
850 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000851 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
852 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
Chris Lattnerccee7062007-05-05 06:30:12 +0000853 AbbrevToUse = FunctionAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000854 break;
855 }
856 case Type::StructTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000857 StructType *ST = cast<StructType>(T);
Chris Lattnerccee7062007-05-05 06:30:12 +0000858 // STRUCT: [ispacked, eltty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000859 TypeVals.push_back(ST->isPacked());
Chris Lattnere14cb882007-05-04 19:11:41 +0000860 // Output all of the element types.
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000861 for (StructType::element_iterator I = ST->element_begin(),
862 E = ST->element_end(); I != E; ++I)
863 TypeVals.push_back(VE.getTypeID(*I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000864
Chris Lattner335d3992011-08-12 18:06:37 +0000865 if (ST->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000866 Code = bitc::TYPE_CODE_STRUCT_ANON;
867 AbbrevToUse = StructAnonAbbrev;
868 } else {
869 if (ST->isOpaque()) {
870 Code = bitc::TYPE_CODE_OPAQUE;
871 } else {
872 Code = bitc::TYPE_CODE_STRUCT_NAMED;
873 AbbrevToUse = StructNamedAbbrev;
874 }
875
876 // Emit the name if it is present.
877 if (!ST->getName().empty())
Teresa Johnson37687f32016-04-23 04:30:47 +0000878 writeStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
879 StructNameAbbrev);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000880 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000881 break;
882 }
883 case Type::ArrayTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000884 ArrayType *AT = cast<ArrayType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000885 // ARRAY: [numelts, eltty]
886 Code = bitc::TYPE_CODE_ARRAY;
887 TypeVals.push_back(AT->getNumElements());
888 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
Chris Lattnerccee7062007-05-05 06:30:12 +0000889 AbbrevToUse = ArrayAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000890 break;
891 }
892 case Type::VectorTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000893 VectorType *VT = cast<VectorType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000894 // VECTOR [numelts, eltty]
895 Code = bitc::TYPE_CODE_VECTOR;
896 TypeVals.push_back(VT->getNumElements());
897 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
898 break;
899 }
900 }
901
902 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000903 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000904 TypeVals.clear();
905 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000906
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000907 Stream.ExitBlock();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000908}
909
Teresa Johnson5e22e442016-02-06 16:07:35 +0000910static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
911 switch (Linkage) {
Rafael Espindola261d25b2015-01-08 16:25:01 +0000912 case GlobalValue::ExternalLinkage:
913 return 0;
914 case GlobalValue::WeakAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000915 return 16;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000916 case GlobalValue::AppendingLinkage:
917 return 2;
918 case GlobalValue::InternalLinkage:
919 return 3;
920 case GlobalValue::LinkOnceAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000921 return 18;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000922 case GlobalValue::ExternalWeakLinkage:
923 return 7;
924 case GlobalValue::CommonLinkage:
925 return 8;
926 case GlobalValue::PrivateLinkage:
927 return 9;
928 case GlobalValue::WeakODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000929 return 17;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000930 case GlobalValue::LinkOnceODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000931 return 19;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000932 case GlobalValue::AvailableExternallyLinkage:
933 return 12;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000934 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000935 llvm_unreachable("Invalid linkage");
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000936}
937
Teresa Johnson5e22e442016-02-06 16:07:35 +0000938static unsigned getEncodedLinkage(const GlobalValue &GV) {
939 return getEncodedLinkage(GV.getLinkage());
940}
941
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000942// Decode the flags for GlobalValue in the summary
943static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
944 uint64_t RawFlags = 0;
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000945
946 RawFlags |= Flags.HasSection; // bool
947
948 // Linkage don't need to be remapped at that time for the summary. Any future
949 // change to the getEncodedLinkage() function will need to be taken into
950 // account here as well.
951 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
952
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000953 return RawFlags;
954}
955
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000956static unsigned getEncodedVisibility(const GlobalValue &GV) {
957 switch (GV.getVisibility()) {
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000958 case GlobalValue::DefaultVisibility: return 0;
959 case GlobalValue::HiddenVisibility: return 1;
960 case GlobalValue::ProtectedVisibility: return 2;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000961 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000962 llvm_unreachable("Invalid visibility");
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000963}
964
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000965static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
966 switch (GV.getDLLStorageClass()) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000967 case GlobalValue::DefaultStorageClass: return 0;
968 case GlobalValue::DLLImportStorageClass: return 1;
969 case GlobalValue::DLLExportStorageClass: return 2;
970 }
971 llvm_unreachable("Invalid DLL storage class");
972}
973
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000974static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000975 switch (GV.getThreadLocalMode()) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000976 case GlobalVariable::NotThreadLocal: return 0;
977 case GlobalVariable::GeneralDynamicTLSModel: return 1;
978 case GlobalVariable::LocalDynamicTLSModel: return 2;
979 case GlobalVariable::InitialExecTLSModel: return 3;
980 case GlobalVariable::LocalExecTLSModel: return 4;
981 }
982 llvm_unreachable("Invalid TLS model");
983}
984
David Majnemerdad0a642014-06-27 18:19:56 +0000985static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
986 switch (C.getSelectionKind()) {
987 case Comdat::Any:
988 return bitc::COMDAT_SELECTION_KIND_ANY;
989 case Comdat::ExactMatch:
990 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
991 case Comdat::Largest:
992 return bitc::COMDAT_SELECTION_KIND_LARGEST;
993 case Comdat::NoDuplicates:
994 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
995 case Comdat::SameSize:
996 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
997 }
998 llvm_unreachable("Invalid selection kind");
999}
1000
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001001static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1002 switch (GV.getUnnamedAddr()) {
1003 case GlobalValue::UnnamedAddr::None: return 0;
1004 case GlobalValue::UnnamedAddr::Local: return 2;
1005 case GlobalValue::UnnamedAddr::Global: return 1;
1006 }
1007 llvm_unreachable("Invalid unnamed_addr");
1008}
1009
Teresa Johnson37687f32016-04-23 04:30:47 +00001010void ModuleBitcodeWriter::writeComdats() {
David Majnemer90a021f2016-03-13 08:01:03 +00001011 SmallVector<unsigned, 64> Vals;
David Majnemerdad0a642014-06-27 18:19:56 +00001012 for (const Comdat *C : VE.getComdats()) {
1013 // COMDAT: [selection_kind, name]
1014 Vals.push_back(getEncodedComdatSelectionKind(*C));
Rafael Espindola4e74d3b2015-01-14 18:25:45 +00001015 size_t Size = C->getName().size();
David Majnemer90a021f2016-03-13 08:01:03 +00001016 assert(isUInt<32>(Size));
Rafael Espindola4e74d3b2015-01-14 18:25:45 +00001017 Vals.push_back(Size);
David Majnemerdad0a642014-06-27 18:19:56 +00001018 for (char Chr : C->getName())
1019 Vals.push_back((unsigned char)Chr);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001020 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
David Majnemerdad0a642014-06-27 18:19:56 +00001021 Vals.clear();
1022 }
1023}
1024
Teresa Johnsonff642b92015-09-17 20:12:00 +00001025/// Write a record that will eventually hold the word offset of the
1026/// module-level VST. For now the offset is 0, which will be backpatched
Teresa Johnson37687f32016-04-23 04:30:47 +00001027/// after the real VST is written. Saves the bit offset to backpatch.
1028void BitcodeWriter::writeValueSymbolTableForwardDecl() {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001029 // Write a placeholder value in for the offset of the real VST,
1030 // which is written after the function blocks so that it can include
1031 // the offset of each function. The placeholder offset will be
1032 // updated when the real VST is written.
1033 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1034 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1035 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1036 // hold the real VST offset. Must use fixed instead of VBR as we don't
1037 // know how many VBR chunks to reserve ahead of time.
1038 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001039 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001040
1041 // Emit the placeholder
1042 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001043 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001044
Teresa Johnson37687f32016-04-23 04:30:47 +00001045 // Compute and save the bit offset to the placeholder, which will be
Teresa Johnsonff642b92015-09-17 20:12:00 +00001046 // patched when the real VST is written. We can simply subtract the 32-bit
1047 // fixed size from the current bit number to get the location to backpatch.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001048 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
Teresa Johnsonff642b92015-09-17 20:12:00 +00001049}
1050
Teresa Johnsone1164de2016-02-10 21:55:02 +00001051enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
1052
1053/// Determine the encoding to use for the given string name and length.
1054static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) {
1055 bool isChar6 = true;
1056 for (const char *C = Str, *E = C + StrLen; C != E; ++C) {
1057 if (isChar6)
1058 isChar6 = BitCodeAbbrevOp::isChar6(*C);
1059 if ((unsigned char)*C & 128)
1060 // don't bother scanning the rest.
1061 return SE_Fixed8;
1062 }
1063 if (isChar6)
1064 return SE_Char6;
1065 else
1066 return SE_Fixed7;
1067}
1068
Teresa Johnsonff642b92015-09-17 20:12:00 +00001069/// Emit top-level description of module, including target triple, inline asm,
1070/// descriptors for global variables, and function prototype info.
1071/// Returns the bit offset to backpatch with the location of the real VST.
Teresa Johnson37687f32016-04-23 04:30:47 +00001072void ModuleBitcodeWriter::writeModuleInfo() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001073 // Emit various pieces of data attached to a module.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001074 if (!M.getTargetTriple().empty())
1075 writeStringRecord(bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001076 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001077 const std::string &DL = M.getDataLayoutStr();
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001078 if (!DL.empty())
Teresa Johnson37687f32016-04-23 04:30:47 +00001079 writeStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001080 if (!M.getModuleInlineAsm().empty())
1081 writeStringRecord(bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001082 0 /*TODO*/);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001083
Gordon Henriksend930f912008-08-17 18:44:35 +00001084 // Emit information about sections and GC, computing how many there are. Also
1085 // compute the maximum alignment value.
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001086 std::map<std::string, unsigned> SectionMap;
Gordon Henriksend930f912008-08-17 18:44:35 +00001087 std::map<std::string, unsigned> GCMap;
Chris Lattner4b00d922007-04-23 16:04:05 +00001088 unsigned MaxAlignment = 0;
Chris Lattnerb5491372007-04-23 18:58:34 +00001089 unsigned MaxGlobalType = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001090 for (const GlobalValue &GV : M.globals()) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001091 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
David Blaikie1a848da2015-04-27 19:58:56 +00001092 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001093 if (GV.hasSection()) {
Chad Rosier75ec09c2011-08-12 16:45:18 +00001094 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001095 unsigned &Entry = SectionMap[GV.getSection()];
Chad Rosier75ec09c2011-08-12 16:45:18 +00001096 if (!Entry) {
Teresa Johnson37687f32016-04-23 04:30:47 +00001097 writeStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1098 0 /*TODO*/);
Chad Rosier75ec09c2011-08-12 16:45:18 +00001099 Entry = SectionMap.size();
1100 }
1101 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001102 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001103 for (const Function &F : M) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001104 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
1105 if (F.hasSection()) {
Gordon Henriksen71183b62007-12-10 03:18:06 +00001106 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001107 unsigned &Entry = SectionMap[F.getSection()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001108 if (!Entry) {
Teresa Johnson37687f32016-04-23 04:30:47 +00001109 writeStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
1110 0 /*TODO*/);
Gordon Henriksen71183b62007-12-10 03:18:06 +00001111 Entry = SectionMap.size();
1112 }
1113 }
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001114 if (F.hasGC()) {
Gordon Henriksend930f912008-08-17 18:44:35 +00001115 // Same for GC names.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001116 unsigned &Entry = GCMap[F.getGC()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001117 if (!Entry) {
Teresa Johnson37687f32016-04-23 04:30:47 +00001118 writeStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(), 0 /*TODO*/);
Gordon Henriksend930f912008-08-17 18:44:35 +00001119 Entry = GCMap.size();
Gordon Henriksen71183b62007-12-10 03:18:06 +00001120 }
1121 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001122 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001123
Chris Lattner4b00d922007-04-23 16:04:05 +00001124 // Emit abbrev for globals, now that we know # sections and max alignment.
1125 unsigned SimpleGVarAbbrev = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001126 if (!M.global_empty()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001127 // Add an abbrev for common globals with no visibility or thread localness.
1128 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1129 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
Chris Lattner2eae59f2007-05-04 20:34:50 +00001130 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001131 Log2_32_Ceil(MaxGlobalType+1)));
David Blaikie1a848da2015-04-27 19:58:56 +00001132 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1133 //| explicitType << 1
1134 //| constant
1135 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1136 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1137 if (MaxAlignment == 0) // Alignment.
Chris Lattner4b00d922007-04-23 16:04:05 +00001138 Abbv->Add(BitCodeAbbrevOp(0));
1139 else {
1140 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
Chris Lattner2eae59f2007-05-04 20:34:50 +00001141 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001142 Log2_32_Ceil(MaxEncAlignment+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001143 }
1144 if (SectionMap.empty()) // Section.
1145 Abbv->Add(BitCodeAbbrevOp(0));
1146 else
Chris Lattner2eae59f2007-05-04 20:34:50 +00001147 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattner1e50c292007-04-24 03:29:47 +00001148 Log2_32_Ceil(SectionMap.size()+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001149 // Don't bother emitting vis + thread local.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001150 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
Chris Lattner4b00d922007-04-23 16:04:05 +00001151 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001152
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001153 // Emit the global variable information.
1154 SmallVector<unsigned, 64> Vals;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001155 for (const GlobalVariable &GV : M.globals()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001156 unsigned AbbrevToUse = 0;
1157
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001158 // GLOBALVAR: [type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00001159 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00001160 // unnamed_addr, externally_initialized, dllstorageclass,
1161 // comdat]
David Blaikie1a848da2015-04-27 19:58:56 +00001162 Vals.push_back(VE.getTypeID(GV.getValueType()));
1163 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001164 Vals.push_back(GV.isDeclaration() ? 0 :
1165 (VE.getValueID(GV.getInitializer()) + 1));
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001166 Vals.push_back(getEncodedLinkage(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001167 Vals.push_back(Log2_32(GV.getAlignment())+1);
1168 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
1169 if (GV.isThreadLocal() ||
1170 GV.getVisibility() != GlobalValue::DefaultVisibility ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001171 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1172 GV.isExternallyInitialized() ||
David Majnemerdad0a642014-06-27 18:19:56 +00001173 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1174 GV.hasComdat()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001175 Vals.push_back(getEncodedVisibility(GV));
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001176 Vals.push_back(getEncodedThreadLocalMode(GV));
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001177 Vals.push_back(getEncodedUnnamedAddr(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001178 Vals.push_back(GV.isExternallyInitialized());
Nico Rieck7157bb72014-01-14 15:22:47 +00001179 Vals.push_back(getEncodedDLLStorageClass(GV));
David Majnemerdad0a642014-06-27 18:19:56 +00001180 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
Chris Lattner4b00d922007-04-23 16:04:05 +00001181 } else {
1182 AbbrevToUse = SimpleGVarAbbrev;
1183 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001184
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001185 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001186 Vals.clear();
1187 }
1188
1189 // Emit the function proto information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001190 for (const Function &F : M) {
Chad Rosier42ee1522011-12-07 23:57:55 +00001191 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment,
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001192 // section, visibility, gc, unnamed_addr, prologuedata,
David Majnemer7fddecc2015-06-17 20:52:32 +00001193 // dllstorageclass, comdat, prefixdata, personalityfn]
David Blaikie561a1572015-04-17 16:28:26 +00001194 Vals.push_back(VE.getTypeID(F.getFunctionType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001195 Vals.push_back(F.getCallingConv());
1196 Vals.push_back(F.isDeclaration());
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001197 Vals.push_back(getEncodedLinkage(F));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001198 Vals.push_back(VE.getAttributeID(F.getAttributes()));
1199 Vals.push_back(Log2_32(F.getAlignment())+1);
1200 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001201 Vals.push_back(getEncodedVisibility(F));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001202 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001203 Vals.push_back(getEncodedUnnamedAddr(F));
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001204 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1205 : 0);
Nico Rieck7157bb72014-01-14 15:22:47 +00001206 Vals.push_back(getEncodedDLLStorageClass(F));
David Majnemerdad0a642014-06-27 18:19:56 +00001207 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001208 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1209 : 0);
David Majnemer7fddecc2015-06-17 20:52:32 +00001210 Vals.push_back(
1211 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001212
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001213 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001214 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001215 Vals.clear();
1216 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001217
Chris Lattner44c17072007-04-26 02:46:40 +00001218 // Emit the alias information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001219 for (const GlobalAlias &A : M.aliases()) {
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001220 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass,
1221 // threadlocal, unnamed_addr]
David Blaikie6a51dbd2015-09-17 22:18:59 +00001222 Vals.push_back(VE.getTypeID(A.getValueType()));
1223 Vals.push_back(A.getType()->getAddressSpace());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001224 Vals.push_back(VE.getValueID(A.getAliasee()));
1225 Vals.push_back(getEncodedLinkage(A));
1226 Vals.push_back(getEncodedVisibility(A));
1227 Vals.push_back(getEncodedDLLStorageClass(A));
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001228 Vals.push_back(getEncodedThreadLocalMode(A));
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001229 Vals.push_back(getEncodedUnnamedAddr(A));
Chris Lattner44c17072007-04-26 02:46:40 +00001230 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001231 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
Chris Lattner44c17072007-04-26 02:46:40 +00001232 Vals.clear();
1233 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001234
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001235 // Emit the ifunc information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001236 for (const GlobalIFunc &I : M.ifuncs()) {
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001237 // IFUNC: [ifunc type, address space, resolver val#, linkage, visibility]
1238 Vals.push_back(VE.getTypeID(I.getValueType()));
1239 Vals.push_back(I.getType()->getAddressSpace());
1240 Vals.push_back(VE.getValueID(I.getResolver()));
1241 Vals.push_back(getEncodedLinkage(I));
1242 Vals.push_back(getEncodedVisibility(I));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001243 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001244 Vals.clear();
1245 }
1246
Teresa Johnsone1164de2016-02-10 21:55:02 +00001247 // Emit the module's source file name.
1248 {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001249 StringEncoding Bits = getStringEncoding(M.getSourceFileName().data(),
1250 M.getSourceFileName().size());
Teresa Johnsone1164de2016-02-10 21:55:02 +00001251 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1252 if (Bits == SE_Char6)
1253 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1254 else if (Bits == SE_Fixed7)
1255 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1256
1257 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1258 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1259 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1260 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1261 Abbv->Add(AbbrevOpToUse);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001262 unsigned FilenameAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnsone1164de2016-02-10 21:55:02 +00001263
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001264 for (const auto P : M.getSourceFileName())
Teresa Johnsone1164de2016-02-10 21:55:02 +00001265 Vals.push_back((unsigned char)P);
1266
1267 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001268 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
Teresa Johnsone1164de2016-02-10 21:55:02 +00001269 Vals.clear();
1270 }
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00001271
Teresa Johnson37687f32016-04-23 04:30:47 +00001272 // If we have a VST, write the VSTOFFSET record placeholder.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001273 if (M.getValueSymbolTable().empty())
Teresa Johnson37687f32016-04-23 04:30:47 +00001274 return;
1275 writeValueSymbolTableForwardDecl();
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001276}
1277
Teresa Johnson37687f32016-04-23 04:30:47 +00001278static uint64_t getOptimizationFlags(const Value *V) {
Dan Gohman0ebd6962009-07-20 21:19:07 +00001279 uint64_t Flags = 0;
1280
Sanjay Patelc00017d2014-10-15 17:45:13 +00001281 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
Dan Gohman16f54152009-08-20 17:11:38 +00001282 if (OBO->hasNoSignedWrap())
1283 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1284 if (OBO->hasNoUnsignedWrap())
1285 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001286 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
Chris Lattner35315d02011-02-06 21:44:57 +00001287 if (PEO->isExact())
1288 Flags |= 1 << bitc::PEO_EXACT;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001289 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001290 if (FPMO->hasUnsafeAlgebra())
Michael Ilseman65f14352012-12-09 21:12:04 +00001291 Flags |= FastMathFlags::UnsafeAlgebra;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001292 if (FPMO->hasNoNaNs())
Michael Ilseman65f14352012-12-09 21:12:04 +00001293 Flags |= FastMathFlags::NoNaNs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001294 if (FPMO->hasNoInfs())
Michael Ilseman65f14352012-12-09 21:12:04 +00001295 Flags |= FastMathFlags::NoInfs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001296 if (FPMO->hasNoSignedZeros())
Michael Ilseman65f14352012-12-09 21:12:04 +00001297 Flags |= FastMathFlags::NoSignedZeros;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001298 if (FPMO->hasAllowReciprocal())
Michael Ilseman65f14352012-12-09 21:12:04 +00001299 Flags |= FastMathFlags::AllowReciprocal;
Dan Gohman0ebd6962009-07-20 21:19:07 +00001300 }
1301
1302 return Flags;
1303}
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001304
Teresa Johnson37687f32016-04-23 04:30:47 +00001305void ModuleBitcodeWriter::writeValueAsMetadata(
1306 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001307 // Mimic an MDNode with a value as one operand.
1308 Value *V = MD->getValue();
1309 Record.push_back(VE.getTypeID(V->getType()));
1310 Record.push_back(VE.getValueID(V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001311 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001312 Record.clear();
1313}
1314
Teresa Johnson37687f32016-04-23 04:30:47 +00001315void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1316 SmallVectorImpl<uint64_t> &Record,
1317 unsigned Abbrev) {
Chris Lattner9b493022009-12-31 01:22:29 +00001318 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001319 Metadata *MD = N->getOperand(i);
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001320 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1321 "Unexpected function-local metadata");
1322 Record.push_back(VE.getMetadataOrNullID(MD));
Devang Patel8cca7b42009-08-04 05:01:35 +00001323 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001324 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1325 : bitc::METADATA_NODE,
1326 Record, Abbrev);
Devang Patel8cca7b42009-08-04 05:01:35 +00001327 Record.clear();
1328}
Devang Patele059ba6e2009-07-23 01:07:34 +00001329
Teresa Johnson37687f32016-04-23 04:30:47 +00001330unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001331 // Assume the column is usually under 128, and always output the inlined-at
1332 // location (it's never more expensive than building an array size 1).
1333 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1334 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1335 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1336 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1337 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1338 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1339 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001340 return Stream.EmitAbbrev(Abbv);
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001341}
1342
Teresa Johnson37687f32016-04-23 04:30:47 +00001343void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1344 SmallVectorImpl<uint64_t> &Record,
1345 unsigned &Abbrev) {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001346 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001347 Abbrev = createDILocationAbbrev();
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001348
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001349 Record.push_back(N->isDistinct());
1350 Record.push_back(N->getLine());
1351 Record.push_back(N->getColumn());
1352 Record.push_back(VE.getMetadataID(N->getScope()));
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001353 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001354
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001355 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001356 Record.clear();
1357}
1358
Teresa Johnson37687f32016-04-23 04:30:47 +00001359unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001360 // Assume the column is usually under 128, and always output the inlined-at
1361 // location (it's never more expensive than building an array size 1).
1362 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1363 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1364 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1365 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1367 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1369 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001370 return Stream.EmitAbbrev(Abbv);
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001371}
1372
Teresa Johnson37687f32016-04-23 04:30:47 +00001373void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1374 SmallVectorImpl<uint64_t> &Record,
1375 unsigned &Abbrev) {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001376 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001377 Abbrev = createGenericDINodeAbbrev();
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001378
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001379 Record.push_back(N->isDistinct());
1380 Record.push_back(N->getTag());
1381 Record.push_back(0); // Per-tag version field; unused for now.
1382
1383 for (auto &I : N->operands())
1384 Record.push_back(VE.getMetadataOrNullID(I));
1385
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001386 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001387 Record.clear();
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001388}
1389
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001390static uint64_t rotateSign(int64_t I) {
1391 uint64_t U = I;
1392 return I < 0 ? ~(U << 1) : U << 1;
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001393}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001394
Teresa Johnson37687f32016-04-23 04:30:47 +00001395void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1396 SmallVectorImpl<uint64_t> &Record,
1397 unsigned Abbrev) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001398 Record.push_back(N->isDistinct());
1399 Record.push_back(N->getCount());
Duncan P. N. Exon Smith5dcf6212015-04-07 00:39:59 +00001400 Record.push_back(rotateSign(N->getLowerBound()));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001401
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001402 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001403 Record.clear();
1404}
1405
Teresa Johnson37687f32016-04-23 04:30:47 +00001406void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1407 SmallVectorImpl<uint64_t> &Record,
1408 unsigned Abbrev) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001409 Record.push_back(N->isDistinct());
1410 Record.push_back(rotateSign(N->getValue()));
1411 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1412
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001413 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001414 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001415}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001416
Teresa Johnson37687f32016-04-23 04:30:47 +00001417void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1418 SmallVectorImpl<uint64_t> &Record,
1419 unsigned Abbrev) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001420 Record.push_back(N->isDistinct());
1421 Record.push_back(N->getTag());
1422 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1423 Record.push_back(N->getSizeInBits());
1424 Record.push_back(N->getAlignInBits());
1425 Record.push_back(N->getEncoding());
1426
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001427 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001428 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001429}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001430
Teresa Johnson37687f32016-04-23 04:30:47 +00001431void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1432 SmallVectorImpl<uint64_t> &Record,
1433 unsigned Abbrev) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001434 Record.push_back(N->isDistinct());
1435 Record.push_back(N->getTag());
1436 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1437 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1438 Record.push_back(N->getLine());
1439 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001440 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001441 Record.push_back(N->getSizeInBits());
1442 Record.push_back(N->getAlignInBits());
1443 Record.push_back(N->getOffsetInBits());
1444 Record.push_back(N->getFlags());
1445 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1446
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001447 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001448 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001449}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001450
Teresa Johnson37687f32016-04-23 04:30:47 +00001451void ModuleBitcodeWriter::writeDICompositeType(
1452 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1453 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001454 const unsigned IsNotUsedInOldTypeRef = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001455 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001456 Record.push_back(N->getTag());
1457 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1458 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1459 Record.push_back(N->getLine());
1460 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1461 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1462 Record.push_back(N->getSizeInBits());
1463 Record.push_back(N->getAlignInBits());
1464 Record.push_back(N->getOffsetInBits());
1465 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001466 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001467 Record.push_back(N->getRuntimeLang());
1468 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001469 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001470 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1471
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001472 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001473 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001474}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001475
Teresa Johnson37687f32016-04-23 04:30:47 +00001476void ModuleBitcodeWriter::writeDISubroutineType(
1477 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1478 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001479 const unsigned HasNoOldTypeRefs = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001480 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001481 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001482 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001483 Record.push_back(N->getCC());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001484
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001485 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001486 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001487}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001488
Teresa Johnson37687f32016-04-23 04:30:47 +00001489void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1490 SmallVectorImpl<uint64_t> &Record,
1491 unsigned Abbrev) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001492 Record.push_back(N->isDistinct());
1493 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1494 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1495
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001496 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001497 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001498}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001499
Teresa Johnson37687f32016-04-23 04:30:47 +00001500void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1501 SmallVectorImpl<uint64_t> &Record,
1502 unsigned Abbrev) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00001503 assert(N->isDistinct() && "Expected distinct compile units");
1504 Record.push_back(/* IsDistinct */ true);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001505 Record.push_back(N->getSourceLanguage());
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001506 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001507 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1508 Record.push_back(N->isOptimized());
1509 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1510 Record.push_back(N->getRuntimeVersion());
1511 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1512 Record.push_back(N->getEmissionKind());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001513 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1514 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
Adrian Prantl75819ae2016-04-15 15:57:41 +00001515 Record.push_back(/* subprograms */ 0);
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001516 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1517 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
Adrian Prantl1f599f92015-05-21 20:37:30 +00001518 Record.push_back(N->getDWOId());
Amjad Abouda9bcf162015-12-10 12:56:35 +00001519 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001520
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001521 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001522 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001523}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001524
Teresa Johnson37687f32016-04-23 04:30:47 +00001525void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1526 SmallVectorImpl<uint64_t> &Record,
1527 unsigned Abbrev) {
Adrian Prantl85338cb2016-05-06 22:53:06 +00001528 uint64_t HasUnitFlag = 1 << 1;
1529 Record.push_back(N->isDistinct() | HasUnitFlag);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001530 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1531 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1532 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1533 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1534 Record.push_back(N->getLine());
1535 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1536 Record.push_back(N->isLocalToUnit());
1537 Record.push_back(N->isDefinition());
1538 Record.push_back(N->getScopeLine());
1539 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1540 Record.push_back(N->getVirtuality());
1541 Record.push_back(N->getVirtualIndex());
1542 Record.push_back(N->getFlags());
1543 Record.push_back(N->isOptimized());
Adrian Prantl75819ae2016-04-15 15:57:41 +00001544 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001545 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001546 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001547 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001548 Record.push_back(N->getThisAdjustment());
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001549
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001550 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001551 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001552}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001553
Teresa Johnson37687f32016-04-23 04:30:47 +00001554void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1555 SmallVectorImpl<uint64_t> &Record,
1556 unsigned Abbrev) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001557 Record.push_back(N->isDistinct());
1558 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1559 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1560 Record.push_back(N->getLine());
1561 Record.push_back(N->getColumn());
1562
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001563 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001564 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001565}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001566
Teresa Johnson37687f32016-04-23 04:30:47 +00001567void ModuleBitcodeWriter::writeDILexicalBlockFile(
1568 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1569 unsigned Abbrev) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001570 Record.push_back(N->isDistinct());
1571 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1572 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1573 Record.push_back(N->getDiscriminator());
1574
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001575 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001576 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001577}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001578
Teresa Johnson37687f32016-04-23 04:30:47 +00001579void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1580 SmallVectorImpl<uint64_t> &Record,
1581 unsigned Abbrev) {
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001582 Record.push_back(N->isDistinct());
1583 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1584 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1585 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1586 Record.push_back(N->getLine());
1587
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001588 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001589 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001590}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001591
Teresa Johnson37687f32016-04-23 04:30:47 +00001592void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1593 SmallVectorImpl<uint64_t> &Record,
1594 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001595 Record.push_back(N->isDistinct());
1596 Record.push_back(N->getMacinfoType());
1597 Record.push_back(N->getLine());
1598 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1599 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1600
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001601 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001602 Record.clear();
1603}
1604
Teresa Johnson37687f32016-04-23 04:30:47 +00001605void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1606 SmallVectorImpl<uint64_t> &Record,
1607 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001608 Record.push_back(N->isDistinct());
1609 Record.push_back(N->getMacinfoType());
1610 Record.push_back(N->getLine());
1611 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1612 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1613
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001614 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001615 Record.clear();
1616}
1617
Teresa Johnson37687f32016-04-23 04:30:47 +00001618void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1619 SmallVectorImpl<uint64_t> &Record,
1620 unsigned Abbrev) {
Adrian Prantlab1243f2015-06-29 23:03:47 +00001621 Record.push_back(N->isDistinct());
1622 for (auto &I : N->operands())
1623 Record.push_back(VE.getMetadataOrNullID(I));
1624
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001625 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
Adrian Prantlab1243f2015-06-29 23:03:47 +00001626 Record.clear();
1627}
1628
Teresa Johnson37687f32016-04-23 04:30:47 +00001629void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1630 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1631 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001632 Record.push_back(N->isDistinct());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001633 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1634 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1635
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001636 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001637 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001638}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001639
Teresa Johnson37687f32016-04-23 04:30:47 +00001640void ModuleBitcodeWriter::writeDITemplateValueParameter(
1641 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1642 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001643 Record.push_back(N->isDistinct());
1644 Record.push_back(N->getTag());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001645 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1646 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1647 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1648
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001649 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001650 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001651}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001652
Teresa Johnson37687f32016-04-23 04:30:47 +00001653void ModuleBitcodeWriter::writeDIGlobalVariable(
1654 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1655 unsigned Abbrev) {
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001656 Record.push_back(N->isDistinct());
1657 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1658 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1659 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1660 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1661 Record.push_back(N->getLine());
1662 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1663 Record.push_back(N->isLocalToUnit());
1664 Record.push_back(N->isDefinition());
Duncan P. N. Exon Smith7ad0bd52015-04-11 20:27:40 +00001665 Record.push_back(VE.getMetadataOrNullID(N->getRawVariable()));
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001666 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1667
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001668 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001669 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001670}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001671
Teresa Johnson37687f32016-04-23 04:30:47 +00001672void ModuleBitcodeWriter::writeDILocalVariable(
1673 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1674 unsigned Abbrev) {
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001675 Record.push_back(N->isDistinct());
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001676 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1677 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1678 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1679 Record.push_back(N->getLine());
1680 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1681 Record.push_back(N->getArg());
1682 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001683
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001684 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001685 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001686}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001687
Teresa Johnson37687f32016-04-23 04:30:47 +00001688void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1689 SmallVectorImpl<uint64_t> &Record,
1690 unsigned Abbrev) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001691 Record.reserve(N->getElements().size() + 1);
1692
1693 Record.push_back(N->isDistinct());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001694 Record.append(N->elements_begin(), N->elements_end());
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001695
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001696 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001697 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001698}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001699
Teresa Johnson37687f32016-04-23 04:30:47 +00001700void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1701 SmallVectorImpl<uint64_t> &Record,
1702 unsigned Abbrev) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001703 Record.push_back(N->isDistinct());
1704 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1705 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1706 Record.push_back(N->getLine());
1707 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1708 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1709 Record.push_back(N->getAttributes());
1710 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1711
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001712 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001713 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001714}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001715
Teresa Johnson37687f32016-04-23 04:30:47 +00001716void ModuleBitcodeWriter::writeDIImportedEntity(
1717 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1718 unsigned Abbrev) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001719 Record.push_back(N->isDistinct());
1720 Record.push_back(N->getTag());
1721 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1722 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1723 Record.push_back(N->getLine());
1724 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1725
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001726 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001727 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001728}
1729
Teresa Johnson37687f32016-04-23 04:30:47 +00001730unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001731 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1732 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1733 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1734 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001735 return Stream.EmitAbbrev(Abbv);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001736}
1737
Teresa Johnson37687f32016-04-23 04:30:47 +00001738void ModuleBitcodeWriter::writeNamedMetadata(
1739 SmallVectorImpl<uint64_t> &Record) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001740 if (M.named_metadata_empty())
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001741 return;
1742
Teresa Johnson37687f32016-04-23 04:30:47 +00001743 unsigned Abbrev = createNamedMetadataAbbrev();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001744 for (const NamedMDNode &NMD : M.named_metadata()) {
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001745 // Write name.
1746 StringRef Str = NMD.getName();
1747 Record.append(Str.bytes_begin(), Str.bytes_end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001748 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001749 Record.clear();
1750
1751 // Write named metadata operands.
1752 for (const MDNode *N : NMD.operands())
1753 Record.push_back(VE.getMetadataID(N));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001754 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001755 Record.clear();
1756 }
1757}
1758
Teresa Johnson37687f32016-04-23 04:30:47 +00001759unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001760 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1761 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1762 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1763 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1764 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001765 return Stream.EmitAbbrev(Abbv);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001766}
1767
1768/// Write out a record for MDString.
1769///
1770/// All the metadata strings in a metadata block are emitted in a single
1771/// record. The sizes and strings themselves are shoved into a blob.
Teresa Johnson37687f32016-04-23 04:30:47 +00001772void ModuleBitcodeWriter::writeMetadataStrings(
1773 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001774 if (Strings.empty())
1775 return;
1776
1777 // Start the record with the number of strings.
1778 Record.push_back(bitc::METADATA_STRINGS);
1779 Record.push_back(Strings.size());
1780
1781 // Emit the sizes of the strings in the blob.
1782 SmallString<256> Blob;
1783 {
1784 BitstreamWriter W(Blob);
1785 for (const Metadata *MD : Strings)
1786 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1787 W.FlushToWord();
1788 }
1789
1790 // Add the offset to the strings to the record.
1791 Record.push_back(Blob.size());
1792
1793 // Add the strings to the blob.
1794 for (const Metadata *MD : Strings)
1795 Blob.append(cast<MDString>(MD)->getString());
1796
1797 // Emit the final record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001798 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001799 Record.clear();
1800}
1801
Teresa Johnson37687f32016-04-23 04:30:47 +00001802void ModuleBitcodeWriter::writeMetadataRecords(
1803 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001804 if (MDs.empty())
Duncan P. N. Exon Smith2fcf60e2015-01-12 22:30:34 +00001805 return;
1806
Duncan P. N. Exon Smith6b7b6802015-02-04 21:54:12 +00001807 // Initialize MDNode abbreviations.
1808#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1809#include "llvm/IR/Metadata.def"
1810
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001811 for (const Metadata *MD : MDs) {
Duncan P. N. Exon Smith73d5aae2015-01-12 22:31:35 +00001812 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
Duncan P. N. Exon Smith79f8d112015-03-17 00:16:35 +00001813 assert(N->isResolved() && "Expected forward references to be resolved");
1814
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001815 switch (N->getMetadataID()) {
1816 default:
1817 llvm_unreachable("Invalid MDNode subclass");
1818#define HANDLE_MDNODE_LEAF(CLASS) \
1819 case Metadata::CLASS##Kind: \
Teresa Johnson37687f32016-04-23 04:30:47 +00001820 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001821 continue;
1822#include "llvm/IR/Metadata.def"
1823 }
Devang Patel8cca7b42009-08-04 05:01:35 +00001824 }
Teresa Johnson37687f32016-04-23 04:30:47 +00001825 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
Devang Patel8cca7b42009-08-04 05:01:35 +00001826 }
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001827}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001828
Teresa Johnson37687f32016-04-23 04:30:47 +00001829void ModuleBitcodeWriter::writeModuleMetadata() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001830 if (!VE.hasMDs() && M.named_metadata_empty())
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001831 return;
1832
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001833 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001834 SmallVector<uint64_t, 64> Record;
Teresa Johnson37687f32016-04-23 04:30:47 +00001835 writeMetadataStrings(VE.getMDStrings(), Record);
1836 writeMetadataRecords(VE.getNonMDStrings(), Record);
1837 writeNamedMetadata(Record);
Peter Collingbourne21521892016-06-21 23:42:48 +00001838
1839 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
1840 SmallVector<uint64_t, 4> Record;
1841 Record.push_back(VE.getValueID(&GO));
1842 pushGlobalMetadataAttachment(Record, GO);
1843 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
1844 };
1845 for (const Function &F : M)
1846 if (F.isDeclaration() && F.hasMetadata())
1847 AddDeclAttachedMetadata(F);
1848 // FIXME: Only store metadata for declarations here, and move data for global
1849 // variable definitions to a separate block (PR28134).
1850 for (const GlobalVariable &GV : M.globals())
1851 if (GV.hasMetadata())
1852 AddDeclAttachedMetadata(GV);
1853
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001854 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00001855}
1856
Teresa Johnson37687f32016-04-23 04:30:47 +00001857void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
Duncan P. N. Exon Smith93429112016-04-02 15:09:42 +00001858 if (!VE.hasMDs())
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00001859 return;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001860
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001861 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00001862 SmallVector<uint64_t, 64> Record;
Teresa Johnson37687f32016-04-23 04:30:47 +00001863 writeMetadataStrings(VE.getMDStrings(), Record);
1864 writeMetadataRecords(VE.getNonMDStrings(), Record);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001865 Stream.ExitBlock();
Victor Hernandezb00a6be2010-01-13 19:37:33 +00001866}
1867
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001868void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
1869 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
1870 // [n x [id, mdnode]]
1871 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1872 GO.getAllMetadata(MDs);
1873 for (const auto &I : MDs) {
1874 Record.push_back(I.first);
1875 Record.push_back(VE.getMetadataID(I.second));
1876 }
1877}
1878
1879void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001880 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
Chris Lattner07d09ed2010-04-03 02:17:50 +00001881
Devang Patelaf206b82009-09-18 19:26:43 +00001882 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001883
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001884 if (F.hasMetadata()) {
1885 pushGlobalMetadataAttachment(Record, F);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001886 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001887 Record.clear();
1888 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001889
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001890 // Write metadata attachments
1891 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1892 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00001893 for (const BasicBlock &BB : F)
1894 for (const Instruction &I : BB) {
Devang Patel6da5dbf2009-10-22 18:55:16 +00001895 MDs.clear();
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00001896 I.getAllMetadataOtherThanDebugLoc(MDs);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001897
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001898 // If no metadata, ignore instruction.
1899 if (MDs.empty()) continue;
1900
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00001901 Record.push_back(VE.getInstructionID(&I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001902
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001903 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1904 Record.push_back(MDs[i].first);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001905 Record.push_back(VE.getMetadataID(MDs[i].second));
Devang Patelaf206b82009-09-18 19:26:43 +00001906 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001907 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001908 Record.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00001909 }
1910
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001911 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00001912}
1913
Peter Collingbourne21521892016-06-21 23:42:48 +00001914void ModuleBitcodeWriter::writeModuleMetadataKinds() {
Devang Patelaf206b82009-09-18 19:26:43 +00001915 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001916
Devang Patelaf206b82009-09-18 19:26:43 +00001917 // Write metadata kinds
1918 // METADATA_KIND - [n x [id, name]]
Michael Ilseman979dfbb2012-12-03 22:57:47 +00001919 SmallVector<StringRef, 8> Names;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001920 M.getMDKindNames(Names);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001921
Dan Gohman43aa8f02010-07-20 21:42:28 +00001922 if (Names.empty()) return;
Chris Lattnerc9558df2009-12-28 20:10:43 +00001923
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001924 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001925
Dan Gohman43aa8f02010-07-20 21:42:28 +00001926 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
Chris Lattnerc9558df2009-12-28 20:10:43 +00001927 Record.push_back(MDKindID);
1928 StringRef KName = Names[MDKindID];
1929 Record.append(KName.begin(), KName.end());
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001930
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001931 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
Devang Patelaf206b82009-09-18 19:26:43 +00001932 Record.clear();
1933 }
1934
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001935 Stream.ExitBlock();
Devang Patel8cca7b42009-08-04 05:01:35 +00001936}
1937
Teresa Johnson37687f32016-04-23 04:30:47 +00001938void ModuleBitcodeWriter::writeOperandBundleTags() {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001939 // Write metadata kinds
1940 //
1941 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
1942 //
1943 // OPERAND_BUNDLE_TAG - [strchr x N]
1944
1945 SmallVector<StringRef, 8> Tags;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001946 M.getOperandBundleTags(Tags);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001947
1948 if (Tags.empty())
1949 return;
1950
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001951 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001952
1953 SmallVector<uint64_t, 64> Record;
1954
1955 for (auto Tag : Tags) {
1956 Record.append(Tag.begin(), Tag.end());
1957
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001958 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001959 Record.clear();
1960 }
1961
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001962 Stream.ExitBlock();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001963}
1964
Jan Wen Voungafaced02012-10-11 20:20:40 +00001965static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
1966 if ((int64_t)V >= 0)
1967 Vals.push_back(V << 1);
1968 else
1969 Vals.push_back((-V << 1) | 1);
1970}
1971
Teresa Johnson37687f32016-04-23 04:30:47 +00001972void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
1973 bool isGlobal) {
Devang Patel8cca7b42009-08-04 05:01:35 +00001974 if (FirstVal == LastVal) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001975
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001976 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
Devang Patel8cca7b42009-08-04 05:01:35 +00001977
1978 unsigned AggregateAbbrev = 0;
1979 unsigned String8Abbrev = 0;
1980 unsigned CString7Abbrev = 0;
1981 unsigned CString6Abbrev = 0;
1982 // If this is a constant pool for the module, emit module-specific abbrevs.
1983 if (isGlobal) {
1984 // Abbrev for CST_CODE_AGGREGATE.
1985 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
1986 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
1987 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1988 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001989 AggregateAbbrev = Stream.EmitAbbrev(Abbv);
Devang Patel8cca7b42009-08-04 05:01:35 +00001990
1991 // Abbrev for CST_CODE_STRING.
1992 Abbv = new BitCodeAbbrev();
1993 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
1994 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1995 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001996 String8Abbrev = Stream.EmitAbbrev(Abbv);
Devang Patel8cca7b42009-08-04 05:01:35 +00001997 // Abbrev for CST_CODE_CSTRING.
1998 Abbv = new BitCodeAbbrev();
1999 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2000 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2001 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002002 CString7Abbrev = Stream.EmitAbbrev(Abbv);
Devang Patel8cca7b42009-08-04 05:01:35 +00002003 // Abbrev for CST_CODE_CSTRING.
2004 Abbv = new BitCodeAbbrev();
2005 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2006 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2007 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002008 CString6Abbrev = Stream.EmitAbbrev(Abbv);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002009 }
2010
Devang Patel8cca7b42009-08-04 05:01:35 +00002011 SmallVector<uint64_t, 64> Record;
2012
2013 const ValueEnumerator::ValueList &Vals = VE.getValues();
Craig Topper2617dcc2014-04-15 06:32:26 +00002014 Type *LastTy = nullptr;
Devang Patel8cca7b42009-08-04 05:01:35 +00002015 for (unsigned i = FirstVal; i != LastVal; ++i) {
2016 const Value *V = Vals[i].first;
Chris Lattner52523562007-04-24 00:16:04 +00002017 // If we need to switch types, do so now.
2018 if (V->getType() != LastTy) {
2019 LastTy = V->getType();
2020 Record.push_back(VE.getTypeID(LastTy));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002021 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2022 CONSTANTS_SETTYPE_ABBREV);
Chris Lattner52523562007-04-24 00:16:04 +00002023 Record.clear();
2024 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002025
Chris Lattner52523562007-04-24 00:16:04 +00002026 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
Dale Johannesenfd04c742009-10-13 20:46:56 +00002027 Record.push_back(unsigned(IA->hasSideEffects()) |
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002028 unsigned(IA->isAlignStack()) << 1 |
2029 unsigned(IA->getDialect()&1) << 2);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002030
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002031 // Add the asm string.
2032 const std::string &AsmStr = IA->getAsmString();
2033 Record.push_back(AsmStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002034 Record.append(AsmStr.begin(), AsmStr.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002035
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002036 // Add the constraint string.
2037 const std::string &ConstraintStr = IA->getConstraintString();
2038 Record.push_back(ConstraintStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002039 Record.append(ConstraintStr.begin(), ConstraintStr.end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002040 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002041 Record.clear();
Chris Lattner52523562007-04-24 00:16:04 +00002042 continue;
2043 }
2044 const Constant *C = cast<Constant>(V);
2045 unsigned Code = -1U;
2046 unsigned AbbrevToUse = 0;
2047 if (C->isNullValue()) {
2048 Code = bitc::CST_CODE_NULL;
2049 } else if (isa<UndefValue>(C)) {
2050 Code = bitc::CST_CODE_UNDEF;
2051 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
Bob Wilsone4077362013-09-09 19:14:35 +00002052 if (IV->getBitWidth() <= 64) {
2053 uint64_t V = IV->getSExtValue();
2054 emitSignedInt64(Record, V);
2055 Code = bitc::CST_CODE_INTEGER;
2056 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2057 } else { // Wide integers, > 64 bits in size.
2058 // We have an arbitrary precision integer value to write whose
2059 // bit width is > 64. However, in canonical unsigned integer
2060 // format it is likely that the high bits are going to be zero.
2061 // So, we only write the number of active words.
2062 unsigned NWords = IV->getValue().getActiveWords();
2063 const uint64_t *RawWords = IV->getValue().getRawData();
2064 for (unsigned i = 0; i != NWords; ++i) {
2065 emitSignedInt64(Record, RawWords[i]);
2066 }
2067 Code = bitc::CST_CODE_WIDE_INTEGER;
2068 }
Chris Lattner52523562007-04-24 00:16:04 +00002069 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2070 Code = bitc::CST_CODE_FLOAT;
Chris Lattner229907c2011-07-18 04:54:35 +00002071 Type *Ty = CFP->getType();
Dan Gohman518cda42011-12-17 00:04:22 +00002072 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002073 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
Chris Lattnerfdd87902009-10-05 05:54:46 +00002074 } else if (Ty->isX86_FP80Ty()) {
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002075 // api needed to prevent premature destruction
Dale Johannesen93eefa02009-03-23 21:16:53 +00002076 // bits are not in the same order as a normal i80 APInt, compensate.
Dale Johannesen54306fe2008-10-09 18:53:47 +00002077 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002078 const uint64_t *p = api.getRawData();
Dale Johannesen93eefa02009-03-23 21:16:53 +00002079 Record.push_back((p[1] << 48) | (p[0] >> 16));
2080 Record.push_back(p[0] & 0xffffLL);
Chris Lattnerfdd87902009-10-05 05:54:46 +00002081 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002082 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002083 const uint64_t *p = api.getRawData();
Dale Johannesen245dceb2007-09-11 18:32:33 +00002084 Record.push_back(p[0]);
2085 Record.push_back(p[1]);
Dale Johannesenbdad8092007-08-09 22:51:36 +00002086 } else {
2087 assert (0 && "Unknown FP type!");
Chris Lattner52523562007-04-24 00:16:04 +00002088 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002089 } else if (isa<ConstantDataSequential>(C) &&
2090 cast<ConstantDataSequential>(C)->isString()) {
2091 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2092 // Emit constant strings specially.
2093 unsigned NumElts = Str->getNumElements();
2094 // If this is a null-terminated string, use the denser CSTRING encoding.
2095 if (Str->isCString()) {
2096 Code = bitc::CST_CODE_CSTRING;
2097 --NumElts; // Don't encode the null, which isn't allowed by char6.
2098 } else {
2099 Code = bitc::CST_CODE_STRING;
2100 AbbrevToUse = String8Abbrev;
2101 }
2102 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2103 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2104 for (unsigned i = 0; i != NumElts; ++i) {
2105 unsigned char V = Str->getElementAsInteger(i);
2106 Record.push_back(V);
2107 isCStr7 &= (V & 128) == 0;
2108 if (isCStrChar6)
2109 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2110 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002111
Chris Lattner372dd1e2012-01-30 00:51:16 +00002112 if (isCStrChar6)
2113 AbbrevToUse = CString6Abbrev;
2114 else if (isCStr7)
2115 AbbrevToUse = CString7Abbrev;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002116 } else if (const ConstantDataSequential *CDS =
Chris Lattner372dd1e2012-01-30 00:51:16 +00002117 dyn_cast<ConstantDataSequential>(C)) {
Chris Lattner5d917072012-01-30 07:36:01 +00002118 Code = bitc::CST_CODE_DATA;
Chris Lattner372dd1e2012-01-30 00:51:16 +00002119 Type *EltTy = CDS->getType()->getElementType();
2120 if (isa<IntegerType>(EltTy)) {
2121 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2122 Record.push_back(CDS->getElementAsInteger(i));
Chris Lattner372dd1e2012-01-30 00:51:16 +00002123 } else {
Justin Bognera43eacb2016-01-06 22:31:32 +00002124 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2125 Record.push_back(
2126 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002127 }
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00002128 } else if (isa<ConstantAggregate>(C)) {
Chris Lattner52523562007-04-24 00:16:04 +00002129 Code = bitc::CST_CODE_AGGREGATE;
Pete Cooper125ad172015-06-25 20:51:38 +00002130 for (const Value *Op : C->operands())
2131 Record.push_back(VE.getValueID(Op));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002132 AbbrevToUse = AggregateAbbrev;
Chris Lattner52523562007-04-24 00:16:04 +00002133 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002134 switch (CE->getOpcode()) {
2135 default:
2136 if (Instruction::isCast(CE->getOpcode())) {
2137 Code = bitc::CST_CODE_CE_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002138 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002139 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2140 Record.push_back(VE.getValueID(C->getOperand(0)));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002141 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002142 } else {
2143 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2144 Code = bitc::CST_CODE_CE_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002145 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002146 Record.push_back(VE.getValueID(C->getOperand(0)));
2147 Record.push_back(VE.getValueID(C->getOperand(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002148 uint64_t Flags = getOptimizationFlags(CE);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002149 if (Flags != 0)
2150 Record.push_back(Flags);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002151 }
2152 break;
David Blaikieb9263572015-03-13 21:03:36 +00002153 case Instruction::GetElementPtr: {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002154 Code = bitc::CST_CODE_CE_GEP;
David Blaikieb9263572015-03-13 21:03:36 +00002155 const auto *GO = cast<GEPOperator>(C);
2156 if (GO->isInBounds())
Dan Gohman1639c392009-07-27 21:53:46 +00002157 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
David Blaikieb9263572015-03-13 21:03:36 +00002158 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002159 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2160 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2161 Record.push_back(VE.getValueID(C->getOperand(i)));
2162 }
2163 break;
David Blaikieb9263572015-03-13 21:03:36 +00002164 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002165 case Instruction::Select:
2166 Code = bitc::CST_CODE_CE_SELECT;
2167 Record.push_back(VE.getValueID(C->getOperand(0)));
2168 Record.push_back(VE.getValueID(C->getOperand(1)));
2169 Record.push_back(VE.getValueID(C->getOperand(2)));
2170 break;
2171 case Instruction::ExtractElement:
2172 Code = bitc::CST_CODE_CE_EXTRACTELT;
2173 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2174 Record.push_back(VE.getValueID(C->getOperand(0)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002175 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002176 Record.push_back(VE.getValueID(C->getOperand(1)));
2177 break;
2178 case Instruction::InsertElement:
2179 Code = bitc::CST_CODE_CE_INSERTELT;
2180 Record.push_back(VE.getValueID(C->getOperand(0)));
2181 Record.push_back(VE.getValueID(C->getOperand(1)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002182 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002183 Record.push_back(VE.getValueID(C->getOperand(2)));
2184 break;
2185 case Instruction::ShuffleVector:
Nate Begeman94aa38d2009-02-12 21:28:33 +00002186 // If the return type and argument types are the same, this is a
2187 // standard shufflevector instruction. If the types are different,
2188 // then the shuffle is widening or truncating the input vectors, and
2189 // the argument type must also be encoded.
2190 if (C->getType() == C->getOperand(0)->getType()) {
2191 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2192 } else {
2193 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2194 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2195 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002196 Record.push_back(VE.getValueID(C->getOperand(0)));
2197 Record.push_back(VE.getValueID(C->getOperand(1)));
2198 Record.push_back(VE.getValueID(C->getOperand(2)));
2199 break;
2200 case Instruction::ICmp:
2201 case Instruction::FCmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002202 Code = bitc::CST_CODE_CE_CMP;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002203 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2204 Record.push_back(VE.getValueID(C->getOperand(0)));
2205 Record.push_back(VE.getValueID(C->getOperand(1)));
2206 Record.push_back(CE->getPredicate());
2207 break;
2208 }
Chris Lattnerf540d742009-10-28 05:24:40 +00002209 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
Chris Lattnerf540d742009-10-28 05:24:40 +00002210 Code = bitc::CST_CODE_BLOCKADDRESS;
2211 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2212 Record.push_back(VE.getValueID(BA->getFunction()));
2213 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
Chris Lattner52523562007-04-24 00:16:04 +00002214 } else {
Dan Gohman47dc8fd2010-07-21 21:18:37 +00002215#ifndef NDEBUG
2216 C->dump();
2217#endif
Torok Edwinfbcc6632009-07-14 16:55:14 +00002218 llvm_unreachable("Unknown constant!");
Chris Lattner52523562007-04-24 00:16:04 +00002219 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002220 Stream.EmitRecord(Code, Record, AbbrevToUse);
Chris Lattner52523562007-04-24 00:16:04 +00002221 Record.clear();
2222 }
2223
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002224 Stream.ExitBlock();
Chris Lattner52523562007-04-24 00:16:04 +00002225}
2226
Teresa Johnson37687f32016-04-23 04:30:47 +00002227void ModuleBitcodeWriter::writeModuleConstants() {
Chris Lattner52523562007-04-24 00:16:04 +00002228 const ValueEnumerator::ValueList &Vals = VE.getValues();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002229
Chris Lattner52523562007-04-24 00:16:04 +00002230 // Find the first constant to emit, which is the first non-globalvalue value.
2231 // We know globalvalues have been emitted by WriteModuleInfo.
2232 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2233 if (!isa<GlobalValue>(Vals[i].first)) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002234 writeConstants(i, Vals.size(), true);
Chris Lattner52523562007-04-24 00:16:04 +00002235 return;
2236 }
2237 }
2238}
Chris Lattner215e9cd2007-04-23 20:35:01 +00002239
Teresa Johnson37687f32016-04-23 04:30:47 +00002240/// pushValueAndType - The file has to encode both the value and type id for
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002241/// many values, because we need to know what type to create for forward
2242/// references. However, most operands are not forward references, so this type
2243/// field is not needed.
2244///
2245/// This function adds V's value ID to Vals. If the value ID is higher than the
2246/// instruction ID, then it is a forward reference, and it also includes the
Jan Wen Voungafaced02012-10-11 20:20:40 +00002247/// type ID. The value ID that is written is encoded relative to the InstID.
Teresa Johnson37687f32016-04-23 04:30:47 +00002248bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2249 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002250 unsigned ValID = VE.getValueID(V);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002251 // Make encoding relative to the InstID.
2252 Vals.push_back(InstID - ValID);
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002253 if (ValID >= InstID) {
2254 Vals.push_back(VE.getTypeID(V->getType()));
2255 return true;
2256 }
2257 return false;
2258}
2259
Teresa Johnson37687f32016-04-23 04:30:47 +00002260void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2261 unsigned InstID) {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002262 SmallVector<unsigned, 64> Record;
2263 LLVMContext &C = CS.getInstruction()->getContext();
2264
2265 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
Sanjoy Das54c3ca62015-11-07 01:56:04 +00002266 const auto &Bundle = CS.getOperandBundleAt(i);
Sanjoy Dasb9ca6dc2015-11-10 20:13:15 +00002267 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002268
2269 for (auto &Input : Bundle.Inputs)
Teresa Johnson37687f32016-04-23 04:30:47 +00002270 pushValueAndType(Input, InstID, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002271
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002272 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002273 Record.clear();
2274 }
2275}
2276
Teresa Johnson37687f32016-04-23 04:30:47 +00002277/// pushValue - Like pushValueAndType, but where the type of the value is
Jan Wen Voungafaced02012-10-11 20:20:40 +00002278/// omitted (perhaps it was already encoded in an earlier operand).
Teresa Johnson37687f32016-04-23 04:30:47 +00002279void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2280 SmallVectorImpl<unsigned> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002281 unsigned ValID = VE.getValueID(V);
2282 Vals.push_back(InstID - ValID);
2283}
2284
Teresa Johnson37687f32016-04-23 04:30:47 +00002285void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2286 SmallVectorImpl<uint64_t> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002287 unsigned ValID = VE.getValueID(V);
2288 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2289 emitSignedInt64(Vals, diff);
2290}
2291
Chris Lattnere6e364c2007-04-26 05:53:54 +00002292/// WriteInstruction - Emit an instruction to the specified stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00002293void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2294 unsigned InstID,
2295 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnere6e364c2007-04-26 05:53:54 +00002296 unsigned Code = 0;
2297 unsigned AbbrevToUse = 0;
Devang Patelaf206b82009-09-18 19:26:43 +00002298 VE.setInstructionID(&I);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002299 switch (I.getOpcode()) {
2300 default:
2301 if (Instruction::isCast(I.getOpcode())) {
Chris Lattner0a603252007-05-01 02:13:26 +00002302 Code = bitc::FUNC_CODE_INST_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002303 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002304 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002305 Vals.push_back(VE.getTypeID(I.getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002306 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
Chris Lattnere6e364c2007-04-26 05:53:54 +00002307 } else {
2308 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
Chris Lattner9f35f912007-05-02 04:26:36 +00002309 Code = bitc::FUNC_CODE_INST_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002310 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002311 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
Teresa Johnson37687f32016-04-23 04:30:47 +00002312 pushValue(I.getOperand(1), InstID, Vals);
2313 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2314 uint64_t Flags = getOptimizationFlags(&I);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002315 if (Flags != 0) {
2316 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2317 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2318 Vals.push_back(Flags);
2319 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002320 }
2321 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002322
David Blaikieb5b5efd2015-02-25 01:08:52 +00002323 case Instruction::GetElementPtr: {
Chris Lattner0a603252007-05-01 02:13:26 +00002324 Code = bitc::FUNC_CODE_INST_GEP;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002325 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2326 auto &GEPInst = cast<GetElementPtrInst>(I);
2327 Vals.push_back(GEPInst.isInBounds());
2328 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002329 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002330 pushValueAndType(I.getOperand(i), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002331 break;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002332 }
Dan Gohmanca0256a2008-05-31 19:11:15 +00002333 case Instruction::ExtractValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002334 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002335 pushValueAndType(I.getOperand(0), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002336 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002337 Vals.append(EVI->idx_begin(), EVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002338 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002339 }
2340 case Instruction::InsertValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002341 Code = bitc::FUNC_CODE_INST_INSERTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002342 pushValueAndType(I.getOperand(0), InstID, Vals);
2343 pushValueAndType(I.getOperand(1), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002344 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002345 Vals.append(IVI->idx_begin(), IVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002346 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002347 }
Chris Lattner0a603252007-05-01 02:13:26 +00002348 case Instruction::Select:
Dan Gohmanc5d28922008-09-16 01:01:33 +00002349 Code = bitc::FUNC_CODE_INST_VSELECT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002350 pushValueAndType(I.getOperand(1), InstID, Vals);
2351 pushValue(I.getOperand(2), InstID, Vals);
2352 pushValueAndType(I.getOperand(0), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002353 break;
2354 case Instruction::ExtractElement:
2355 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002356 pushValueAndType(I.getOperand(0), InstID, Vals);
2357 pushValueAndType(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002358 break;
2359 case Instruction::InsertElement:
2360 Code = bitc::FUNC_CODE_INST_INSERTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002361 pushValueAndType(I.getOperand(0), InstID, Vals);
2362 pushValue(I.getOperand(1), InstID, Vals);
2363 pushValueAndType(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002364 break;
2365 case Instruction::ShuffleVector:
2366 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002367 pushValueAndType(I.getOperand(0), InstID, Vals);
2368 pushValue(I.getOperand(1), InstID, Vals);
2369 pushValue(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002370 break;
2371 case Instruction::ICmp:
James Molloy88eb5352015-07-10 12:52:00 +00002372 case Instruction::FCmp: {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002373 // compare returning Int1Ty or vector of Int1Ty
2374 Code = bitc::FUNC_CODE_INST_CMP2;
Teresa Johnson37687f32016-04-23 04:30:47 +00002375 pushValueAndType(I.getOperand(0), InstID, Vals);
2376 pushValue(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002377 Vals.push_back(cast<CmpInst>(I).getPredicate());
Teresa Johnson37687f32016-04-23 04:30:47 +00002378 uint64_t Flags = getOptimizationFlags(&I);
James Molloy88eb5352015-07-10 12:52:00 +00002379 if (Flags != 0)
2380 Vals.push_back(Flags);
Chris Lattner0a603252007-05-01 02:13:26 +00002381 break;
James Molloy88eb5352015-07-10 12:52:00 +00002382 }
Chris Lattner0a603252007-05-01 02:13:26 +00002383
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002384 case Instruction::Ret:
Devang Patelbbfd8742008-02-26 01:29:32 +00002385 {
2386 Code = bitc::FUNC_CODE_INST_RET;
2387 unsigned NumOperands = I.getNumOperands();
Devang Patelbbfd8742008-02-26 01:29:32 +00002388 if (NumOperands == 0)
2389 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2390 else if (NumOperands == 1) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002391 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Devang Patelbbfd8742008-02-26 01:29:32 +00002392 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2393 } else {
2394 for (unsigned i = 0, e = NumOperands; i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002395 pushValueAndType(I.getOperand(i), InstID, Vals);
Devang Patelbbfd8742008-02-26 01:29:32 +00002396 }
2397 }
Chris Lattner0a603252007-05-01 02:13:26 +00002398 break;
2399 case Instruction::Br:
Gabor Greif1933b002009-01-30 18:27:21 +00002400 {
2401 Code = bitc::FUNC_CODE_INST_BR;
David Blaikieb78e9e52013-02-11 01:16:51 +00002402 const BranchInst &II = cast<BranchInst>(I);
Gabor Greif1933b002009-01-30 18:27:21 +00002403 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2404 if (II.isConditional()) {
2405 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002406 pushValue(II.getCondition(), InstID, Vals);
Gabor Greif1933b002009-01-30 18:27:21 +00002407 }
Chris Lattner0a603252007-05-01 02:13:26 +00002408 }
2409 break;
2410 case Instruction::Switch:
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002411 {
2412 Code = bitc::FUNC_CODE_INST_SWITCH;
David Blaikieb78e9e52013-02-11 01:16:51 +00002413 const SwitchInst &SI = cast<SwitchInst>(I);
Bob Wilsone4077362013-09-09 19:14:35 +00002414 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002415 pushValue(SI.getCondition(), InstID, Vals);
Bob Wilsone4077362013-09-09 19:14:35 +00002416 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
Sanjay Patel225d65f2015-11-13 16:21:23 +00002417 for (SwitchInst::ConstCaseIt Case : SI.cases()) {
2418 Vals.push_back(VE.getValueID(Case.getCaseValue()));
2419 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002420 }
2421 }
Chris Lattner0a603252007-05-01 02:13:26 +00002422 break;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00002423 case Instruction::IndirectBr:
2424 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
Chris Lattner3ed871f2009-10-27 19:13:16 +00002425 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Jan Wen Voungafaced02012-10-11 20:20:40 +00002426 // Encode the address operand as relative, but not the basic blocks.
Teresa Johnson37687f32016-04-23 04:30:47 +00002427 pushValue(I.getOperand(0), InstID, Vals);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002428 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
Chris Lattner3ed871f2009-10-27 19:13:16 +00002429 Vals.push_back(VE.getValueID(I.getOperand(i)));
2430 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002431
Chris Lattnerb811e952007-05-01 07:03:37 +00002432 case Instruction::Invoke: {
Gabor Greif4b79e472009-01-16 18:40:27 +00002433 const InvokeInst *II = cast<InvokeInst>(&I);
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002434 const Value *Callee = II->getCalledValue();
2435 FunctionType *FTy = II->getFunctionType();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002436
2437 if (II->hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002438 writeOperandBundles(II, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002439
Chris Lattner0a603252007-05-01 02:13:26 +00002440 Code = bitc::FUNC_CODE_INST_INVOKE;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002441
Devang Patel4c758ea2008-09-25 21:00:45 +00002442 Vals.push_back(VE.getAttributeID(II->getAttributes()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002443 Vals.push_back(II->getCallingConv() | 1 << 13);
Gabor Greif6ecd6f42009-01-07 22:39:29 +00002444 Vals.push_back(VE.getValueID(II->getNormalDest()));
2445 Vals.push_back(VE.getValueID(II->getUnwindDest()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002446 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002447 pushValueAndType(Callee, InstID, Vals);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002448
Chris Lattner0a603252007-05-01 02:13:26 +00002449 // Emit value #'s for the fixed parameters.
Chris Lattner0a603252007-05-01 02:13:26 +00002450 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002451 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
Chris Lattner0a603252007-05-01 02:13:26 +00002452
2453 // Emit type/value pairs for varargs params.
2454 if (FTy->isVarArg()) {
Gabor Greifa2fbc0a2010-03-24 13:21:49 +00002455 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002456 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002457 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
Chris Lattner0a603252007-05-01 02:13:26 +00002458 }
2459 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002460 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00002461 case Instruction::Resume:
2462 Code = bitc::FUNC_CODE_INST_RESUME;
Teresa Johnson37687f32016-04-23 04:30:47 +00002463 pushValueAndType(I.getOperand(0), InstID, Vals);
Bill Wendlingf891bf82011-07-31 06:30:59 +00002464 break;
David Majnemer654e1302015-07-31 17:58:14 +00002465 case Instruction::CleanupRet: {
2466 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2467 const auto &CRI = cast<CleanupReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002468 pushValue(CRI.getCleanupPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002469 if (CRI.hasUnwindDest())
2470 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2471 break;
2472 }
2473 case Instruction::CatchRet: {
2474 Code = bitc::FUNC_CODE_INST_CATCHRET;
2475 const auto &CRI = cast<CatchReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002476 pushValue(CRI.getCatchPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002477 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2478 break;
2479 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00002480 case Instruction::CleanupPad:
David Majnemer654e1302015-07-31 17:58:14 +00002481 case Instruction::CatchPad: {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002482 const auto &FuncletPad = cast<FuncletPadInst>(I);
2483 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2484 : bitc::FUNC_CODE_INST_CLEANUPPAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002485 pushValue(FuncletPad.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002486
2487 unsigned NumArgOperands = FuncletPad.getNumArgOperands();
David Majnemer654e1302015-07-31 17:58:14 +00002488 Vals.push_back(NumArgOperands);
2489 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
Teresa Johnson37687f32016-04-23 04:30:47 +00002490 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002491 break;
2492 }
2493 case Instruction::CatchSwitch: {
2494 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2495 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2496
Teresa Johnson37687f32016-04-23 04:30:47 +00002497 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002498
2499 unsigned NumHandlers = CatchSwitch.getNumHandlers();
2500 Vals.push_back(NumHandlers);
2501 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2502 Vals.push_back(VE.getValueID(CatchPadBB));
2503
2504 if (CatchSwitch.hasUnwindDest())
2505 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
David Majnemer654e1302015-07-31 17:58:14 +00002506 break;
2507 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002508 case Instruction::Unreachable:
2509 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
Chris Lattnercc6d4c92007-05-06 01:28:01 +00002510 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002511 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002512
Jay Foad372ad642011-06-20 14:18:48 +00002513 case Instruction::PHI: {
2514 const PHINode &PN = cast<PHINode>(I);
Chris Lattner0a603252007-05-01 02:13:26 +00002515 Code = bitc::FUNC_CODE_INST_PHI;
Jan Wen Voungafaced02012-10-11 20:20:40 +00002516 // With the newer instruction encoding, forward references could give
2517 // negative valued IDs. This is most common for PHIs, so we use
2518 // signed VBRs.
2519 SmallVector<uint64_t, 128> Vals64;
2520 Vals64.push_back(VE.getTypeID(PN.getType()));
Jay Foad372ad642011-06-20 14:18:48 +00002521 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002522 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002523 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
Jay Foad372ad642011-06-20 14:18:48 +00002524 }
Jan Wen Voungafaced02012-10-11 20:20:40 +00002525 // Emit a Vals64 vector and exit.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002526 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002527 Vals64.clear();
2528 return;
Jay Foad372ad642011-06-20 14:18:48 +00002529 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002530
Bill Wendlingfae14752011-08-12 20:24:12 +00002531 case Instruction::LandingPad: {
2532 const LandingPadInst &LP = cast<LandingPadInst>(I);
2533 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2534 Vals.push_back(VE.getTypeID(LP.getType()));
Bill Wendlingfae14752011-08-12 20:24:12 +00002535 Vals.push_back(LP.isCleanup());
2536 Vals.push_back(LP.getNumClauses());
2537 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2538 if (LP.isCatch(I))
2539 Vals.push_back(LandingPadInst::Catch);
2540 else
2541 Vals.push_back(LandingPadInst::Filter);
Teresa Johnson37687f32016-04-23 04:30:47 +00002542 pushValueAndType(LP.getClause(I), InstID, Vals);
Bill Wendlingfae14752011-08-12 20:24:12 +00002543 }
2544 break;
2545 }
2546
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002547 case Instruction::Alloca: {
Chris Lattner0a603252007-05-01 02:13:26 +00002548 Code = bitc::FUNC_CODE_INST_ALLOCA;
David Blaikiebdb49102015-04-28 16:51:01 +00002549 const AllocaInst &AI = cast<AllocaInst>(I);
2550 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
Dan Gohman9da5bb02010-05-28 01:38:28 +00002551 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002552 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002553 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2554 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2555 "not enough bits for maximum alignment");
2556 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2557 AlignRecord |= AI.isUsedWithInAlloca() << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00002558 AlignRecord |= 1 << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00002559 AlignRecord |= AI.isSwiftError() << 7;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002560 Vals.push_back(AlignRecord);
Chris Lattner0a603252007-05-01 02:13:26 +00002561 break;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002562 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002563
Chris Lattner0a603252007-05-01 02:13:26 +00002564 case Instruction::Load:
Eli Friedman59b66882011-08-09 23:02:53 +00002565 if (cast<LoadInst>(I).isAtomic()) {
2566 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002567 pushValueAndType(I.getOperand(0), InstID, Vals);
Eli Friedman59b66882011-08-09 23:02:53 +00002568 } else {
2569 Code = bitc::FUNC_CODE_INST_LOAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002570 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
Eli Friedman59b66882011-08-09 23:02:53 +00002571 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2572 }
David Blaikie85035652015-02-25 01:07:20 +00002573 Vals.push_back(VE.getTypeID(I.getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002574 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2575 Vals.push_back(cast<LoadInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002576 if (cast<LoadInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002577 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2578 Vals.push_back(getEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
Eli Friedman59b66882011-08-09 23:02:53 +00002579 }
Chris Lattner0a603252007-05-01 02:13:26 +00002580 break;
2581 case Instruction::Store:
Eli Friedman59b66882011-08-09 23:02:53 +00002582 if (cast<StoreInst>(I).isAtomic())
2583 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2584 else
2585 Code = bitc::FUNC_CODE_INST_STORE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002586 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2587 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
Chris Lattner0a603252007-05-01 02:13:26 +00002588 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2589 Vals.push_back(cast<StoreInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002590 if (cast<StoreInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002591 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2592 Vals.push_back(getEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
Eli Friedman59b66882011-08-09 23:02:53 +00002593 }
Chris Lattner0a603252007-05-01 02:13:26 +00002594 break;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002595 case Instruction::AtomicCmpXchg:
2596 Code = bitc::FUNC_CODE_INST_CMPXCHG;
Teresa Johnson37687f32016-04-23 04:30:47 +00002597 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2598 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2599 pushValue(I.getOperand(2), InstID, Vals); // newval.
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002600 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002601 Vals.push_back(
2602 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2603 Vals.push_back(
2604 getEncodedSynchScope(cast<AtomicCmpXchgInst>(I).getSynchScope()));
2605 Vals.push_back(
2606 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
Tim Northover420a2162014-06-13 14:24:07 +00002607 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002608 break;
2609 case Instruction::AtomicRMW:
2610 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
Teresa Johnson37687f32016-04-23 04:30:47 +00002611 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2612 pushValue(I.getOperand(1), InstID, Vals); // val.
2613 Vals.push_back(
2614 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002615 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002616 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2617 Vals.push_back(
2618 getEncodedSynchScope(cast<AtomicRMWInst>(I).getSynchScope()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002619 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002620 case Instruction::Fence:
2621 Code = bitc::FUNC_CODE_INST_FENCE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002622 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2623 Vals.push_back(getEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
Eli Friedmanfee02c62011-07-25 23:16:38 +00002624 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002625 case Instruction::Call: {
Gabor Greife9afee22010-06-26 09:35:09 +00002626 const CallInst &CI = cast<CallInst>(I);
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002627 FunctionType *FTy = CI.getFunctionType();
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002628
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002629 if (CI.hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002630 writeOperandBundles(&CI, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002631
Chris Lattnerc44070802011-06-17 18:17:37 +00002632 Code = bitc::FUNC_CODE_INST_CALL;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002633
Gabor Greife9afee22010-06-26 09:35:09 +00002634 Vals.push_back(VE.getAttributeID(CI.getAttributes()));
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002635
Teresa Johnson37687f32016-04-23 04:30:47 +00002636 unsigned Flags = getOptimizationFlags(&I);
Akira Hatanaka97cb3972015-11-07 02:48:49 +00002637 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2638 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2639 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2640 1 << bitc::CALL_EXPLICIT_TYPE |
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002641 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2642 unsigned(Flags != 0) << bitc::CALL_FMF);
2643 if (Flags != 0)
2644 Vals.push_back(Flags);
2645
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002646 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002647 pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002648
Chris Lattner0a603252007-05-01 02:13:26 +00002649 // Emit value #'s for the fixed parameters.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002650 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2651 // Check for labels (can happen with asm labels).
2652 if (FTy->getParamType(i)->isLabelTy())
2653 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2654 else
Teresa Johnson37687f32016-04-23 04:30:47 +00002655 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002656 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002657
Chris Lattnerb811e952007-05-01 07:03:37 +00002658 // Emit type/value pairs for varargs params.
2659 if (FTy->isVarArg()) {
Gabor Greife9afee22010-06-26 09:35:09 +00002660 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002661 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002662 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
Chris Lattner0a603252007-05-01 02:13:26 +00002663 }
2664 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002665 }
Chris Lattner0a603252007-05-01 02:13:26 +00002666 case Instruction::VAArg:
2667 Code = bitc::FUNC_CODE_INST_VAARG;
2668 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
Teresa Johnson37687f32016-04-23 04:30:47 +00002669 pushValue(I.getOperand(0), InstID, Vals); // valist.
Chris Lattner0a603252007-05-01 02:13:26 +00002670 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2671 break;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002672 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002673
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002674 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002675 Vals.clear();
2676}
2677
Teresa Johnson37687f32016-04-23 04:30:47 +00002678/// Emit names for globals/functions etc. \p IsModuleLevel is true when
2679/// we are writing the module-level VST, where we are including a function
2680/// bitcode index and need to backpatch the VST forward declaration record.
2681void ModuleBitcodeWriter::writeValueSymbolTable(
2682 const ValueSymbolTable &VST, bool IsModuleLevel,
2683 DenseMap<const Function *, uint64_t> *FunctionToBitcodeIndex) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00002684 if (VST.empty()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002685 // writeValueSymbolTableForwardDecl should have returned early as
Teresa Johnsonff642b92015-09-17 20:12:00 +00002686 // well. Ensure this handling remains in sync by asserting that
2687 // the placeholder offset is not set.
Teresa Johnson37687f32016-04-23 04:30:47 +00002688 assert(!IsModuleLevel || !hasVSTOffsetPlaceholder());
Teresa Johnsonff642b92015-09-17 20:12:00 +00002689 return;
2690 }
2691
Teresa Johnson37687f32016-04-23 04:30:47 +00002692 if (IsModuleLevel && hasVSTOffsetPlaceholder()) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00002693 // Get the offset of the VST we are writing, and backpatch it into
2694 // the VST forward declaration record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002695 uint64_t VSTOffset = Stream.GetCurrentBitNo();
Teresa Johnsonff642b92015-09-17 20:12:00 +00002696 // The BitcodeStartBit was the stream offset of the actual bitcode
2697 // (e.g. excluding any initial darwin header).
Teresa Johnson37687f32016-04-23 04:30:47 +00002698 VSTOffset -= bitcodeStartBit();
Teresa Johnsonff642b92015-09-17 20:12:00 +00002699 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002700 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002701 }
2702
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002703 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
Chris Lattner2eae59f2007-05-04 20:34:50 +00002704
Teresa Johnsonff642b92015-09-17 20:12:00 +00002705 // For the module-level VST, add abbrev Ids for the VST_CODE_FNENTRY
2706 // records, which are not used in the per-function VSTs.
2707 unsigned FnEntry8BitAbbrev;
2708 unsigned FnEntry7BitAbbrev;
2709 unsigned FnEntry6BitAbbrev;
Teresa Johnson37687f32016-04-23 04:30:47 +00002710 if (IsModuleLevel && hasVSTOffsetPlaceholder()) {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002711 // 8-bit fixed-width VST_CODE_FNENTRY function strings.
Teresa Johnsonff642b92015-09-17 20:12:00 +00002712 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2713 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002714 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2715 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
Teresa Johnsonff642b92015-09-17 20:12:00 +00002716 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2717 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002718 FnEntry8BitAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002719
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002720 // 7-bit fixed width VST_CODE_FNENTRY function strings.
Teresa Johnsonff642b92015-09-17 20:12:00 +00002721 Abbv = new BitCodeAbbrev();
2722 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002723 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2724 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
Teresa Johnsonff642b92015-09-17 20:12:00 +00002725 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2726 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002727 FnEntry7BitAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002728
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002729 // 6-bit char6 VST_CODE_FNENTRY function strings.
Teresa Johnsonff642b92015-09-17 20:12:00 +00002730 Abbv = new BitCodeAbbrev();
2731 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002732 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2733 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
Teresa Johnsonff642b92015-09-17 20:12:00 +00002734 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2735 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002736 FnEntry6BitAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002737 }
2738
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002739 // FIXME: Set up the abbrev, we know how many values there are!
2740 // FIXME: We know if the type names can use 7-bit ascii.
2741 SmallVector<unsigned, 64> NameVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002742
Yaron Keren001e2e42015-08-10 07:04:29 +00002743 for (const ValueName &Name : VST) {
Chris Lattner4d925982007-05-04 20:52:02 +00002744 // Figure out the encoding to use for the name.
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002745 StringEncoding Bits =
2746 getStringEncoding(Name.getKeyData(), Name.getKeyLength());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002747
Chris Lattnera0987962007-05-04 21:31:13 +00002748 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
Teresa Johnsonff642b92015-09-17 20:12:00 +00002749 NameVals.push_back(VE.getValueID(Name.getValue()));
2750
2751 Function *F = dyn_cast<Function>(Name.getValue());
2752 if (!F) {
2753 // If value is an alias, need to get the aliased base object to
2754 // see if it is a function.
2755 auto *GA = dyn_cast<GlobalAlias>(Name.getValue());
2756 if (GA && GA->getBaseObject())
2757 F = dyn_cast<Function>(GA->getBaseObject());
2758 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002759
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002760 // VST_CODE_ENTRY: [valueid, namechar x N]
2761 // VST_CODE_FNENTRY: [valueid, funcoffset, namechar x N]
2762 // VST_CODE_BBENTRY: [bbid, namechar x N]
Chris Lattner6be58c62007-05-03 22:18:21 +00002763 unsigned Code;
Yaron Keren001e2e42015-08-10 07:04:29 +00002764 if (isa<BasicBlock>(Name.getValue())) {
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002765 Code = bitc::VST_CODE_BBENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002766 if (Bits == SE_Char6)
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002767 AbbrevToUse = VST_BBENTRY_6_ABBREV;
Teresa Johnsonff642b92015-09-17 20:12:00 +00002768 } else if (F && !F->isDeclaration()) {
2769 // Must be the module-level VST, where we pass in the Index and
2770 // have a VSTOffsetPlaceholder. The function-level VST should not
2771 // contain any Function symbols.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00002772 assert(FunctionToBitcodeIndex);
Teresa Johnson37687f32016-04-23 04:30:47 +00002773 assert(hasVSTOffsetPlaceholder());
Teresa Johnsonff642b92015-09-17 20:12:00 +00002774
2775 // Save the word offset of the function (from the start of the
2776 // actual bitcode written to the stream).
Teresa Johnson37687f32016-04-23 04:30:47 +00002777 uint64_t BitcodeIndex = (*FunctionToBitcodeIndex)[F] - bitcodeStartBit();
Teresa Johnsonff642b92015-09-17 20:12:00 +00002778 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2779 NameVals.push_back(BitcodeIndex / 32);
2780
2781 Code = bitc::VST_CODE_FNENTRY;
2782 AbbrevToUse = FnEntry8BitAbbrev;
2783 if (Bits == SE_Char6)
2784 AbbrevToUse = FnEntry6BitAbbrev;
2785 else if (Bits == SE_Fixed7)
2786 AbbrevToUse = FnEntry7BitAbbrev;
Chris Lattner6be58c62007-05-03 22:18:21 +00002787 } else {
2788 Code = bitc::VST_CODE_ENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002789 if (Bits == SE_Char6)
Chris Lattnere760d6f2007-05-05 01:26:50 +00002790 AbbrevToUse = VST_ENTRY_6_ABBREV;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002791 else if (Bits == SE_Fixed7)
Chris Lattnere760d6f2007-05-05 01:26:50 +00002792 AbbrevToUse = VST_ENTRY_7_ABBREV;
Chris Lattner6be58c62007-05-03 22:18:21 +00002793 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002794
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002795 for (const auto P : Name.getKey())
2796 NameVals.push_back((unsigned char)P);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002797
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002798 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002799 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002800 NameVals.clear();
2801 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002802 Stream.ExitBlock();
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002803}
2804
Teresa Johnson403a7872015-10-04 14:33:43 +00002805/// Emit function names and summary offsets for the combined index
2806/// used by ThinLTO.
Teresa Johnson37687f32016-04-23 04:30:47 +00002807void IndexBitcodeWriter::writeCombinedValueSymbolTable() {
2808 assert(hasVSTOffsetPlaceholder() && "Expected non-zero VSTOffsetPlaceholder");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002809 // Get the offset of the VST we are writing, and backpatch it into
2810 // the VST forward declaration record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002811 uint64_t VSTOffset = Stream.GetCurrentBitNo();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002812 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002813 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002814
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002815 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
Teresa Johnson403a7872015-10-04 14:33:43 +00002816
Teresa Johnson403a7872015-10-04 14:33:43 +00002817 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002818 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_COMBINED_ENTRY));
2819 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
2820 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // refguid
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002821 unsigned EntryAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnson403a7872015-10-04 14:33:43 +00002822
Teresa Johnsone1164de2016-02-10 21:55:02 +00002823 SmallVector<uint64_t, 64> NameVals;
Teresa Johnson37687f32016-04-23 04:30:47 +00002824 for (const auto &GVI : valueIds()) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002825 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
2826 NameVals.push_back(GVI.second);
2827 NameVals.push_back(GVI.first);
2828
2829 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002830 Stream.EmitRecord(bitc::VST_CODE_COMBINED_ENTRY, NameVals, EntryAbbrev);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002831 NameVals.clear();
Teresa Johnson403a7872015-10-04 14:33:43 +00002832 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002833 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00002834}
2835
Teresa Johnson37687f32016-04-23 04:30:47 +00002836void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002837 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2838 unsigned Code;
2839 if (isa<BasicBlock>(Order.V))
2840 Code = bitc::USELIST_CODE_BB;
2841 else
2842 Code = bitc::USELIST_CODE_DEFAULT;
2843
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002844 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002845 Record.push_back(VE.getValueID(Order.V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002846 Stream.EmitRecord(Code, Record);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002847}
2848
Teresa Johnson37687f32016-04-23 04:30:47 +00002849void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00002850 assert(VE.shouldPreserveUseListOrder() &&
2851 "Expected to be preserving use-list order");
2852
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002853 auto hasMore = [&]() {
2854 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2855 };
2856 if (!hasMore())
2857 // Nothing to do.
2858 return;
2859
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002860 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002861 while (hasMore()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002862 writeUseList(std::move(VE.UseListOrders.back()));
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002863 VE.UseListOrders.pop_back();
2864 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002865 Stream.ExitBlock();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002866}
2867
Teresa Johnson403a7872015-10-04 14:33:43 +00002868/// Emit a function body to the module stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00002869void ModuleBitcodeWriter::writeFunction(
2870 const Function &F,
2871 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00002872 // Save the bitcode index of the start of this function block for recording
2873 // in the VST.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002874 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002875
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002876 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
Chad Rosier6a11b642011-06-03 17:02:19 +00002877 VE.incorporateFunction(F);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002878
2879 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002880
Chris Lattnere6e364c2007-04-26 05:53:54 +00002881 // Emit the number of basic blocks, so the reader can create them ahead of
2882 // time.
2883 Vals.push_back(VE.getBasicBlocks().size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002884 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002885 Vals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002886
Chris Lattnere6e364c2007-04-26 05:53:54 +00002887 // If there are function-local constants, emit them now.
2888 unsigned CstStart, CstEnd;
2889 VE.getFunctionConstantRange(CstStart, CstEnd);
Teresa Johnson37687f32016-04-23 04:30:47 +00002890 writeConstants(CstStart, CstEnd, false);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002891
Victor Hernandez6c730de2010-01-14 01:50:08 +00002892 // If there is function-local metadata, emit it now.
Teresa Johnson37687f32016-04-23 04:30:47 +00002893 writeFunctionMetadata(F);
Victor Hernandez6c730de2010-01-14 01:50:08 +00002894
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002895 // Keep a running idea of what the instruction ID is.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002896 unsigned InstID = CstEnd;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002897
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002898 bool NeedsMetadataAttachment = F.hasMetadata();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002899
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002900 DILocation *LastDL = nullptr;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002901 // Finally, emit all the instructions, in order.
Nick Lewycky4d43d3c2008-04-25 16:53:59 +00002902 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002903 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2904 I != E; ++I) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002905 writeInstruction(*I, InstID, Vals);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002906
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002907 if (!I->getType()->isVoidTy())
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002908 ++InstID;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002909
Chris Lattner07d09ed2010-04-03 02:17:50 +00002910 // If the instruction has metadata, write a metadata attachment later.
2911 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002912
Chris Lattner07d09ed2010-04-03 02:17:50 +00002913 // If the instruction has a debug location, emit it.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002914 DILocation *DL = I->getDebugLoc();
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00002915 if (!DL)
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002916 continue;
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002917
2918 if (DL == LastDL) {
Chris Lattner07d09ed2010-04-03 02:17:50 +00002919 // Just repeat the same debug loc as last time.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002920 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002921 continue;
Chris Lattner07d09ed2010-04-03 02:17:50 +00002922 }
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002923
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00002924 Vals.push_back(DL->getLine());
2925 Vals.push_back(DL->getColumn());
2926 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2927 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002928 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002929 Vals.clear();
Duncan P. N. Exon Smith538ef562015-05-06 22:51:12 +00002930
2931 LastDL = DL;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002932 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002933
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002934 // Emit names for all the instructions etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00002935 writeValueSymbolTable(F.getValueSymbolTable());
Devang Patelaf206b82009-09-18 19:26:43 +00002936
Chris Lattner07d09ed2010-04-03 02:17:50 +00002937 if (NeedsMetadataAttachment)
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002938 writeFunctionMetadataAttachment(F);
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00002939 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00002940 writeUseListBlock(&F);
Chad Rosier6a11b642011-06-03 17:02:19 +00002941 VE.purgeFunction();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002942 Stream.ExitBlock();
Chris Lattner831d4202007-04-26 03:27:58 +00002943}
2944
Chris Lattner702658c2007-05-04 18:26:27 +00002945// Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00002946void ModuleBitcodeWriter::writeBlockInfo() {
Chris Lattner702658c2007-05-04 18:26:27 +00002947 // We only want to emit block info records for blocks that have multiple
Jan Wen Voungafaced02012-10-11 20:20:40 +00002948 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
Jan Wen Voung8c9e9412012-10-11 21:45:16 +00002949 // Other blocks can define their abbrevs inline.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002950 Stream.EnterBlockInfoBlock(2);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002951
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002952 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
Chris Lattner982ec1e2007-05-05 00:17:00 +00002953 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2954 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2955 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2956 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2957 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002958 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002959 VST_ENTRY_8_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002960 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00002961 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002962
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002963 { // 7-bit fixed width VST_CODE_ENTRY strings.
Chris Lattner982ec1e2007-05-05 00:17:00 +00002964 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2965 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2966 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2967 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2968 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002969 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002970 VST_ENTRY_7_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002971 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00002972 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002973 { // 6-bit char6 VST_CODE_ENTRY strings.
Chris Lattnere760d6f2007-05-05 01:26:50 +00002974 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2975 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2976 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2977 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2978 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002979 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002980 VST_ENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002981 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnere760d6f2007-05-05 01:26:50 +00002982 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002983 { // 6-bit char6 VST_CODE_BBENTRY strings.
Chris Lattner982ec1e2007-05-05 00:17:00 +00002984 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2985 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2986 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2987 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chris Lattnere760d6f2007-05-05 01:26:50 +00002988 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002989 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002990 VST_BBENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002991 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00002992 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002993
2994
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002995
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002996 { // SETTYPE abbrev for CONSTANTS_BLOCK.
2997 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
2998 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2999 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
David Blaikie7b028102015-02-25 00:51:52 +00003000 VE.computeBitsRequiredForTypeIndicies()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003001 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003002 CONSTANTS_SETTYPE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003003 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003004 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003005
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003006 { // INTEGER abbrev for CONSTANTS_BLOCK.
3007 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3008 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3009 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003010 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003011 CONSTANTS_INTEGER_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003012 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003013 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003014
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003015 { // CE_CAST abbrev for CONSTANTS_BLOCK.
3016 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3017 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3018 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3019 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
David Blaikie7b028102015-02-25 00:51:52 +00003020 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003021 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3022
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003023 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003024 CONSTANTS_CE_CAST_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003025 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003026 }
3027 { // NULL abbrev for CONSTANTS_BLOCK.
3028 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3029 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003030 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003031 CONSTANTS_NULL_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003032 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003033 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003034
Chris Lattnerb80751d2007-05-05 07:44:49 +00003035 // FIXME: This should only use space for first class types!
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003036
Chris Lattnerb80751d2007-05-05 07:44:49 +00003037 { // INST_LOAD abbrev for FUNCTION_BLOCK.
3038 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3039 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
Chris Lattnerb80751d2007-05-05 07:44:49 +00003040 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
David Blaikie85035652015-02-25 01:07:20 +00003041 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3042 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerb80751d2007-05-05 07:44:49 +00003043 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3044 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003045 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003046 FUNCTION_INST_LOAD_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003047 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerb80751d2007-05-05 07:44:49 +00003048 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003049 { // INST_BINOP abbrev for FUNCTION_BLOCK.
3050 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3051 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3052 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3053 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3054 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003055 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003056 FUNCTION_INST_BINOP_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003057 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003058 }
Dan Gohman0ebd6962009-07-20 21:19:07 +00003059 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3060 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3061 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3062 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3063 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3064 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3065 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003066 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003067 FUNCTION_INST_BINOP_FLAGS_ABBREV)
Dan Gohman0ebd6962009-07-20 21:19:07 +00003068 llvm_unreachable("Unexpected abbrev ordering!");
3069 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003070 { // INST_CAST abbrev for FUNCTION_BLOCK.
3071 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3072 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3073 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3074 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
David Blaikie7b028102015-02-25 00:51:52 +00003075 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003076 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003077 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003078 FUNCTION_INST_CAST_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003079 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003080 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003081
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003082 { // INST_RET abbrev for FUNCTION_BLOCK.
3083 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3084 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003085 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003086 FUNCTION_INST_RET_VOID_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003087 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003088 }
3089 { // INST_RET abbrev for FUNCTION_BLOCK.
3090 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3091 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3092 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003093 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003094 FUNCTION_INST_RET_VAL_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003095 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003096 }
3097 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3098 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3099 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003100 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003101 FUNCTION_INST_UNREACHABLE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003102 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003103 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00003104 {
3105 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3106 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3107 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3108 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3109 Log2_32_Ceil(VE.getTypes().size() + 1)));
3110 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3111 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003112 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
David Blaikieb5b5efd2015-02-25 01:08:52 +00003113 FUNCTION_INST_GEP_ABBREV)
3114 llvm_unreachable("Unexpected abbrev ordering!");
3115 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003116
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003117 Stream.ExitBlock();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003118}
3119
Teresa Johnson403a7872015-10-04 14:33:43 +00003120/// Write the module path strings, currently only used when generating
3121/// a combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003122void IndexBitcodeWriter::writeModStrings() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003123 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
Teresa Johnson403a7872015-10-04 14:33:43 +00003124
3125 // TODO: See which abbrev sizes we actually need to emit
3126
3127 // 8-bit fixed-width MST_ENTRY strings.
3128 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3129 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3130 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3131 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3132 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003133 unsigned Abbrev8Bit = Stream.EmitAbbrev(Abbv);
Teresa Johnson403a7872015-10-04 14:33:43 +00003134
3135 // 7-bit fixed width MST_ENTRY strings.
3136 Abbv = new BitCodeAbbrev();
3137 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3138 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3139 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3140 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003141 unsigned Abbrev7Bit = Stream.EmitAbbrev(Abbv);
Teresa Johnson403a7872015-10-04 14:33:43 +00003142
3143 // 6-bit char6 MST_ENTRY strings.
3144 Abbv = new BitCodeAbbrev();
3145 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3146 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3147 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3148 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003149 unsigned Abbrev6Bit = Stream.EmitAbbrev(Abbv);
Teresa Johnson403a7872015-10-04 14:33:43 +00003150
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003151 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3152 Abbv = new BitCodeAbbrev();
3153 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3154 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3155 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3156 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3157 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3158 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003159 unsigned AbbrevHash = Stream.EmitAbbrev(Abbv);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003160
3161 SmallVector<unsigned, 64> Vals;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003162 for (const auto &MPSE : Index.modulePaths()) {
Teresa Johnson84174c32016-05-10 13:48:23 +00003163 if (!doIncludeModule(MPSE.getKey()))
3164 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00003165 StringEncoding Bits =
3166 getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size());
3167 unsigned AbbrevToUse = Abbrev8Bit;
3168 if (Bits == SE_Char6)
3169 AbbrevToUse = Abbrev6Bit;
3170 else if (Bits == SE_Fixed7)
3171 AbbrevToUse = Abbrev7Bit;
3172
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003173 Vals.push_back(MPSE.getValue().first);
Teresa Johnson403a7872015-10-04 14:33:43 +00003174
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003175 for (const auto P : MPSE.getKey())
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003176 Vals.push_back((unsigned char)P);
Teresa Johnson403a7872015-10-04 14:33:43 +00003177
3178 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003179 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003180
3181 Vals.clear();
3182 // Emit an optional hash for the module now
3183 auto &Hash = MPSE.getValue().second;
3184 bool AllZero = true; // Detect if the hash is empty, and do not generate it
3185 for (auto Val : Hash) {
3186 if (Val)
3187 AllZero = false;
3188 Vals.push_back(Val);
3189 }
3190 if (!AllZero) {
3191 // Emit the hash record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003192 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003193 }
3194
3195 Vals.clear();
Teresa Johnson403a7872015-10-04 14:33:43 +00003196 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003197 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003198}
3199
3200// Helper to emit a single function summary record.
Teresa Johnson37687f32016-04-23 04:30:47 +00003201void ModuleBitcodeWriter::writePerModuleFunctionSummaryRecord(
Teresa Johnson28e457b2016-04-24 14:57:11 +00003202 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
Teresa Johnson37687f32016-04-23 04:30:47 +00003203 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3204 const Function &F) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003205 NameVals.push_back(ValueID);
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003206
Teresa Johnson28e457b2016-04-24 14:57:11 +00003207 FunctionSummary *FS = cast<FunctionSummary>(Summary);
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003208 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
Teresa Johnson403a7872015-10-04 14:33:43 +00003209 NameVals.push_back(FS->instCount());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003210 NameVals.push_back(FS->refs().size());
3211
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003212 unsigned SizeBeforeRefs = NameVals.size();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003213 for (auto &RI : FS->refs())
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003214 NameVals.push_back(VE.getValueID(RI.getValue()));
3215 // Sort the refs for determinism output, the vector returned by FS->refs() has
3216 // been initialized from a DenseSet.
3217 std::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003218
Mehdi Amini367577a2016-05-16 09:04:55 +00003219 std::vector<FunctionSummary::EdgeTy> Calls = FS->calls();
3220 std::sort(Calls.begin(), Calls.end(),
3221 [this](const FunctionSummary::EdgeTy &L,
3222 const FunctionSummary::EdgeTy &R) {
3223 return VE.getValueID(L.first.getValue()) <
3224 VE.getValueID(R.first.getValue());
3225 });
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003226 bool HasProfileData = F.getEntryCount().hasValue();
Mehdi Amini367577a2016-05-16 09:04:55 +00003227 for (auto &ECI : Calls) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003228 NameVals.push_back(VE.getValueID(ECI.first.getValue()));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003229 assert(ECI.second.CallsiteCount > 0 && "Expected at least one callsite");
3230 NameVals.push_back(ECI.second.CallsiteCount);
3231 if (HasProfileData)
3232 NameVals.push_back(ECI.second.ProfileCount);
3233 }
3234
3235 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3236 unsigned Code =
3237 (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
Teresa Johnson403a7872015-10-04 14:33:43 +00003238
3239 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003240 Stream.EmitRecord(Code, NameVals, FSAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003241 NameVals.clear();
3242}
3243
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003244// Collect the global value references in the given variable's initializer,
3245// and emit them in a summary record.
Teresa Johnson37687f32016-04-23 04:30:47 +00003246void ModuleBitcodeWriter::writeModuleLevelReferences(
3247 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3248 unsigned FSModRefsAbbrev) {
Teresa Johnson13968092016-03-15 19:35:45 +00003249 // Only interested in recording variable defs in the summary.
3250 if (V.isDeclaration())
3251 return;
Teresa Johnson13968092016-03-15 19:35:45 +00003252 NameVals.push_back(VE.getValueID(&V));
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003253 NameVals.push_back(getEncodedGVSummaryFlags(V));
Teresa Johnson28e457b2016-04-24 14:57:11 +00003254 auto *Summary = Index->getGlobalValueSummary(V);
3255 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003256
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003257 unsigned SizeBeforeRefs = NameVals.size();
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003258 for (auto &RI : VS->refs())
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003259 NameVals.push_back(VE.getValueID(RI.getValue()));
3260 // Sort the refs for determinism output, the vector returned by FS->refs() has
3261 // been initialized from a DenseSet.
3262 std::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003263
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003264 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3265 FSModRefsAbbrev);
Teresa Johnson13968092016-03-15 19:35:45 +00003266 NameVals.clear();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003267}
Teresa Johnson403a7872015-10-04 14:33:43 +00003268
Mehdi Amini8fe69362016-04-24 03:18:11 +00003269// Current version for the summary.
3270// This is bumped whenever we introduce changes in the way some record are
3271// interpreted, like flags for instance.
3272static const uint64_t INDEX_VERSION = 1;
3273
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003274/// Emit the per-module summary section alongside the rest of
3275/// the module's bitcode.
Teresa Johnson37687f32016-04-23 04:30:47 +00003276void ModuleBitcodeWriter::writePerModuleGlobalValueSummary() {
Teresa Johnson37687f32016-04-23 04:30:47 +00003277 if (Index->begin() == Index->end())
Teresa Johnsonb35cc692016-04-20 14:39:45 +00003278 return;
3279
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003280 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 4);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003281
Mehdi Amini8fe69362016-04-24 03:18:11 +00003282 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3283
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003284 // Abbrev for FS_PERMODULE.
Teresa Johnson403a7872015-10-04 14:33:43 +00003285 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003286 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003287 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003288 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003289 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003290 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3291 // numrefs x valueid, n x (valueid, callsitecount)
3292 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3293 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003294 unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnson403a7872015-10-04 14:33:43 +00003295
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003296 // Abbrev for FS_PERMODULE_PROFILE.
3297 Abbv = new BitCodeAbbrev();
3298 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3299 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003300 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003301 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3302 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3303 // numrefs x valueid, n x (valueid, callsitecount, profilecount)
3304 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3305 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003306 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003307
3308 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
3309 Abbv = new BitCodeAbbrev();
3310 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3311 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003312 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003313 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3314 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003315 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003316
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003317 // Abbrev for FS_ALIAS.
3318 Abbv = new BitCodeAbbrev();
3319 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3320 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003321 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003322 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003323 unsigned FSAliasAbbrev = Stream.EmitAbbrev(Abbv);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003324
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003325 SmallVector<uint64_t, 64> NameVals;
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003326 // Iterate over the list of functions instead of the Index to
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003327 // ensure the ordering is stable.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003328 for (const Function &F : M) {
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003329 if (F.isDeclaration())
3330 continue;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003331 // Summary emission does not support anonymous functions, they have to
3332 // renamed using the anonymous function renaming pass.
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003333 if (!F.hasName())
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003334 report_fatal_error("Unexpected anonymous function when writing summary");
Teresa Johnson403a7872015-10-04 14:33:43 +00003335
Teresa Johnson28e457b2016-04-24 14:57:11 +00003336 auto *Summary = Index->getGlobalValueSummary(F);
Peter Collingbourne832e7fa2016-05-06 02:41:23 +00003337 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3338 FSCallsAbbrev, FSCallsProfileAbbrev, F);
Teresa Johnson403a7872015-10-04 14:33:43 +00003339 }
3340
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003341 // Capture references from GlobalVariable initializers, which are outside
3342 // of a function scope.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003343 for (const GlobalVariable &G : M.globals())
Teresa Johnson37687f32016-04-23 04:30:47 +00003344 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003345
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003346 for (const GlobalAlias &A : M.aliases()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003347 auto *Aliasee = A.getBaseObject();
3348 if (!Aliasee->hasName())
3349 // Nameless function don't have an entry in the summary, skip it.
3350 continue;
3351 auto AliasId = VE.getValueID(&A);
3352 auto AliaseeId = VE.getValueID(Aliasee);
3353 NameVals.push_back(AliasId);
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003354 NameVals.push_back(getEncodedGVSummaryFlags(A));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003355 NameVals.push_back(AliaseeId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003356 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003357 NameVals.clear();
3358 }
3359
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003360 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003361}
3362
Teresa Johnson26ab5772016-03-15 00:04:37 +00003363/// Emit the combined summary section into the combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003364void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003365 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
Mehdi Amini8fe69362016-04-24 03:18:11 +00003366 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
Teresa Johnson403a7872015-10-04 14:33:43 +00003367
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003368 // Abbrev for FS_COMBINED.
Teresa Johnson403a7872015-10-04 14:33:43 +00003369 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003370 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
Teresa Johnson02e98332016-04-27 13:28:35 +00003371 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003372 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003373 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003374 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3375 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3376 // numrefs x valueid, n x (valueid, callsitecount)
3377 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3378 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003379 unsigned FSCallsAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnson403a7872015-10-04 14:33:43 +00003380
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003381 // Abbrev for FS_COMBINED_PROFILE.
3382 Abbv = new BitCodeAbbrev();
3383 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
Teresa Johnson02e98332016-04-27 13:28:35 +00003384 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003385 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003386 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003387 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3388 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3389 // numrefs x valueid, n x (valueid, callsitecount, profilecount)
3390 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3391 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003392 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003393
3394 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
3395 Abbv = new BitCodeAbbrev();
3396 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003397 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003398 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003399 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003400 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3401 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003402 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003403
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003404 // Abbrev for FS_COMBINED_ALIAS.
3405 Abbv = new BitCodeAbbrev();
3406 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003407 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003408 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003409 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson02e98332016-04-27 13:28:35 +00003410 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003411 unsigned FSAliasAbbrev = Stream.EmitAbbrev(Abbv);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003412
Teresa Johnson02e98332016-04-27 13:28:35 +00003413 // The aliases are emitted as a post-pass, and will point to the value
3414 // id of the aliasee. Save them in a vector for post-processing.
Teresa Johnson28e457b2016-04-24 14:57:11 +00003415 SmallVector<AliasSummary *, 64> Aliases;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003416
Teresa Johnson02e98332016-04-27 13:28:35 +00003417 // Save the value id for each summary for alias emission.
3418 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3419
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003420 SmallVector<uint64_t, 64> NameVals;
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003421
3422 // For local linkage, we also emit the original name separately
3423 // immediately after the record.
3424 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3425 if (!GlobalValue::isLocalLinkage(S.linkage()))
3426 return;
3427 NameVals.push_back(S.getOriginalName());
3428 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3429 NameVals.clear();
3430 };
3431
Teresa Johnson84174c32016-05-10 13:48:23 +00003432 for (const auto &I : *this) {
3433 GlobalValueSummary *S = I.second;
3434 assert(S);
Teresa Johnson02e98332016-04-27 13:28:35 +00003435
Teresa Johnson84174c32016-05-10 13:48:23 +00003436 assert(hasValueId(I.first));
3437 unsigned ValueId = getValueId(I.first);
3438 SummaryToValueIdMap[S] = ValueId;
Teresa Johnson02e98332016-04-27 13:28:35 +00003439
Teresa Johnson84174c32016-05-10 13:48:23 +00003440 if (auto *AS = dyn_cast<AliasSummary>(S)) {
3441 // Will process aliases as a post-pass because the reader wants all
3442 // global to be loaded first.
3443 Aliases.push_back(AS);
3444 continue;
3445 }
Teresa Johnson403a7872015-10-04 14:33:43 +00003446
Teresa Johnson84174c32016-05-10 13:48:23 +00003447 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
Teresa Johnson02e98332016-04-27 13:28:35 +00003448 NameVals.push_back(ValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003449 NameVals.push_back(Index.getModuleId(VS->modulePath()));
3450 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3451 for (auto &RI : VS->refs()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00003452 NameVals.push_back(getValueId(RI.getGUID()));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003453 }
3454
Teresa Johnson403a7872015-10-04 14:33:43 +00003455 // Emit the finished record.
Teresa Johnson84174c32016-05-10 13:48:23 +00003456 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3457 FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003458 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003459 MaybeEmitOriginalName(*S);
Teresa Johnson84174c32016-05-10 13:48:23 +00003460 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00003461 }
Teresa Johnson84174c32016-05-10 13:48:23 +00003462
3463 auto *FS = cast<FunctionSummary>(S);
3464 NameVals.push_back(ValueId);
3465 NameVals.push_back(Index.getModuleId(FS->modulePath()));
3466 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3467 NameVals.push_back(FS->instCount());
3468 NameVals.push_back(FS->refs().size());
3469
3470 for (auto &RI : FS->refs()) {
3471 NameVals.push_back(getValueId(RI.getGUID()));
3472 }
3473
3474 bool HasProfileData = false;
3475 for (auto &EI : FS->calls()) {
3476 HasProfileData |= EI.second.ProfileCount != 0;
3477 if (HasProfileData)
3478 break;
3479 }
3480
3481 for (auto &EI : FS->calls()) {
3482 // If this GUID doesn't have a value id, it doesn't have a function
3483 // summary and we don't need to record any calls to it.
3484 if (!hasValueId(EI.first.getGUID()))
3485 continue;
3486 NameVals.push_back(getValueId(EI.first.getGUID()));
3487 assert(EI.second.CallsiteCount > 0 && "Expected at least one callsite");
3488 NameVals.push_back(EI.second.CallsiteCount);
3489 if (HasProfileData)
3490 NameVals.push_back(EI.second.ProfileCount);
3491 }
3492
3493 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3494 unsigned Code =
3495 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3496
3497 // Emit the finished record.
3498 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3499 NameVals.clear();
3500 MaybeEmitOriginalName(*S);
Teresa Johnson403a7872015-10-04 14:33:43 +00003501 }
3502
Teresa Johnson28e457b2016-04-24 14:57:11 +00003503 for (auto *AS : Aliases) {
Teresa Johnson02e98332016-04-27 13:28:35 +00003504 auto AliasValueId = SummaryToValueIdMap[AS];
3505 assert(AliasValueId);
3506 NameVals.push_back(AliasValueId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003507 NameVals.push_back(Index.getModuleId(AS->modulePath()));
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003508 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
Teresa Johnson02e98332016-04-27 13:28:35 +00003509 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3510 assert(AliaseeValueId);
3511 NameVals.push_back(AliaseeValueId);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003512
3513 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003514 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003515 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003516 MaybeEmitOriginalName(*AS);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003517 }
3518
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003519 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003520}
3521
Teresa Johnson37687f32016-04-23 04:30:47 +00003522void ModuleBitcodeWriter::writeIdentificationBlock() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003523 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
Mehdi Amini5d303282015-10-26 18:37:00 +00003524
3525 // Write the "user readable" string identifying the bitcode producer
3526 BitCodeAbbrev *Abbv = new BitCodeAbbrev();
3527 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3528 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3529 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003530 auto StringAbbrev = Stream.EmitAbbrev(Abbv);
Teresa Johnson37687f32016-04-23 04:30:47 +00003531 writeStringRecord(bitc::IDENTIFICATION_CODE_STRING,
3532 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
Mehdi Amini5d303282015-10-26 18:37:00 +00003533
3534 // Write the epoch version
3535 Abbv = new BitCodeAbbrev();
3536 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3537 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003538 auto EpochAbbrev = Stream.EmitAbbrev(Abbv);
Mehdi Amini5d303282015-10-26 18:37:00 +00003539 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003540 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3541 Stream.ExitBlock();
Mehdi Amini5d303282015-10-26 18:37:00 +00003542}
3543
Teresa Johnson37687f32016-04-23 04:30:47 +00003544void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003545 // Emit the module's hash.
3546 // MODULE_CODE_HASH: [5*i32]
3547 SHA1 Hasher;
Sjoerd Meijer41beee62016-04-27 18:35:02 +00003548 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003549 Buffer.size() - BlockStartPos));
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003550 auto Hash = Hasher.result();
3551 SmallVector<uint64_t, 20> Vals;
3552 auto LShift = [&](unsigned char Val, unsigned Amount)
3553 -> uint64_t { return ((uint64_t)Val) << Amount; };
3554 for (int Pos = 0; Pos < 20; Pos += 4) {
3555 uint32_t SubHash = LShift(Hash[Pos + 0], 24);
3556 SubHash |= LShift(Hash[Pos + 1], 16) | LShift(Hash[Pos + 2], 8) |
3557 (unsigned)(unsigned char)Hash[Pos + 3];
3558 Vals.push_back(SubHash);
3559 }
3560
3561 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003562 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003563}
3564
Teresa Johnson37687f32016-04-23 04:30:47 +00003565void BitcodeWriter::write() {
3566 // Emit the file header first.
3567 writeBitcodeHeader();
3568
3569 writeBlocks();
3570}
3571
3572void ModuleBitcodeWriter::writeBlocks() {
3573 writeIdentificationBlock();
3574 writeModule();
3575}
3576
3577void IndexBitcodeWriter::writeBlocks() {
3578 // Index contains only a single outer (module) block.
3579 writeIndex();
3580}
3581
3582void ModuleBitcodeWriter::writeModule() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003583 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3584 size_t BlockStartPos = Buffer.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003585
Jan Wen Voungafaced02012-10-11 20:20:40 +00003586 SmallVector<unsigned, 1> Vals;
3587 unsigned CurVersion = 1;
3588 Vals.push_back(CurVersion);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003589 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003590
3591 // Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00003592 writeBlockInfo();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003593
Bill Wendlingdc095552013-02-10 23:09:32 +00003594 // Emit information about attribute groups.
Teresa Johnson37687f32016-04-23 04:30:47 +00003595 writeAttributeGroupTable();
Bill Wendlingdc095552013-02-10 23:09:32 +00003596
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003597 // Emit information about parameter attributes.
Teresa Johnson37687f32016-04-23 04:30:47 +00003598 writeAttributeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003599
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003600 // Emit information describing all of the types in the module.
Teresa Johnson37687f32016-04-23 04:30:47 +00003601 writeTypeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003602
Teresa Johnson37687f32016-04-23 04:30:47 +00003603 writeComdats();
David Majnemerdad0a642014-06-27 18:19:56 +00003604
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003605 // Emit top-level description of module, including target triple, inline asm,
3606 // descriptors for global variables, and function prototype info.
Teresa Johnson37687f32016-04-23 04:30:47 +00003607 writeModuleInfo();
Devang Patel7428d8a2009-07-22 17:43:22 +00003608
Devang Patele059ba6e2009-07-23 01:07:34 +00003609 // Emit constants.
Teresa Johnson37687f32016-04-23 04:30:47 +00003610 writeModuleConstants();
Devang Patele059ba6e2009-07-23 01:07:34 +00003611
Peter Collingbourne21521892016-06-21 23:42:48 +00003612 // Emit metadata kind names.
3613 writeModuleMetadataKinds();
Devang Patel8cca7b42009-08-04 05:01:35 +00003614
Devang Patelaf206b82009-09-18 19:26:43 +00003615 // Emit metadata.
Peter Collingbourne21521892016-06-21 23:42:48 +00003616 writeModuleMetadata();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003617
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003618 // Emit module-level use-lists.
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00003619 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00003620 writeUseListBlock(nullptr);
Chad Rosierca2567b2011-12-07 21:44:12 +00003621
Teresa Johnson37687f32016-04-23 04:30:47 +00003622 writeOperandBundleTags();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003623
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003624 // Emit function bodies.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003625 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003626 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003627 if (!F->isDeclaration())
Teresa Johnson37687f32016-04-23 04:30:47 +00003628 writeFunction(*F, FunctionToBitcodeIndex);
Teresa Johnson403a7872015-10-04 14:33:43 +00003629
3630 // Need to write after the above call to WriteFunction which populates
3631 // the summary information in the index.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003632 if (Index)
Teresa Johnson37687f32016-04-23 04:30:47 +00003633 writePerModuleGlobalValueSummary();
Teresa Johnsonff642b92015-09-17 20:12:00 +00003634
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003635 writeValueSymbolTable(M.getValueSymbolTable(),
Teresa Johnson37687f32016-04-23 04:30:47 +00003636 /* IsModuleLevel */ true, &FunctionToBitcodeIndex);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003637
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003638 if (GenerateHash) {
Teresa Johnson37687f32016-04-23 04:30:47 +00003639 writeModuleHash(BlockStartPos);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003640 }
3641
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003642 Stream.ExitBlock();
Chris Lattner702658c2007-05-04 18:26:27 +00003643}
3644
Teresa Johnson37687f32016-04-23 04:30:47 +00003645static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3646 uint32_t &Position) {
3647 support::endian::write32le(&Buffer[Position], Value);
3648 Position += 4;
3649}
3650
3651/// If generating a bc file on darwin, we have to emit a
Chris Lattnera660f4b2008-07-09 05:14:23 +00003652/// header and trailer to make it compatible with the system archiver. To do
3653/// this we emit the following header, and then emit a trailer that pads the
3654/// file out to be a multiple of 16 bytes.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003655///
Chris Lattnera660f4b2008-07-09 05:14:23 +00003656/// struct bc_header {
3657/// uint32_t Magic; // 0x0B17C0DE
3658/// uint32_t Version; // Version, currently always 0.
3659/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3660/// uint32_t BitcodeSize; // Size of traditional bitcode file.
3661/// uint32_t CPUType; // CPU specifier.
3662/// ... potentially more later ...
3663/// };
Teresa Johnson37687f32016-04-23 04:30:47 +00003664static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003665 const Triple &TT) {
Chris Lattnera660f4b2008-07-09 05:14:23 +00003666 unsigned CPUType = ~0U;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003667
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003668 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
Evan Cheng545d3602010-02-12 20:39:35 +00003669 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3670 // number from /usr/include/mach/machine.h. It is ok to reproduce the
3671 // specific constants here because they are implicitly part of the Darwin ABI.
Chris Lattnera660f4b2008-07-09 05:14:23 +00003672 enum {
3673 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
3674 DARWIN_CPU_TYPE_X86 = 7,
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003675 DARWIN_CPU_TYPE_ARM = 12,
Chris Lattnera660f4b2008-07-09 05:14:23 +00003676 DARWIN_CPU_TYPE_POWERPC = 18
3677 };
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003678
Evan Chengcffdcae2011-06-14 01:51:33 +00003679 Triple::ArchType Arch = TT.getArch();
3680 if (Arch == Triple::x86_64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003681 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00003682 else if (Arch == Triple::x86)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003683 CPUType = DARWIN_CPU_TYPE_X86;
Evan Chengcffdcae2011-06-14 01:51:33 +00003684 else if (Arch == Triple::ppc)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003685 CPUType = DARWIN_CPU_TYPE_POWERPC;
Evan Chengcffdcae2011-06-14 01:51:33 +00003686 else if (Arch == Triple::ppc64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003687 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00003688 else if (Arch == Triple::arm || Arch == Triple::thumb)
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003689 CPUType = DARWIN_CPU_TYPE_ARM;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003690
Chris Lattnera660f4b2008-07-09 05:14:23 +00003691 // Traditional Bitcode starts after header.
Akira Hatanaka4f472a882016-01-29 05:55:09 +00003692 assert(Buffer.size() >= BWH_HeaderSize &&
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003693 "Expected header size to be reserved");
Akira Hatanaka4f472a882016-01-29 05:55:09 +00003694 unsigned BCOffset = BWH_HeaderSize;
3695 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003696
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003697 // Write the magic and version.
3698 unsigned Position = 0;
Teresa Johnson37687f32016-04-23 04:30:47 +00003699 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
3700 writeInt32ToBuffer(0, Buffer, Position); // Version.
3701 writeInt32ToBuffer(BCOffset, Buffer, Position);
3702 writeInt32ToBuffer(BCSize, Buffer, Position);
3703 writeInt32ToBuffer(CPUType, Buffer, Position);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003704
Chris Lattnera660f4b2008-07-09 05:14:23 +00003705 // If the file is not a multiple of 16 bytes, insert dummy padding.
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003706 while (Buffer.size() & 15)
3707 Buffer.push_back(0);
Chris Lattnera660f4b2008-07-09 05:14:23 +00003708}
3709
Teresa Johnson403a7872015-10-04 14:33:43 +00003710/// Helper to write the header common to all bitcode files.
Teresa Johnson37687f32016-04-23 04:30:47 +00003711void BitcodeWriter::writeBitcodeHeader() {
Teresa Johnson403a7872015-10-04 14:33:43 +00003712 // Emit the file header.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003713 Stream.Emit((unsigned)'B', 8);
3714 Stream.Emit((unsigned)'C', 8);
3715 Stream.Emit(0x0, 4);
3716 Stream.Emit(0xC, 4);
3717 Stream.Emit(0xE, 4);
3718 Stream.Emit(0xD, 4);
Teresa Johnson403a7872015-10-04 14:33:43 +00003719}
3720
Chris Lattnerc1d10d62007-04-22 06:24:45 +00003721/// WriteBitcodeToFile - Write the specified module to the specified output
3722/// stream.
Duncan P. N. Exon Smitha052ed62015-04-15 00:10:50 +00003723void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
Teresa Johnson403a7872015-10-04 14:33:43 +00003724 bool ShouldPreserveUseListOrder,
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003725 const ModuleSummaryIndex *Index,
3726 bool GenerateHash) {
Michael Ilsemane26658d2012-12-03 21:29:36 +00003727 SmallVector<char, 0> Buffer;
Chris Lattnerc1d10d62007-04-22 06:24:45 +00003728 Buffer.reserve(256*1024);
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00003729
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003730 // If this is darwin or another generic macho target, reserve space for the
3731 // header.
3732 Triple TT(M->getTargetTriple());
Akira Hatanaka1235d282016-01-23 16:02:10 +00003733 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Akira Hatanaka4f472a882016-01-29 05:55:09 +00003734 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003735
3736 // Emit the module into the buffer.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003737 ModuleBitcodeWriter ModuleWriter(M, Buffer, ShouldPreserveUseListOrder, Index,
3738 GenerateHash);
Teresa Johnson37687f32016-04-23 04:30:47 +00003739 ModuleWriter.write();
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003740
Akira Hatanaka1235d282016-01-23 16:02:10 +00003741 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Teresa Johnson37687f32016-04-23 04:30:47 +00003742 emitDarwinBCHeaderAndTrailer(Buffer, TT);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003743
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00003744 // Write the generated bitstream to "Out".
3745 Out.write((char*)&Buffer.front(), Buffer.size());
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00003746}
Teresa Johnson403a7872015-10-04 14:33:43 +00003747
Teresa Johnson37687f32016-04-23 04:30:47 +00003748void IndexBitcodeWriter::writeIndex() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003749 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
Teresa Johnson37687f32016-04-23 04:30:47 +00003750
3751 SmallVector<unsigned, 1> Vals;
3752 unsigned CurVersion = 1;
3753 Vals.push_back(CurVersion);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003754 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
Teresa Johnson37687f32016-04-23 04:30:47 +00003755
3756 // If we have a VST, write the VSTOFFSET record placeholder.
3757 writeValueSymbolTableForwardDecl();
3758
3759 // Write the module paths in the combined index.
3760 writeModStrings();
3761
3762 // Write the summary combined index records.
3763 writeCombinedGlobalValueSummary();
3764
3765 // Need a special VST writer for the combined index (we don't have a
3766 // real VST and real values when this is invoked).
3767 writeCombinedValueSymbolTable();
3768
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003769 Stream.ExitBlock();
Teresa Johnson37687f32016-04-23 04:30:47 +00003770}
3771
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003772// Write the specified module summary index to the given raw output stream,
Teresa Johnson403a7872015-10-04 14:33:43 +00003773// where it will be written in a new bitcode block. This is used when
Teresa Johnson84174c32016-05-10 13:48:23 +00003774// writing the combined index file for ThinLTO. When writing a subset of the
3775// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
3776void llvm::WriteIndexToFile(
3777 const ModuleSummaryIndex &Index, raw_ostream &Out,
3778 std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003779 SmallVector<char, 0> Buffer;
3780 Buffer.reserve(256 * 1024);
3781
Teresa Johnson84174c32016-05-10 13:48:23 +00003782 IndexBitcodeWriter IndexWriter(Buffer, Index, ModuleToSummariesForIndex);
Teresa Johnson37687f32016-04-23 04:30:47 +00003783 IndexWriter.write();
Teresa Johnson403a7872015-10-04 14:33:43 +00003784
3785 Out.write((char *)&Buffer.front(), Buffer.size());
3786}