blob: 0e518d2bbc8ff472f61d4021a6a7441f13aae0b5 [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
Teresa Johnsonad176792016-11-11 05:34:58 +000014#include "llvm/Bitcode/BitcodeWriter.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "ValueEnumerator.h"
Mehdi Aminid7ad2212016-04-01 05:33:11 +000016#include "llvm/ADT/StringExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/Triple.h"
Chris Lattnerc1d10d62007-04-22 06:24:45 +000018#include "llvm/Bitcode/BitstreamWriter.h"
Chris Lattner362b4a12007-04-23 01:01:37 +000019#include "llvm/Bitcode/LLVMBitCodes.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"
Peter Collingbournea0f371a2017-04-17 17:51:36 +000031#include "llvm/MC/StringTableBuilder.h"
Peter Collingbourne92648c22017-06-27 23:50:11 +000032#include "llvm/Object/IRSymtab.h"
Torok Edwin56d06592009-07-11 20:10:48 +000033#include "llvm/Support/ErrorHandling.h"
Chris Lattnerc1d10d62007-04-22 06:24:45 +000034#include "llvm/Support/MathExtras.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000035#include "llvm/Support/Program.h"
Mehdi Aminid7ad2212016-04-01 05:33:11 +000036#include "llvm/Support/SHA1.h"
Peter Collingbourne92648c22017-06-27 23:50:11 +000037#include "llvm/Support/TargetRegistry.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000038#include "llvm/Support/raw_ostream.h"
Nick Lewycky0de20af2010-12-19 20:43:38 +000039#include <cctype>
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000040#include <map>
Chris Lattnerc1d10d62007-04-22 06:24:45 +000041using namespace llvm;
42
Benjamin Kramera65b6102016-05-15 15:18:11 +000043namespace {
Mehdi Aminie98f9252016-12-28 22:30:28 +000044
45cl::opt<unsigned>
46 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
47 cl::desc("Number of metadatas above which we emit an index "
48 "to enable lazy-loading"));
Chris Lattner4d925982007-05-04 20:52:02 +000049/// These are manifest constants used by the bitcode writer. They do not need to
50/// be kept in sync with the reader, but need to be consistent within this file.
51enum {
Chris Lattner4d925982007-05-04 20:52:02 +000052 // VALUE_SYMTAB_BLOCK abbrev id's.
53 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
Chris Lattnerfd1ad102007-05-04 20:58:35 +000054 VST_ENTRY_7_ABBREV,
Chris Lattnere760d6f2007-05-05 01:26:50 +000055 VST_ENTRY_6_ABBREV,
Chris Lattnerda5e5d22007-05-05 07:36:14 +000056 VST_BBENTRY_6_ABBREV,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000057
Chris Lattnerda5e5d22007-05-05 07:36:14 +000058 // CONSTANTS_BLOCK abbrev id's.
59 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
60 CONSTANTS_INTEGER_ABBREV,
61 CONSTANTS_CE_CAST_Abbrev,
Chris Lattnerb80751d2007-05-05 07:44:49 +000062 CONSTANTS_NULL_Abbrev,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000063
Chris Lattnerb80751d2007-05-05 07:44:49 +000064 // FUNCTION_BLOCK abbrev id's.
Chris Lattnercc6d4c92007-05-06 01:28:01 +000065 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
Chris Lattnerc67e6d92007-05-06 02:38:57 +000066 FUNCTION_INST_BINOP_ABBREV,
Dan Gohman0ebd6962009-07-20 21:19:07 +000067 FUNCTION_INST_BINOP_FLAGS_ABBREV,
Chris Lattnerc67e6d92007-05-06 02:38:57 +000068 FUNCTION_INST_CAST_ABBREV,
Chris Lattnercc6d4c92007-05-06 01:28:01 +000069 FUNCTION_INST_RET_VOID_ABBREV,
70 FUNCTION_INST_RET_VAL_ABBREV,
David Blaikieb5b5efd2015-02-25 01:08:52 +000071 FUNCTION_INST_UNREACHABLE_ABBREV,
72 FUNCTION_INST_GEP_ABBREV,
Chris Lattner4d925982007-05-04 20:52:02 +000073};
74
Teresa Johnsonc814e0c2016-04-23 04:31:20 +000075/// Abstract class to manage the bitcode writing, subclassed for each bitcode
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +000076/// file type.
77class BitcodeWriterBase {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +000078protected:
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +000079 /// The stream created and owned by the client.
80 BitstreamWriter &Stream;
Teresa Johnson37687f32016-04-23 04:30:47 +000081
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +000082 StringTableBuilder &StrtabBuilder;
83
Teresa Johnson37687f32016-04-23 04:30:47 +000084public:
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +000085 /// Constructs a BitcodeWriterBase object that writes to the provided
86 /// \p Stream.
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +000087 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
88 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
Teresa Johnson37687f32016-04-23 04:30:47 +000089
90protected:
Teresa Johnson37687f32016-04-23 04:30:47 +000091 void writeBitcodeHeader();
Peter Collingbournea0f371a2017-04-17 17:51:36 +000092 void writeModuleVersion();
Teresa Johnson37687f32016-04-23 04:30:47 +000093};
94
Peter Collingbournea0f371a2017-04-17 17:51:36 +000095void BitcodeWriterBase::writeModuleVersion() {
96 // VERSION: [version#]
97 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
98}
99
Teresa Johnson37687f32016-04-23 04:30:47 +0000100/// Class to manage the bitcode writing for a module.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000101class ModuleBitcodeWriter : public BitcodeWriterBase {
102 /// Pointer to the buffer allocated by caller for bitcode writing.
103 const SmallVectorImpl<char> &Buffer;
104
Teresa Johnson37687f32016-04-23 04:30:47 +0000105 /// The Module to write to bitcode.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000106 const Module &M;
Teresa Johnson37687f32016-04-23 04:30:47 +0000107
108 /// Enumerates ids for all values in the module.
109 ValueEnumerator VE;
110
111 /// Optional per-module index to write for ThinLTO.
112 const ModuleSummaryIndex *Index;
113
114 /// True if a module hash record should be written.
115 bool GenerateHash;
116
Peter Collingbournec8556152017-07-06 17:56:01 +0000117 SHA1 Hasher;
118
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000119 /// If non-null, when GenerateHash is true, the resulting hash is written
120 /// into ModHash. When GenerateHash is false, that specified value
121 /// is used as the hash instead of computing from the generated bitcode.
122 /// Can be used to produce the same module hash for a minimized bitcode
123 /// used just for the thin link as in the regular full bitcode that will
124 /// be used in the backend.
125 ModuleHash *ModHash;
126
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000127 /// The start bit of the identification block.
128 uint64_t BitcodeStartBit;
Teresa Johnson37687f32016-04-23 04:30:47 +0000129
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000130 /// Map that holds the correspondence between GUIDs in the summary index,
131 /// that came from indirect call profiles, and a value id generated by this
132 /// class to use in the VST and summary block records.
133 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
134
135 /// Tracks the last value id recorded in the GUIDToValueMap.
136 unsigned GlobalValueId;
137
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000138 /// Saves the offset of the VSTOffset record that must eventually be
139 /// backpatched with the offset of the actual VST.
140 uint64_t VSTOffsetPlaceholder = 0;
141
Teresa Johnson37687f32016-04-23 04:30:47 +0000142public:
143 /// Constructs a ModuleBitcodeWriter object for the given Module,
144 /// writing to the provided \p Buffer.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000145 ModuleBitcodeWriter(const Module *M, SmallVectorImpl<char> &Buffer,
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000146 StringTableBuilder &StrtabBuilder,
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000147 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000148 const ModuleSummaryIndex *Index, bool GenerateHash,
149 ModuleHash *ModHash = nullptr)
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000150 : BitcodeWriterBase(Stream, StrtabBuilder), Buffer(Buffer), M(*M),
151 VE(*M, ShouldPreserveUseListOrder), Index(Index),
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000152 GenerateHash(GenerateHash), ModHash(ModHash),
153 BitcodeStartBit(Stream.GetCurrentBitNo()) {
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000154 // Assign ValueIds to any callee values in the index that came from
155 // indirect call profiles and were recorded as a GUID not a Value*
156 // (which would have been assigned an ID by the ValueEnumerator).
157 // The starting ValueId is just after the number of values in the
158 // ValueEnumerator, so that they can be emitted in the VST.
159 GlobalValueId = VE.getValues().size();
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000160 if (!Index)
161 return;
162 for (const auto &GUIDSummaryLists : *Index)
163 // Examine all summaries for this GUID.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000164 for (auto &Summary : GUIDSummaryLists.second.SummaryList)
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000165 if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
166 // For each call in the function summary, see if the call
167 // is to a GUID (which means it is for an indirect call,
168 // otherwise we would have a Value for it). If so, synthesize
169 // a value id.
170 for (auto &CallEdge : FS->calls())
Peter Collingbourne9667b912017-05-04 18:03:25 +0000171 if (!CallEdge.first.getValue())
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000172 assignValueId(CallEdge.first.getGUID());
Teresa Johnson37687f32016-04-23 04:30:47 +0000173 }
174
Teresa Johnson37687f32016-04-23 04:30:47 +0000175 /// Emit the current module to the bitstream.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000176 void write();
Teresa Johnson37687f32016-04-23 04:30:47 +0000177
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000178private:
Teresa Johnson37687f32016-04-23 04:30:47 +0000179 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
180
Peter Collingbournec8556152017-07-06 17:56:01 +0000181 size_t addToStrtab(StringRef Str);
182
Teresa Johnson37687f32016-04-23 04:30:47 +0000183 void writeAttributeGroupTable();
184 void writeAttributeTable();
185 void writeTypeTable();
186 void writeComdats();
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000187 void writeValueSymbolTableForwardDecl();
Teresa Johnson37687f32016-04-23 04:30:47 +0000188 void writeModuleInfo();
189 void writeValueAsMetadata(const ValueAsMetadata *MD,
190 SmallVectorImpl<uint64_t> &Record);
191 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
192 unsigned Abbrev);
193 unsigned createDILocationAbbrev();
194 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
195 unsigned &Abbrev);
196 unsigned createGenericDINodeAbbrev();
197 void writeGenericDINode(const GenericDINode *N,
198 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
199 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
200 unsigned Abbrev);
201 void writeDIEnumerator(const DIEnumerator *N,
202 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
203 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
204 unsigned Abbrev);
205 void writeDIDerivedType(const DIDerivedType *N,
206 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
207 void writeDICompositeType(const DICompositeType *N,
208 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
209 void writeDISubroutineType(const DISubroutineType *N,
210 SmallVectorImpl<uint64_t> &Record,
211 unsigned Abbrev);
212 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
213 unsigned Abbrev);
214 void writeDICompileUnit(const DICompileUnit *N,
215 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
216 void writeDISubprogram(const DISubprogram *N,
217 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
218 void writeDILexicalBlock(const DILexicalBlock *N,
219 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
220 void writeDILexicalBlockFile(const DILexicalBlockFile *N,
221 SmallVectorImpl<uint64_t> &Record,
222 unsigned Abbrev);
223 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
224 unsigned Abbrev);
225 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
226 unsigned Abbrev);
227 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
228 unsigned Abbrev);
229 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
230 unsigned Abbrev);
231 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
232 SmallVectorImpl<uint64_t> &Record,
233 unsigned Abbrev);
234 void writeDITemplateValueParameter(const DITemplateValueParameter *N,
235 SmallVectorImpl<uint64_t> &Record,
236 unsigned Abbrev);
237 void writeDIGlobalVariable(const DIGlobalVariable *N,
238 SmallVectorImpl<uint64_t> &Record,
239 unsigned Abbrev);
240 void writeDILocalVariable(const DILocalVariable *N,
241 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
242 void writeDIExpression(const DIExpression *N,
243 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000244 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
245 SmallVectorImpl<uint64_t> &Record,
246 unsigned Abbrev);
Teresa Johnson37687f32016-04-23 04:30:47 +0000247 void writeDIObjCProperty(const DIObjCProperty *N,
248 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
249 void writeDIImportedEntity(const DIImportedEntity *N,
250 SmallVectorImpl<uint64_t> &Record,
251 unsigned Abbrev);
252 unsigned createNamedMetadataAbbrev();
253 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
254 unsigned createMetadataStringsAbbrev();
255 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
256 SmallVectorImpl<uint64_t> &Record);
257 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
Mehdi Aminie98f9252016-12-28 22:30:28 +0000258 SmallVectorImpl<uint64_t> &Record,
259 std::vector<unsigned> *MDAbbrevs = nullptr,
260 std::vector<uint64_t> *IndexPos = nullptr);
Teresa Johnson37687f32016-04-23 04:30:47 +0000261 void writeModuleMetadata();
262 void writeFunctionMetadata(const Function &F);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000263 void writeFunctionMetadataAttachment(const Function &F);
264 void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
265 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
266 const GlobalObject &GO);
Peter Collingbourne21521892016-06-21 23:42:48 +0000267 void writeModuleMetadataKinds();
Teresa Johnson37687f32016-04-23 04:30:47 +0000268 void writeOperandBundleTags();
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000269 void writeSyncScopeNames();
Teresa Johnson37687f32016-04-23 04:30:47 +0000270 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
271 void writeModuleConstants();
272 bool pushValueAndType(const Value *V, unsigned InstID,
273 SmallVectorImpl<unsigned> &Vals);
274 void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
275 void pushValue(const Value *V, unsigned InstID,
276 SmallVectorImpl<unsigned> &Vals);
277 void pushValueSigned(const Value *V, unsigned InstID,
278 SmallVectorImpl<uint64_t> &Vals);
279 void writeInstruction(const Instruction &I, unsigned InstID,
280 SmallVectorImpl<unsigned> &Vals);
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000281 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
282 void writeGlobalValueSymbolTable(
283 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
Teresa Johnson37687f32016-04-23 04:30:47 +0000284 void writeUseList(UseListOrder &&Order);
285 void writeUseListBlock(const Function *F);
286 void
287 writeFunction(const Function &F,
288 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
289 void writeBlockInfo();
290 void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
Teresa Johnson28e457b2016-04-24 14:57:11 +0000291 GlobalValueSummary *Summary,
Teresa Johnson37687f32016-04-23 04:30:47 +0000292 unsigned ValueID,
293 unsigned FSCallsAbbrev,
294 unsigned FSCallsProfileAbbrev,
295 const Function &F);
296 void writeModuleLevelReferences(const GlobalVariable &V,
297 SmallVector<uint64_t, 64> &NameVals,
298 unsigned FSModRefsAbbrev);
299 void writePerModuleGlobalValueSummary();
300 void writeModuleHash(size_t BlockStartPos);
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000301
302 void assignValueId(GlobalValue::GUID ValGUID) {
303 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
304 }
305 unsigned getValueId(GlobalValue::GUID ValGUID) {
306 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000307 // Expect that any GUID value had a value Id assigned by an
308 // earlier call to assignValueId.
309 assert(VMI != GUIDToValueIdMap.end() &&
310 "GUID does not have assigned value Id");
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000311 return VMI->second;
312 }
313 // Helper to get the valueId for the type of value recorded in VI.
314 unsigned getValueId(ValueInfo VI) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000315 if (!VI.getValue())
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000316 return getValueId(VI.getGUID());
317 return VE.getValueID(VI.getValue());
318 }
319 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000320
321 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
322 return unsigned(SSID);
323 }
Teresa Johnson37687f32016-04-23 04:30:47 +0000324};
325
326/// Class to manage the bitcode writing for a combined index.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000327class IndexBitcodeWriter : public BitcodeWriterBase {
Teresa Johnson37687f32016-04-23 04:30:47 +0000328 /// The combined index to write to bitcode.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000329 const ModuleSummaryIndex &Index;
Teresa Johnson37687f32016-04-23 04:30:47 +0000330
Teresa Johnson84174c32016-05-10 13:48:23 +0000331 /// When writing a subset of the index for distributed backends, client
332 /// provides a map of modules to the corresponding GUIDs/summaries to write.
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +0000333 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
Teresa Johnson84174c32016-05-10 13:48:23 +0000334
Teresa Johnson37687f32016-04-23 04:30:47 +0000335 /// Map that holds the correspondence between the GUID used in the combined
336 /// index and a value id generated by this class to use in references.
337 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
338
339 /// Tracks the last value id recorded in the GUIDToValueMap.
340 unsigned GlobalValueId = 0;
341
342public:
343 /// Constructs a IndexBitcodeWriter object for the given combined index,
Teresa Johnson84174c32016-05-10 13:48:23 +0000344 /// writing to the provided \p Buffer. When writing a subset of the index
345 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000346 IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
347 const ModuleSummaryIndex &Index,
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +0000348 const std::map<std::string, GVSummaryMapTy>
Teresa Johnson84174c32016-05-10 13:48:23 +0000349 *ModuleToSummariesForIndex = nullptr)
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000350 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
Teresa Johnson84174c32016-05-10 13:48:23 +0000351 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
352 // Assign unique value ids to all summaries to be written, for use
Teresa Johnson37687f32016-04-23 04:30:47 +0000353 // in writing out the call graph edges. Save the mapping from GUID
354 // to the new global value id to use when writing those edges, which
355 // are currently saved in the index in terms of GUID.
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000356 forEachSummary([&](GVInfo I) {
Teresa Johnson84174c32016-05-10 13:48:23 +0000357 GUIDToValueIdMap[I.first] = ++GlobalValueId;
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000358 });
Teresa Johnson37687f32016-04-23 04:30:47 +0000359 }
360
Teresa Johnson84174c32016-05-10 13:48:23 +0000361 /// The below iterator returns the GUID and associated summary.
362 typedef std::pair<GlobalValue::GUID, GlobalValueSummary *> GVInfo;
363
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000364 /// Calls the callback for each value GUID and summary to be written to
365 /// bitcode. This hides the details of whether they are being pulled from the
366 /// entire index or just those in a provided ModuleToSummariesForIndex map.
David Blaikie358c0122017-06-02 18:25:29 +0000367 template<typename Functor>
368 void forEachSummary(Functor Callback) {
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000369 if (ModuleToSummariesForIndex) {
370 for (auto &M : *ModuleToSummariesForIndex)
371 for (auto &Summary : M.second)
372 Callback(Summary);
373 } else {
374 for (auto &Summaries : Index)
Peter Collingbourne9667b912017-05-04 18:03:25 +0000375 for (auto &Summary : Summaries.second.SummaryList)
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000376 Callback({Summaries.first, Summary.get()});
Teresa Johnson84174c32016-05-10 13:48:23 +0000377 }
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000378 }
Teresa Johnson84174c32016-05-10 13:48:23 +0000379
Teresa Johnson7a27b132017-06-02 01:56:02 +0000380 /// Calls the callback for each entry in the modulePaths StringMap that
381 /// should be written to the module path string table. This hides the details
382 /// of whether they are being pulled from the entire index or just those in a
383 /// provided ModuleToSummariesForIndex map.
David Blaikieb6b42e02017-06-02 17:24:26 +0000384 template <typename Functor> void forEachModule(Functor Callback) {
Teresa Johnson7a27b132017-06-02 01:56:02 +0000385 if (ModuleToSummariesForIndex) {
386 for (const auto &M : *ModuleToSummariesForIndex) {
387 const auto &MPI = Index.modulePaths().find(M.first);
388 if (MPI == Index.modulePaths().end()) {
389 // This should only happen if the bitcode file was empty, in which
390 // case we shouldn't be importing (the ModuleToSummariesForIndex
391 // would only include the module we are writing and index for).
392 assert(ModuleToSummariesForIndex->size() == 1);
393 continue;
394 }
395 Callback(*MPI);
396 }
397 } else {
398 for (const auto &MPSE : Index.modulePaths())
399 Callback(MPSE);
400 }
401 }
402
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000403 /// Main entry point for writing a combined index to bitcode.
404 void write();
Teresa Johnson37687f32016-04-23 04:30:47 +0000405
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000406private:
Teresa Johnson37687f32016-04-23 04:30:47 +0000407 void writeModStrings();
Teresa Johnson37687f32016-04-23 04:30:47 +0000408 void writeCombinedGlobalValueSummary();
409
Teresa Johnsona6a3fb52017-05-31 18:58:11 +0000410 Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000411 auto VMI = GUIDToValueIdMap.find(ValGUID);
Teresa Johnsona6a3fb52017-05-31 18:58:11 +0000412 if (VMI == GUIDToValueIdMap.end())
413 return None;
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000414 return VMI->second;
Teresa Johnson37687f32016-04-23 04:30:47 +0000415 }
Teresa Johnson37687f32016-04-23 04:30:47 +0000416 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
417};
Benjamin Kramera65b6102016-05-15 15:18:11 +0000418} // end anonymous namespace
Teresa Johnson37687f32016-04-23 04:30:47 +0000419
420static unsigned getEncodedCastOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000421 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000422 default: llvm_unreachable("Unknown cast instruction!");
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000423 case Instruction::Trunc : return bitc::CAST_TRUNC;
424 case Instruction::ZExt : return bitc::CAST_ZEXT;
425 case Instruction::SExt : return bitc::CAST_SEXT;
426 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
427 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
428 case Instruction::UIToFP : return bitc::CAST_UITOFP;
429 case Instruction::SIToFP : return bitc::CAST_SITOFP;
430 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
431 case Instruction::FPExt : return bitc::CAST_FPEXT;
432 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
433 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
434 case Instruction::BitCast : return bitc::CAST_BITCAST;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000435 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000436 }
437}
438
Teresa Johnson37687f32016-04-23 04:30:47 +0000439static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000440 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000441 default: llvm_unreachable("Unknown binary instruction!");
Dan Gohmana5b96452009-06-04 22:49:04 +0000442 case Instruction::Add:
443 case Instruction::FAdd: return bitc::BINOP_ADD;
444 case Instruction::Sub:
445 case Instruction::FSub: return bitc::BINOP_SUB;
446 case Instruction::Mul:
447 case Instruction::FMul: return bitc::BINOP_MUL;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000448 case Instruction::UDiv: return bitc::BINOP_UDIV;
449 case Instruction::FDiv:
450 case Instruction::SDiv: return bitc::BINOP_SDIV;
451 case Instruction::URem: return bitc::BINOP_UREM;
452 case Instruction::FRem:
453 case Instruction::SRem: return bitc::BINOP_SREM;
454 case Instruction::Shl: return bitc::BINOP_SHL;
455 case Instruction::LShr: return bitc::BINOP_LSHR;
456 case Instruction::AShr: return bitc::BINOP_ASHR;
457 case Instruction::And: return bitc::BINOP_AND;
458 case Instruction::Or: return bitc::BINOP_OR;
459 case Instruction::Xor: return bitc::BINOP_XOR;
460 }
461}
462
Teresa Johnson37687f32016-04-23 04:30:47 +0000463static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000464 switch (Op) {
465 default: llvm_unreachable("Unknown RMW operation!");
466 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
467 case AtomicRMWInst::Add: return bitc::RMW_ADD;
468 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
469 case AtomicRMWInst::And: return bitc::RMW_AND;
470 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
471 case AtomicRMWInst::Or: return bitc::RMW_OR;
472 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
473 case AtomicRMWInst::Max: return bitc::RMW_MAX;
474 case AtomicRMWInst::Min: return bitc::RMW_MIN;
475 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
476 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
477 }
478}
479
Teresa Johnson37687f32016-04-23 04:30:47 +0000480static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000481 switch (Ordering) {
JF Bastien800f87a2016-04-06 21:19:33 +0000482 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
483 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
484 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
485 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
486 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
487 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
488 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000489 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000490 llvm_unreachable("Invalid ordering");
Eli Friedmanfee02c62011-07-25 23:16:38 +0000491}
492
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000493static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
494 StringRef Str, unsigned AbbrevToUse) {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000495 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000496
Chris Lattnere14cb882007-05-04 19:11:41 +0000497 // Code: [strchar x N]
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000498 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
499 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
500 AbbrevToUse = 0;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000501 Vals.push_back(Str[i]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000502 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000503
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000504 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000505 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000506}
507
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000508static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
509 switch (Kind) {
510 case Attribute::Alignment:
511 return bitc::ATTR_KIND_ALIGNMENT;
George Burgess IV278199f2016-04-12 01:05:35 +0000512 case Attribute::AllocSize:
513 return bitc::ATTR_KIND_ALLOC_SIZE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000514 case Attribute::AlwaysInline:
515 return bitc::ATTR_KIND_ALWAYS_INLINE;
Igor Laevsky39d662f2015-07-11 10:30:36 +0000516 case Attribute::ArgMemOnly:
517 return bitc::ATTR_KIND_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000518 case Attribute::Builtin:
519 return bitc::ATTR_KIND_BUILTIN;
520 case Attribute::ByVal:
521 return bitc::ATTR_KIND_BY_VAL;
Owen Anderson85fa7d52015-05-26 23:48:40 +0000522 case Attribute::Convergent:
523 return bitc::ATTR_KIND_CONVERGENT;
Reid Klecknera534a382013-12-19 02:14:12 +0000524 case Attribute::InAlloca:
525 return bitc::ATTR_KIND_IN_ALLOCA;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000526 case Attribute::Cold:
527 return bitc::ATTR_KIND_COLD;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +0000528 case Attribute::InaccessibleMemOnly:
529 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
530 case Attribute::InaccessibleMemOrArgMemOnly:
531 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000532 case Attribute::InlineHint:
533 return bitc::ATTR_KIND_INLINE_HINT;
534 case Attribute::InReg:
535 return bitc::ATTR_KIND_IN_REG;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000536 case Attribute::JumpTable:
537 return bitc::ATTR_KIND_JUMP_TABLE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000538 case Attribute::MinSize:
539 return bitc::ATTR_KIND_MIN_SIZE;
540 case Attribute::Naked:
541 return bitc::ATTR_KIND_NAKED;
542 case Attribute::Nest:
543 return bitc::ATTR_KIND_NEST;
544 case Attribute::NoAlias:
545 return bitc::ATTR_KIND_NO_ALIAS;
546 case Attribute::NoBuiltin:
547 return bitc::ATTR_KIND_NO_BUILTIN;
548 case Attribute::NoCapture:
549 return bitc::ATTR_KIND_NO_CAPTURE;
550 case Attribute::NoDuplicate:
551 return bitc::ATTR_KIND_NO_DUPLICATE;
552 case Attribute::NoImplicitFloat:
553 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
554 case Attribute::NoInline:
555 return bitc::ATTR_KIND_NO_INLINE;
James Molloye6f87ca2015-11-06 10:32:53 +0000556 case Attribute::NoRecurse:
557 return bitc::ATTR_KIND_NO_RECURSE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000558 case Attribute::NonLazyBind:
559 return bitc::ATTR_KIND_NON_LAZY_BIND;
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000560 case Attribute::NonNull:
561 return bitc::ATTR_KIND_NON_NULL;
Hal Finkelb0407ba2014-07-18 15:51:28 +0000562 case Attribute::Dereferenceable:
563 return bitc::ATTR_KIND_DEREFERENCEABLE;
Sanjoy Das31ea6d12015-04-16 20:29:50 +0000564 case Attribute::DereferenceableOrNull:
565 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000566 case Attribute::NoRedZone:
567 return bitc::ATTR_KIND_NO_RED_ZONE;
568 case Attribute::NoReturn:
569 return bitc::ATTR_KIND_NO_RETURN;
570 case Attribute::NoUnwind:
571 return bitc::ATTR_KIND_NO_UNWIND;
572 case Attribute::OptimizeForSize:
573 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000574 case Attribute::OptimizeNone:
575 return bitc::ATTR_KIND_OPTIMIZE_NONE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000576 case Attribute::ReadNone:
577 return bitc::ATTR_KIND_READ_NONE;
578 case Attribute::ReadOnly:
579 return bitc::ATTR_KIND_READ_ONLY;
580 case Attribute::Returned:
581 return bitc::ATTR_KIND_RETURNED;
582 case Attribute::ReturnsTwice:
583 return bitc::ATTR_KIND_RETURNS_TWICE;
584 case Attribute::SExt:
585 return bitc::ATTR_KIND_S_EXT;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +0000586 case Attribute::Speculatable:
587 return bitc::ATTR_KIND_SPECULATABLE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000588 case Attribute::StackAlignment:
589 return bitc::ATTR_KIND_STACK_ALIGNMENT;
590 case Attribute::StackProtect:
591 return bitc::ATTR_KIND_STACK_PROTECT;
592 case Attribute::StackProtectReq:
593 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
594 case Attribute::StackProtectStrong:
595 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000596 case Attribute::SafeStack:
597 return bitc::ATTR_KIND_SAFESTACK;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000598 case Attribute::StructRet:
599 return bitc::ATTR_KIND_STRUCT_RET;
600 case Attribute::SanitizeAddress:
601 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
602 case Attribute::SanitizeThread:
603 return bitc::ATTR_KIND_SANITIZE_THREAD;
604 case Attribute::SanitizeMemory:
605 return bitc::ATTR_KIND_SANITIZE_MEMORY;
Manman Ren9bfd0d02016-04-01 21:41:15 +0000606 case Attribute::SwiftError:
607 return bitc::ATTR_KIND_SWIFT_ERROR;
Manman Renf46262e2016-03-29 17:37:21 +0000608 case Attribute::SwiftSelf:
609 return bitc::ATTR_KIND_SWIFT_SELF;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000610 case Attribute::UWTable:
611 return bitc::ATTR_KIND_UW_TABLE;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +0000612 case Attribute::WriteOnly:
613 return bitc::ATTR_KIND_WRITEONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000614 case Attribute::ZExt:
615 return bitc::ATTR_KIND_Z_EXT;
616 case Attribute::EndAttrKinds:
617 llvm_unreachable("Can not encode end-attribute kinds marker.");
618 case Attribute::None:
619 llvm_unreachable("Can not encode none-attribute.");
620 }
621
622 llvm_unreachable("Trying to encode unknown attribute");
623}
624
Teresa Johnson37687f32016-04-23 04:30:47 +0000625void ModuleBitcodeWriter::writeAttributeGroupTable() {
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000626 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
627 VE.getAttributeGroups();
Bill Wendling92ed7002013-02-11 22:33:26 +0000628 if (AttrGrps.empty()) return;
Bill Wendlingdc095552013-02-10 23:09:32 +0000629
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000630 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
Bill Wendlingdc095552013-02-10 23:09:32 +0000631
632 SmallVector<uint64_t, 64> Record;
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000633 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
634 unsigned AttrListIndex = Pair.first;
635 AttributeSet AS = Pair.second;
636 Record.push_back(VE.getAttributeGroupID(Pair));
637 Record.push_back(AttrListIndex);
Bill Wendlingdc095552013-02-10 23:09:32 +0000638
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000639 for (Attribute Attr : AS) {
640 if (Attr.isEnumAttribute()) {
641 Record.push_back(0);
642 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
643 } else if (Attr.isIntAttribute()) {
644 Record.push_back(1);
645 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
646 Record.push_back(Attr.getValueAsInt());
647 } else {
648 StringRef Kind = Attr.getKindAsString();
649 StringRef Val = Attr.getValueAsString();
Bill Wendlingdc095552013-02-10 23:09:32 +0000650
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000651 Record.push_back(Val.empty() ? 3 : 4);
652 Record.append(Kind.begin(), Kind.end());
653 Record.push_back(0);
654 if (!Val.empty()) {
655 Record.append(Val.begin(), Val.end());
Bill Wendlingdc095552013-02-10 23:09:32 +0000656 Record.push_back(0);
Bill Wendlingdc095552013-02-10 23:09:32 +0000657 }
658 }
Bill Wendlingdc095552013-02-10 23:09:32 +0000659 }
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000660
661 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
662 Record.clear();
Bill Wendlingdc095552013-02-10 23:09:32 +0000663 }
664
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000665 Stream.ExitBlock();
Bill Wendlingdc095552013-02-10 23:09:32 +0000666}
667
Teresa Johnson37687f32016-04-23 04:30:47 +0000668void ModuleBitcodeWriter::writeAttributeTable() {
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000669 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000670 if (Attrs.empty()) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000671
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000672 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000673
674 SmallVector<uint64_t, 64> Record;
675 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
Reid Kleckner8bf67fe2017-05-23 17:01:48 +0000676 AttributeList AL = Attrs[i];
677 for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) {
678 AttributeSet AS = AL.getAttributes(i);
679 if (AS.hasAttributes())
680 Record.push_back(VE.getAttributeGroupID({i, AS}));
681 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000682
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000683 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000684 Record.clear();
685 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000686
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000687 Stream.ExitBlock();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000688}
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000689
690/// WriteTypeTable - Write out the type table for a module.
Teresa Johnson37687f32016-04-23 04:30:47 +0000691void ModuleBitcodeWriter::writeTypeTable() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000692 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000693
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000694 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000695 SmallVector<uint64_t, 64> TypeVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000696
David Blaikie7b028102015-02-25 00:51:52 +0000697 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
Chad Rosier9646c0d2011-12-08 00:38:45 +0000698
Chris Lattnerccee7062007-05-05 06:30:12 +0000699 // Abbrev for TYPE_CODE_POINTER.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000700 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000701 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000702 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
Christopher Lamb25f50762007-12-12 08:44:39 +0000703 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
David Blaikie7ad9dc12017-01-04 22:36:33 +0000704 unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000705
Chris Lattnerccee7062007-05-05 06:30:12 +0000706 // Abbrev for TYPE_CODE_FUNCTION.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000707 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000708 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
709 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
Chris Lattnerccee7062007-05-05 06:30:12 +0000710 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000711 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
712
David Blaikie7ad9dc12017-01-04 22:36:33 +0000713 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000714
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000715 // Abbrev for TYPE_CODE_STRUCT_ANON.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000716 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000717 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
Chris Lattnerccee7062007-05-05 06:30:12 +0000718 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
719 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000720 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
721
David Blaikie7ad9dc12017-01-04 22:36:33 +0000722 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000723
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000724 // Abbrev for TYPE_CODE_STRUCT_NAME.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000725 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000726 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
727 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
728 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000729 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000730
731 // Abbrev for TYPE_CODE_STRUCT_NAMED.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000732 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000733 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
734 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
735 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000736 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
737
David Blaikie7ad9dc12017-01-04 22:36:33 +0000738 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000739
Chris Lattnerccee7062007-05-05 06:30:12 +0000740 // Abbrev for TYPE_CODE_ARRAY.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000741 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000742 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
743 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
Chad Rosier9646c0d2011-12-08 00:38:45 +0000744 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
745
David Blaikie7ad9dc12017-01-04 22:36:33 +0000746 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000747
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000748 // Emit an entry count so the reader can reserve space.
749 TypeVals.push_back(TypeList.size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000750 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000751 TypeVals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000752
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000753 // Loop over all of the types, emitting each in turn.
754 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +0000755 Type *T = TypeList[i];
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000756 int AbbrevToUse = 0;
757 unsigned Code = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000758
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000759 switch (T->getTypeID()) {
Joe Abbey2ad8df22012-11-25 15:23:39 +0000760 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
761 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
762 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
763 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
764 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
765 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000766 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
Joe Abbey2ad8df22012-11-25 15:23:39 +0000767 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
768 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
769 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
David Majnemerb611e3f2015-08-14 05:09:07 +0000770 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000771 case Type::IntegerTyID:
772 // INTEGER: [width]
773 Code = bitc::TYPE_CODE_INTEGER;
774 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
775 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000776 case Type::PointerTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000777 PointerType *PTy = cast<PointerType>(T);
Christopher Lamb25f50762007-12-12 08:44:39 +0000778 // POINTER: [pointee type, address space]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000779 Code = bitc::TYPE_CODE_POINTER;
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000780 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
Christopher Lamb25f50762007-12-12 08:44:39 +0000781 unsigned AddressSpace = PTy->getAddressSpace();
782 TypeVals.push_back(AddressSpace);
783 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000784 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000785 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000786 case Type::FunctionTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000787 FunctionType *FT = cast<FunctionType>(T);
Chad Rosier95898722011-11-03 00:14:01 +0000788 // FUNCTION: [isvararg, retty, paramty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000789 Code = bitc::TYPE_CODE_FUNCTION;
790 TypeVals.push_back(FT->isVarArg());
791 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000792 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
793 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
Chris Lattnerccee7062007-05-05 06:30:12 +0000794 AbbrevToUse = FunctionAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000795 break;
796 }
797 case Type::StructTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000798 StructType *ST = cast<StructType>(T);
Chris Lattnerccee7062007-05-05 06:30:12 +0000799 // STRUCT: [ispacked, eltty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000800 TypeVals.push_back(ST->isPacked());
Chris Lattnere14cb882007-05-04 19:11:41 +0000801 // Output all of the element types.
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000802 for (StructType::element_iterator I = ST->element_begin(),
803 E = ST->element_end(); I != E; ++I)
804 TypeVals.push_back(VE.getTypeID(*I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000805
Chris Lattner335d3992011-08-12 18:06:37 +0000806 if (ST->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000807 Code = bitc::TYPE_CODE_STRUCT_ANON;
808 AbbrevToUse = StructAnonAbbrev;
809 } else {
810 if (ST->isOpaque()) {
811 Code = bitc::TYPE_CODE_OPAQUE;
812 } else {
813 Code = bitc::TYPE_CODE_STRUCT_NAMED;
814 AbbrevToUse = StructNamedAbbrev;
815 }
816
817 // Emit the name if it is present.
818 if (!ST->getName().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000819 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
Teresa Johnson37687f32016-04-23 04:30:47 +0000820 StructNameAbbrev);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000821 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000822 break;
823 }
824 case Type::ArrayTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000825 ArrayType *AT = cast<ArrayType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000826 // ARRAY: [numelts, eltty]
827 Code = bitc::TYPE_CODE_ARRAY;
828 TypeVals.push_back(AT->getNumElements());
829 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
Chris Lattnerccee7062007-05-05 06:30:12 +0000830 AbbrevToUse = ArrayAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000831 break;
832 }
833 case Type::VectorTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000834 VectorType *VT = cast<VectorType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000835 // VECTOR [numelts, eltty]
836 Code = bitc::TYPE_CODE_VECTOR;
837 TypeVals.push_back(VT->getNumElements());
838 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
839 break;
840 }
841 }
842
843 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000844 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000845 TypeVals.clear();
846 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000847
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000848 Stream.ExitBlock();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000849}
850
Teresa Johnson5e22e442016-02-06 16:07:35 +0000851static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
852 switch (Linkage) {
Rafael Espindola261d25b2015-01-08 16:25:01 +0000853 case GlobalValue::ExternalLinkage:
854 return 0;
855 case GlobalValue::WeakAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000856 return 16;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000857 case GlobalValue::AppendingLinkage:
858 return 2;
859 case GlobalValue::InternalLinkage:
860 return 3;
861 case GlobalValue::LinkOnceAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000862 return 18;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000863 case GlobalValue::ExternalWeakLinkage:
864 return 7;
865 case GlobalValue::CommonLinkage:
866 return 8;
867 case GlobalValue::PrivateLinkage:
868 return 9;
869 case GlobalValue::WeakODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000870 return 17;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000871 case GlobalValue::LinkOnceODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000872 return 19;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000873 case GlobalValue::AvailableExternallyLinkage:
874 return 12;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000875 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000876 llvm_unreachable("Invalid linkage");
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000877}
878
Teresa Johnson5e22e442016-02-06 16:07:35 +0000879static unsigned getEncodedLinkage(const GlobalValue &GV) {
880 return getEncodedLinkage(GV.getLinkage());
881}
882
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000883// Decode the flags for GlobalValue in the summary
884static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
885 uint64_t RawFlags = 0;
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000886
Mehdi Amini1380edf2017-02-03 07:41:43 +0000887 RawFlags |= Flags.NotEligibleToImport; // bool
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000888 RawFlags |= (Flags.Live << 1);
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000889 // Linkage don't need to be remapped at that time for the summary. Any future
890 // change to the getEncodedLinkage() function will need to be taken into
891 // account here as well.
Mehdi Amini1380edf2017-02-03 07:41:43 +0000892 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
893
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000894 return RawFlags;
895}
896
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000897static unsigned getEncodedVisibility(const GlobalValue &GV) {
898 switch (GV.getVisibility()) {
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000899 case GlobalValue::DefaultVisibility: return 0;
900 case GlobalValue::HiddenVisibility: return 1;
901 case GlobalValue::ProtectedVisibility: return 2;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000902 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000903 llvm_unreachable("Invalid visibility");
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000904}
905
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000906static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
907 switch (GV.getDLLStorageClass()) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000908 case GlobalValue::DefaultStorageClass: return 0;
909 case GlobalValue::DLLImportStorageClass: return 1;
910 case GlobalValue::DLLExportStorageClass: return 2;
911 }
912 llvm_unreachable("Invalid DLL storage class");
913}
914
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000915static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000916 switch (GV.getThreadLocalMode()) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000917 case GlobalVariable::NotThreadLocal: return 0;
918 case GlobalVariable::GeneralDynamicTLSModel: return 1;
919 case GlobalVariable::LocalDynamicTLSModel: return 2;
920 case GlobalVariable::InitialExecTLSModel: return 3;
921 case GlobalVariable::LocalExecTLSModel: return 4;
922 }
923 llvm_unreachable("Invalid TLS model");
924}
925
David Majnemerdad0a642014-06-27 18:19:56 +0000926static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
927 switch (C.getSelectionKind()) {
928 case Comdat::Any:
929 return bitc::COMDAT_SELECTION_KIND_ANY;
930 case Comdat::ExactMatch:
931 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
932 case Comdat::Largest:
933 return bitc::COMDAT_SELECTION_KIND_LARGEST;
934 case Comdat::NoDuplicates:
935 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
936 case Comdat::SameSize:
937 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
938 }
939 llvm_unreachable("Invalid selection kind");
940}
941
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000942static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
943 switch (GV.getUnnamedAddr()) {
944 case GlobalValue::UnnamedAddr::None: return 0;
945 case GlobalValue::UnnamedAddr::Local: return 2;
946 case GlobalValue::UnnamedAddr::Global: return 1;
947 }
948 llvm_unreachable("Invalid unnamed_addr");
949}
950
Peter Collingbournec8556152017-07-06 17:56:01 +0000951size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
952 if (GenerateHash)
953 Hasher.update(Str);
954 return StrtabBuilder.add(Str);
955}
956
Teresa Johnson37687f32016-04-23 04:30:47 +0000957void ModuleBitcodeWriter::writeComdats() {
David Majnemer90a021f2016-03-13 08:01:03 +0000958 SmallVector<unsigned, 64> Vals;
David Majnemerdad0a642014-06-27 18:19:56 +0000959 for (const Comdat *C : VE.getComdats()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000960 // COMDAT: [strtab offset, strtab size, selection_kind]
Peter Collingbournec8556152017-07-06 17:56:01 +0000961 Vals.push_back(addToStrtab(C->getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000962 Vals.push_back(C->getName().size());
David Majnemerdad0a642014-06-27 18:19:56 +0000963 Vals.push_back(getEncodedComdatSelectionKind(*C));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000964 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
David Majnemerdad0a642014-06-27 18:19:56 +0000965 Vals.clear();
966 }
967}
968
Teresa Johnsonff642b92015-09-17 20:12:00 +0000969/// Write a record that will eventually hold the word offset of the
970/// module-level VST. For now the offset is 0, which will be backpatched
Teresa Johnson37687f32016-04-23 04:30:47 +0000971/// after the real VST is written. Saves the bit offset to backpatch.
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000972void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
Teresa Johnsonff642b92015-09-17 20:12:00 +0000973 // Write a placeholder value in for the offset of the real VST,
974 // which is written after the function blocks so that it can include
975 // the offset of each function. The placeholder offset will be
976 // updated when the real VST is written.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000977 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnsonff642b92015-09-17 20:12:00 +0000978 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
979 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
980 // hold the real VST offset. Must use fixed instead of VBR as we don't
981 // know how many VBR chunks to reserve ahead of time.
982 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000983 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnsonff642b92015-09-17 20:12:00 +0000984
985 // Emit the placeholder
986 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000987 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
Teresa Johnsonff642b92015-09-17 20:12:00 +0000988
Teresa Johnson37687f32016-04-23 04:30:47 +0000989 // Compute and save the bit offset to the placeholder, which will be
Teresa Johnsonff642b92015-09-17 20:12:00 +0000990 // patched when the real VST is written. We can simply subtract the 32-bit
991 // fixed size from the current bit number to get the location to backpatch.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000992 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
Teresa Johnsonff642b92015-09-17 20:12:00 +0000993}
994
Teresa Johnsone1164de2016-02-10 21:55:02 +0000995enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
996
997/// Determine the encoding to use for the given string name and length.
David Blaikieb6b42e02017-06-02 17:24:26 +0000998static StringEncoding getStringEncoding(StringRef Str) {
Teresa Johnsone1164de2016-02-10 21:55:02 +0000999 bool isChar6 = true;
David Blaikieb6b42e02017-06-02 17:24:26 +00001000 for (char C : Str) {
Teresa Johnsone1164de2016-02-10 21:55:02 +00001001 if (isChar6)
David Blaikieb6b42e02017-06-02 17:24:26 +00001002 isChar6 = BitCodeAbbrevOp::isChar6(C);
1003 if ((unsigned char)C & 128)
Teresa Johnsone1164de2016-02-10 21:55:02 +00001004 // don't bother scanning the rest.
1005 return SE_Fixed8;
1006 }
1007 if (isChar6)
1008 return SE_Char6;
David Blaikieb6b42e02017-06-02 17:24:26 +00001009 return SE_Fixed7;
Teresa Johnsone1164de2016-02-10 21:55:02 +00001010}
1011
Teresa Johnsonff642b92015-09-17 20:12:00 +00001012/// Emit top-level description of module, including target triple, inline asm,
1013/// descriptors for global variables, and function prototype info.
1014/// Returns the bit offset to backpatch with the location of the real VST.
Teresa Johnson37687f32016-04-23 04:30:47 +00001015void ModuleBitcodeWriter::writeModuleInfo() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001016 // Emit various pieces of data attached to a module.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001017 if (!M.getTargetTriple().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001018 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001019 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001020 const std::string &DL = M.getDataLayoutStr();
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001021 if (!DL.empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001022 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001023 if (!M.getModuleInlineAsm().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001024 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001025 0 /*TODO*/);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001026
Gordon Henriksend930f912008-08-17 18:44:35 +00001027 // Emit information about sections and GC, computing how many there are. Also
1028 // compute the maximum alignment value.
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001029 std::map<std::string, unsigned> SectionMap;
Gordon Henriksend930f912008-08-17 18:44:35 +00001030 std::map<std::string, unsigned> GCMap;
Chris Lattner4b00d922007-04-23 16:04:05 +00001031 unsigned MaxAlignment = 0;
Chris Lattnerb5491372007-04-23 18:58:34 +00001032 unsigned MaxGlobalType = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001033 for (const GlobalValue &GV : M.globals()) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001034 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
David Blaikie1a848da2015-04-27 19:58:56 +00001035 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001036 if (GV.hasSection()) {
Chad Rosier75ec09c2011-08-12 16:45:18 +00001037 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001038 unsigned &Entry = SectionMap[GV.getSection()];
Chad Rosier75ec09c2011-08-12 16:45:18 +00001039 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001040 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001041 0 /*TODO*/);
Chad Rosier75ec09c2011-08-12 16:45:18 +00001042 Entry = SectionMap.size();
1043 }
1044 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001045 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001046 for (const Function &F : M) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001047 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
1048 if (F.hasSection()) {
Gordon Henriksen71183b62007-12-10 03:18:06 +00001049 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001050 unsigned &Entry = SectionMap[F.getSection()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001051 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001052 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001053 0 /*TODO*/);
Gordon Henriksen71183b62007-12-10 03:18:06 +00001054 Entry = SectionMap.size();
1055 }
1056 }
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001057 if (F.hasGC()) {
Gordon Henriksend930f912008-08-17 18:44:35 +00001058 // Same for GC names.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001059 unsigned &Entry = GCMap[F.getGC()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001060 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001061 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1062 0 /*TODO*/);
Gordon Henriksend930f912008-08-17 18:44:35 +00001063 Entry = GCMap.size();
Gordon Henriksen71183b62007-12-10 03:18:06 +00001064 }
1065 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001066 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001067
Chris Lattner4b00d922007-04-23 16:04:05 +00001068 // Emit abbrev for globals, now that we know # sections and max alignment.
1069 unsigned SimpleGVarAbbrev = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001070 if (!M.global_empty()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001071 // Add an abbrev for common globals with no visibility or thread localness.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001072 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner4b00d922007-04-23 16:04:05 +00001073 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001074 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1075 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Chris Lattner2eae59f2007-05-04 20:34:50 +00001076 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001077 Log2_32_Ceil(MaxGlobalType+1)));
David Blaikie1a848da2015-04-27 19:58:56 +00001078 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1079 //| explicitType << 1
1080 //| constant
1081 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1082 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1083 if (MaxAlignment == 0) // Alignment.
Chris Lattner4b00d922007-04-23 16:04:05 +00001084 Abbv->Add(BitCodeAbbrevOp(0));
1085 else {
1086 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
Chris Lattner2eae59f2007-05-04 20:34:50 +00001087 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001088 Log2_32_Ceil(MaxEncAlignment+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001089 }
1090 if (SectionMap.empty()) // Section.
1091 Abbv->Add(BitCodeAbbrevOp(0));
1092 else
Chris Lattner2eae59f2007-05-04 20:34:50 +00001093 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattner1e50c292007-04-24 03:29:47 +00001094 Log2_32_Ceil(SectionMap.size()+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001095 // Don't bother emitting vis + thread local.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001096 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Chris Lattner4b00d922007-04-23 16:04:05 +00001097 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001098
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001099 SmallVector<unsigned, 64> Vals;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001100 // Emit the module's source file name.
1101 {
David Blaikieb6b42e02017-06-02 17:24:26 +00001102 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001103 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1104 if (Bits == SE_Char6)
1105 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1106 else if (Bits == SE_Fixed7)
1107 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1108
1109 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1110 auto Abbv = std::make_shared<BitCodeAbbrev>();
1111 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1112 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1113 Abbv->Add(AbbrevOpToUse);
1114 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1115
1116 for (const auto P : M.getSourceFileName())
1117 Vals.push_back((unsigned char)P);
1118
1119 // Emit the finished record.
1120 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1121 Vals.clear();
1122 }
1123
1124 // Emit the global variable information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001125 for (const GlobalVariable &GV : M.globals()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001126 unsigned AbbrevToUse = 0;
1127
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001128 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00001129 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00001130 // unnamed_addr, externally_initialized, dllstorageclass,
Javed Absarf3d79042017-05-11 12:28:08 +00001131 // comdat, attributes]
Peter Collingbournec8556152017-07-06 17:56:01 +00001132 Vals.push_back(addToStrtab(GV.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001133 Vals.push_back(GV.getName().size());
David Blaikie1a848da2015-04-27 19:58:56 +00001134 Vals.push_back(VE.getTypeID(GV.getValueType()));
1135 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001136 Vals.push_back(GV.isDeclaration() ? 0 :
1137 (VE.getValueID(GV.getInitializer()) + 1));
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001138 Vals.push_back(getEncodedLinkage(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001139 Vals.push_back(Log2_32(GV.getAlignment())+1);
1140 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
1141 if (GV.isThreadLocal() ||
1142 GV.getVisibility() != GlobalValue::DefaultVisibility ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001143 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1144 GV.isExternallyInitialized() ||
David Majnemerdad0a642014-06-27 18:19:56 +00001145 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
Javed Absarf3d79042017-05-11 12:28:08 +00001146 GV.hasComdat() ||
1147 GV.hasAttributes()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001148 Vals.push_back(getEncodedVisibility(GV));
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001149 Vals.push_back(getEncodedThreadLocalMode(GV));
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001150 Vals.push_back(getEncodedUnnamedAddr(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001151 Vals.push_back(GV.isExternallyInitialized());
Nico Rieck7157bb72014-01-14 15:22:47 +00001152 Vals.push_back(getEncodedDLLStorageClass(GV));
David Majnemerdad0a642014-06-27 18:19:56 +00001153 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
Javed Absarf3d79042017-05-11 12:28:08 +00001154
1155 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1156 Vals.push_back(VE.getAttributeListID(AL));
Chris Lattner4b00d922007-04-23 16:04:05 +00001157 } else {
1158 AbbrevToUse = SimpleGVarAbbrev;
1159 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001160
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001161 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001162 Vals.clear();
1163 }
1164
1165 // Emit the function proto information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001166 for (const Function &F : M) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001167 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1168 // linkage, paramattrs, alignment, section, visibility, gc,
1169 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1170 // prefixdata, personalityfn]
Peter Collingbournec8556152017-07-06 17:56:01 +00001171 Vals.push_back(addToStrtab(F.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001172 Vals.push_back(F.getName().size());
David Blaikie561a1572015-04-17 16:28:26 +00001173 Vals.push_back(VE.getTypeID(F.getFunctionType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001174 Vals.push_back(F.getCallingConv());
1175 Vals.push_back(F.isDeclaration());
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001176 Vals.push_back(getEncodedLinkage(F));
Reid Klecknerb4a2d182017-04-24 20:38:30 +00001177 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001178 Vals.push_back(Log2_32(F.getAlignment())+1);
1179 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001180 Vals.push_back(getEncodedVisibility(F));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001181 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001182 Vals.push_back(getEncodedUnnamedAddr(F));
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001183 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1184 : 0);
Nico Rieck7157bb72014-01-14 15:22:47 +00001185 Vals.push_back(getEncodedDLLStorageClass(F));
David Majnemerdad0a642014-06-27 18:19:56 +00001186 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001187 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1188 : 0);
David Majnemer7fddecc2015-06-17 20:52:32 +00001189 Vals.push_back(
1190 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001191
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001192 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001193 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001194 Vals.clear();
1195 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001196
Chris Lattner44c17072007-04-26 02:46:40 +00001197 // Emit the alias information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001198 for (const GlobalAlias &A : M.aliases()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001199 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1200 // visibility, dllstorageclass, threadlocal, unnamed_addr]
Peter Collingbournec8556152017-07-06 17:56:01 +00001201 Vals.push_back(addToStrtab(A.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001202 Vals.push_back(A.getName().size());
David Blaikie6a51dbd2015-09-17 22:18:59 +00001203 Vals.push_back(VE.getTypeID(A.getValueType()));
1204 Vals.push_back(A.getType()->getAddressSpace());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001205 Vals.push_back(VE.getValueID(A.getAliasee()));
1206 Vals.push_back(getEncodedLinkage(A));
1207 Vals.push_back(getEncodedVisibility(A));
1208 Vals.push_back(getEncodedDLLStorageClass(A));
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001209 Vals.push_back(getEncodedThreadLocalMode(A));
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001210 Vals.push_back(getEncodedUnnamedAddr(A));
Chris Lattner44c17072007-04-26 02:46:40 +00001211 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001212 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
Chris Lattner44c17072007-04-26 02:46:40 +00001213 Vals.clear();
1214 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001215
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001216 // Emit the ifunc information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001217 for (const GlobalIFunc &I : M.ifuncs()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001218 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1219 // val#, linkage, visibility]
Peter Collingbournec8556152017-07-06 17:56:01 +00001220 Vals.push_back(addToStrtab(I.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001221 Vals.push_back(I.getName().size());
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001222 Vals.push_back(VE.getTypeID(I.getValueType()));
1223 Vals.push_back(I.getType()->getAddressSpace());
1224 Vals.push_back(VE.getValueID(I.getResolver()));
1225 Vals.push_back(getEncodedLinkage(I));
1226 Vals.push_back(getEncodedVisibility(I));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001227 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001228 Vals.clear();
1229 }
1230
Teresa Johnson37687f32016-04-23 04:30:47 +00001231 writeValueSymbolTableForwardDecl();
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001232}
1233
Teresa Johnson37687f32016-04-23 04:30:47 +00001234static uint64_t getOptimizationFlags(const Value *V) {
Dan Gohman0ebd6962009-07-20 21:19:07 +00001235 uint64_t Flags = 0;
1236
Sanjay Patelc00017d2014-10-15 17:45:13 +00001237 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
Dan Gohman16f54152009-08-20 17:11:38 +00001238 if (OBO->hasNoSignedWrap())
1239 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1240 if (OBO->hasNoUnsignedWrap())
1241 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001242 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
Chris Lattner35315d02011-02-06 21:44:57 +00001243 if (PEO->isExact())
1244 Flags |= 1 << bitc::PEO_EXACT;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001245 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001246 if (FPMO->hasUnsafeAlgebra())
Michael Ilseman65f14352012-12-09 21:12:04 +00001247 Flags |= FastMathFlags::UnsafeAlgebra;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001248 if (FPMO->hasNoNaNs())
Michael Ilseman65f14352012-12-09 21:12:04 +00001249 Flags |= FastMathFlags::NoNaNs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001250 if (FPMO->hasNoInfs())
Michael Ilseman65f14352012-12-09 21:12:04 +00001251 Flags |= FastMathFlags::NoInfs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001252 if (FPMO->hasNoSignedZeros())
Michael Ilseman65f14352012-12-09 21:12:04 +00001253 Flags |= FastMathFlags::NoSignedZeros;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001254 if (FPMO->hasAllowReciprocal())
Michael Ilseman65f14352012-12-09 21:12:04 +00001255 Flags |= FastMathFlags::AllowReciprocal;
Adam Nemetcd847a82017-03-28 20:11:52 +00001256 if (FPMO->hasAllowContract())
1257 Flags |= FastMathFlags::AllowContract;
Dan Gohman0ebd6962009-07-20 21:19:07 +00001258 }
1259
1260 return Flags;
1261}
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001262
Teresa Johnson37687f32016-04-23 04:30:47 +00001263void ModuleBitcodeWriter::writeValueAsMetadata(
1264 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001265 // Mimic an MDNode with a value as one operand.
1266 Value *V = MD->getValue();
1267 Record.push_back(VE.getTypeID(V->getType()));
1268 Record.push_back(VE.getValueID(V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001269 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001270 Record.clear();
1271}
1272
Teresa Johnson37687f32016-04-23 04:30:47 +00001273void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1274 SmallVectorImpl<uint64_t> &Record,
1275 unsigned Abbrev) {
Chris Lattner9b493022009-12-31 01:22:29 +00001276 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001277 Metadata *MD = N->getOperand(i);
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001278 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1279 "Unexpected function-local metadata");
1280 Record.push_back(VE.getMetadataOrNullID(MD));
Devang Patel8cca7b42009-08-04 05:01:35 +00001281 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001282 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1283 : bitc::METADATA_NODE,
1284 Record, Abbrev);
Devang Patel8cca7b42009-08-04 05:01:35 +00001285 Record.clear();
1286}
Devang Patele059ba6e2009-07-23 01:07:34 +00001287
Teresa Johnson37687f32016-04-23 04:30:47 +00001288unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001289 // Assume the column is usually under 128, and always output the inlined-at
1290 // location (it's never more expensive than building an array size 1).
David Blaikie7ad9dc12017-01-04 22:36:33 +00001291 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001292 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1293 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1294 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1295 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1296 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1297 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001298 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001299}
1300
Teresa Johnson37687f32016-04-23 04:30:47 +00001301void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1302 SmallVectorImpl<uint64_t> &Record,
1303 unsigned &Abbrev) {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001304 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001305 Abbrev = createDILocationAbbrev();
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001306
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001307 Record.push_back(N->isDistinct());
1308 Record.push_back(N->getLine());
1309 Record.push_back(N->getColumn());
1310 Record.push_back(VE.getMetadataID(N->getScope()));
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001311 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001312
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001313 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001314 Record.clear();
1315}
1316
Teresa Johnson37687f32016-04-23 04:30:47 +00001317unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001318 // Assume the column is usually under 128, and always output the inlined-at
1319 // location (it's never more expensive than building an array size 1).
David Blaikie7ad9dc12017-01-04 22:36:33 +00001320 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001321 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1322 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1323 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1324 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1325 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1326 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1327 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001328 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001329}
1330
Teresa Johnson37687f32016-04-23 04:30:47 +00001331void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1332 SmallVectorImpl<uint64_t> &Record,
1333 unsigned &Abbrev) {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001334 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001335 Abbrev = createGenericDINodeAbbrev();
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001336
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001337 Record.push_back(N->isDistinct());
1338 Record.push_back(N->getTag());
1339 Record.push_back(0); // Per-tag version field; unused for now.
1340
1341 for (auto &I : N->operands())
1342 Record.push_back(VE.getMetadataOrNullID(I));
1343
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001344 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001345 Record.clear();
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001346}
1347
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001348static uint64_t rotateSign(int64_t I) {
1349 uint64_t U = I;
1350 return I < 0 ? ~(U << 1) : U << 1;
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001351}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001352
Teresa Johnson37687f32016-04-23 04:30:47 +00001353void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1354 SmallVectorImpl<uint64_t> &Record,
1355 unsigned Abbrev) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001356 Record.push_back(N->isDistinct());
1357 Record.push_back(N->getCount());
Duncan P. N. Exon Smith5dcf6212015-04-07 00:39:59 +00001358 Record.push_back(rotateSign(N->getLowerBound()));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001359
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001360 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001361 Record.clear();
1362}
1363
Teresa Johnson37687f32016-04-23 04:30:47 +00001364void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1365 SmallVectorImpl<uint64_t> &Record,
1366 unsigned Abbrev) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001367 Record.push_back(N->isDistinct());
1368 Record.push_back(rotateSign(N->getValue()));
1369 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1370
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001371 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001372 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001373}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001374
Teresa Johnson37687f32016-04-23 04:30:47 +00001375void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1376 SmallVectorImpl<uint64_t> &Record,
1377 unsigned Abbrev) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001378 Record.push_back(N->isDistinct());
1379 Record.push_back(N->getTag());
1380 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1381 Record.push_back(N->getSizeInBits());
1382 Record.push_back(N->getAlignInBits());
1383 Record.push_back(N->getEncoding());
1384
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001385 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001386 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001387}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001388
Teresa Johnson37687f32016-04-23 04:30:47 +00001389void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1390 SmallVectorImpl<uint64_t> &Record,
1391 unsigned Abbrev) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001392 Record.push_back(N->isDistinct());
1393 Record.push_back(N->getTag());
1394 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1395 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1396 Record.push_back(N->getLine());
1397 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001398 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001399 Record.push_back(N->getSizeInBits());
1400 Record.push_back(N->getAlignInBits());
1401 Record.push_back(N->getOffsetInBits());
1402 Record.push_back(N->getFlags());
1403 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1404
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00001405 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1406 // that there is no DWARF address space associated with DIDerivedType.
1407 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1408 Record.push_back(*DWARFAddressSpace + 1);
1409 else
1410 Record.push_back(0);
1411
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001412 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001413 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001414}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001415
Teresa Johnson37687f32016-04-23 04:30:47 +00001416void ModuleBitcodeWriter::writeDICompositeType(
1417 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1418 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001419 const unsigned IsNotUsedInOldTypeRef = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001420 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001421 Record.push_back(N->getTag());
1422 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1423 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1424 Record.push_back(N->getLine());
1425 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1426 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1427 Record.push_back(N->getSizeInBits());
1428 Record.push_back(N->getAlignInBits());
1429 Record.push_back(N->getOffsetInBits());
1430 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001431 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001432 Record.push_back(N->getRuntimeLang());
1433 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001434 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001435 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1436
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001437 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001438 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001439}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001440
Teresa Johnson37687f32016-04-23 04:30:47 +00001441void ModuleBitcodeWriter::writeDISubroutineType(
1442 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1443 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001444 const unsigned HasNoOldTypeRefs = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001445 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001446 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001447 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001448 Record.push_back(N->getCC());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001449
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001450 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001451 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001452}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001453
Teresa Johnson37687f32016-04-23 04:30:47 +00001454void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1455 SmallVectorImpl<uint64_t> &Record,
1456 unsigned Abbrev) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001457 Record.push_back(N->isDistinct());
1458 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1459 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
Amjad Aboud7faeecc2016-12-25 10:12:09 +00001460 Record.push_back(N->getChecksumKind());
1461 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001462
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001463 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001464 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001465}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001466
Teresa Johnson37687f32016-04-23 04:30:47 +00001467void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1468 SmallVectorImpl<uint64_t> &Record,
1469 unsigned Abbrev) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00001470 assert(N->isDistinct() && "Expected distinct compile units");
1471 Record.push_back(/* IsDistinct */ true);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001472 Record.push_back(N->getSourceLanguage());
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001473 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001474 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1475 Record.push_back(N->isOptimized());
1476 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1477 Record.push_back(N->getRuntimeVersion());
1478 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1479 Record.push_back(N->getEmissionKind());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001480 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1481 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
Adrian Prantl75819ae2016-04-15 15:57:41 +00001482 Record.push_back(/* subprograms */ 0);
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001483 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1484 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
Adrian Prantl1f599f92015-05-21 20:37:30 +00001485 Record.push_back(N->getDWOId());
Amjad Abouda9bcf162015-12-10 12:56:35 +00001486 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
David Blaikiea01f2952016-08-24 18:29:49 +00001487 Record.push_back(N->getSplitDebugInlining());
Dehao Chen0944a8c2017-02-01 22:45:09 +00001488 Record.push_back(N->getDebugInfoForProfiling());
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001489
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001490 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001491 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001492}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001493
Teresa Johnson37687f32016-04-23 04:30:47 +00001494void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1495 SmallVectorImpl<uint64_t> &Record,
1496 unsigned Abbrev) {
Adrian Prantl85338cb2016-05-06 22:53:06 +00001497 uint64_t HasUnitFlag = 1 << 1;
1498 Record.push_back(N->isDistinct() | HasUnitFlag);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001499 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1500 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1501 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1502 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1503 Record.push_back(N->getLine());
1504 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1505 Record.push_back(N->isLocalToUnit());
1506 Record.push_back(N->isDefinition());
1507 Record.push_back(N->getScopeLine());
1508 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1509 Record.push_back(N->getVirtuality());
1510 Record.push_back(N->getVirtualIndex());
1511 Record.push_back(N->getFlags());
1512 Record.push_back(N->isOptimized());
Adrian Prantl75819ae2016-04-15 15:57:41 +00001513 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001514 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001515 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001516 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001517 Record.push_back(N->getThisAdjustment());
Adrian Prantl1d12b882017-04-26 22:56:44 +00001518 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001519
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001520 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001521 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001522}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001523
Teresa Johnson37687f32016-04-23 04:30:47 +00001524void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1525 SmallVectorImpl<uint64_t> &Record,
1526 unsigned Abbrev) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001527 Record.push_back(N->isDistinct());
1528 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1529 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1530 Record.push_back(N->getLine());
1531 Record.push_back(N->getColumn());
1532
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001533 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001534 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001535}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001536
Teresa Johnson37687f32016-04-23 04:30:47 +00001537void ModuleBitcodeWriter::writeDILexicalBlockFile(
1538 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1539 unsigned Abbrev) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001540 Record.push_back(N->isDistinct());
1541 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1542 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1543 Record.push_back(N->getDiscriminator());
1544
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001545 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001546 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001547}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001548
Teresa Johnson37687f32016-04-23 04:30:47 +00001549void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1550 SmallVectorImpl<uint64_t> &Record,
1551 unsigned Abbrev) {
Adrian Prantldbfda632016-11-03 19:42:02 +00001552 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001553 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001554 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001555
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001556 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001557 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001558}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001559
Teresa Johnson37687f32016-04-23 04:30:47 +00001560void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1561 SmallVectorImpl<uint64_t> &Record,
1562 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001563 Record.push_back(N->isDistinct());
1564 Record.push_back(N->getMacinfoType());
1565 Record.push_back(N->getLine());
1566 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1567 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1568
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001569 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001570 Record.clear();
1571}
1572
Teresa Johnson37687f32016-04-23 04:30:47 +00001573void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1574 SmallVectorImpl<uint64_t> &Record,
1575 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001576 Record.push_back(N->isDistinct());
1577 Record.push_back(N->getMacinfoType());
1578 Record.push_back(N->getLine());
1579 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1580 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1581
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001582 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001583 Record.clear();
1584}
1585
Teresa Johnson37687f32016-04-23 04:30:47 +00001586void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1587 SmallVectorImpl<uint64_t> &Record,
1588 unsigned Abbrev) {
Adrian Prantlab1243f2015-06-29 23:03:47 +00001589 Record.push_back(N->isDistinct());
1590 for (auto &I : N->operands())
1591 Record.push_back(VE.getMetadataOrNullID(I));
1592
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001593 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
Adrian Prantlab1243f2015-06-29 23:03:47 +00001594 Record.clear();
1595}
1596
Teresa Johnson37687f32016-04-23 04:30:47 +00001597void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1598 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1599 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001600 Record.push_back(N->isDistinct());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001601 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1602 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1603
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001604 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001605 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001606}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001607
Teresa Johnson37687f32016-04-23 04:30:47 +00001608void ModuleBitcodeWriter::writeDITemplateValueParameter(
1609 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1610 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001611 Record.push_back(N->isDistinct());
1612 Record.push_back(N->getTag());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001613 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1614 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1615 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1616
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001617 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001618 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001619}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001620
Teresa Johnson37687f32016-04-23 04:30:47 +00001621void ModuleBitcodeWriter::writeDIGlobalVariable(
1622 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1623 unsigned Abbrev) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001624 const uint64_t Version = 1 << 1;
1625 Record.push_back((uint64_t)N->isDistinct() | Version);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001626 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1627 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1628 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1629 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1630 Record.push_back(N->getLine());
1631 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1632 Record.push_back(N->isLocalToUnit());
1633 Record.push_back(N->isDefinition());
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001634 Record.push_back(/* expr */ 0);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001635 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
Victor Leschuk2ede1262016-10-20 00:13:12 +00001636 Record.push_back(N->getAlignInBits());
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001637
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001638 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001639 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001640}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001641
Teresa Johnson37687f32016-04-23 04:30:47 +00001642void ModuleBitcodeWriter::writeDILocalVariable(
1643 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1644 unsigned Abbrev) {
Victor Leschuk2ede1262016-10-20 00:13:12 +00001645 // In order to support all possible bitcode formats in BitcodeReader we need
Simon Pilgrim25059362016-10-20 10:42:14 +00001646 // to distinguish the following cases:
Victor Leschuk2ede1262016-10-20 00:13:12 +00001647 // 1) Record has no artificial tag (Record[1]),
1648 // has no obsolete inlinedAt field (Record[9]).
1649 // In this case Record size will be 8, HasAlignment flag is false.
1650 // 2) Record has artificial tag (Record[1]),
1651 // has no obsolete inlignedAt field (Record[9]).
1652 // In this case Record size will be 9, HasAlignment flag is false.
1653 // 3) Record has both artificial tag (Record[1]) and
1654 // obsolete inlignedAt field (Record[9]).
1655 // In this case Record size will be 10, HasAlignment flag is false.
1656 // 4) Record has neither artificial tag, nor inlignedAt field, but
1657 // HasAlignment flag is true and Record[8] contains alignment value.
1658 const uint64_t HasAlignmentFlag = 1 << 1;
Simon Pilgrim071da462016-10-20 10:37:58 +00001659 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001660 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1661 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1662 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1663 Record.push_back(N->getLine());
1664 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1665 Record.push_back(N->getArg());
1666 Record.push_back(N->getFlags());
Victor Leschuk2ede1262016-10-20 00:13:12 +00001667 Record.push_back(N->getAlignInBits());
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001668
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001669 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001670 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001671}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001672
Teresa Johnson37687f32016-04-23 04:30:47 +00001673void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1674 SmallVectorImpl<uint64_t> &Record,
1675 unsigned Abbrev) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001676 Record.reserve(N->getElements().size() + 1);
Florian Hahnffc498d2017-06-14 13:14:38 +00001677 const uint64_t Version = 3 << 1;
Adrian Prantl6825fb62017-04-18 01:21:53 +00001678 Record.push_back((uint64_t)N->isDistinct() | Version);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001679 Record.append(N->elements_begin(), N->elements_end());
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001680
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001681 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001682 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001683}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001684
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001685void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1686 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1687 unsigned Abbrev) {
1688 Record.push_back(N->isDistinct());
1689 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1690 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
1691
1692 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1693 Record.clear();
1694}
1695
Teresa Johnson37687f32016-04-23 04:30:47 +00001696void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1697 SmallVectorImpl<uint64_t> &Record,
1698 unsigned Abbrev) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001699 Record.push_back(N->isDistinct());
1700 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1701 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1702 Record.push_back(N->getLine());
1703 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1704 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1705 Record.push_back(N->getAttributes());
1706 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1707
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001708 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001709 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001710}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001711
Teresa Johnson37687f32016-04-23 04:30:47 +00001712void ModuleBitcodeWriter::writeDIImportedEntity(
1713 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1714 unsigned Abbrev) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001715 Record.push_back(N->isDistinct());
1716 Record.push_back(N->getTag());
1717 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1718 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1719 Record.push_back(N->getLine());
1720 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1721
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001722 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001723 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001724}
1725
Teresa Johnson37687f32016-04-23 04:30:47 +00001726unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
David Blaikie7ad9dc12017-01-04 22:36:33 +00001727 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001728 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1729 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1730 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001731 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001732}
1733
Teresa Johnson37687f32016-04-23 04:30:47 +00001734void ModuleBitcodeWriter::writeNamedMetadata(
1735 SmallVectorImpl<uint64_t> &Record) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001736 if (M.named_metadata_empty())
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001737 return;
1738
Teresa Johnson37687f32016-04-23 04:30:47 +00001739 unsigned Abbrev = createNamedMetadataAbbrev();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001740 for (const NamedMDNode &NMD : M.named_metadata()) {
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001741 // Write name.
1742 StringRef Str = NMD.getName();
1743 Record.append(Str.bytes_begin(), Str.bytes_end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001744 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001745 Record.clear();
1746
1747 // Write named metadata operands.
1748 for (const MDNode *N : NMD.operands())
1749 Record.push_back(VE.getMetadataID(N));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001750 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001751 Record.clear();
1752 }
1753}
1754
Teresa Johnson37687f32016-04-23 04:30:47 +00001755unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
David Blaikie7ad9dc12017-01-04 22:36:33 +00001756 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001757 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1758 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1759 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1760 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001761 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001762}
1763
1764/// Write out a record for MDString.
1765///
1766/// All the metadata strings in a metadata block are emitted in a single
1767/// record. The sizes and strings themselves are shoved into a blob.
Teresa Johnson37687f32016-04-23 04:30:47 +00001768void ModuleBitcodeWriter::writeMetadataStrings(
1769 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001770 if (Strings.empty())
1771 return;
1772
1773 // Start the record with the number of strings.
1774 Record.push_back(bitc::METADATA_STRINGS);
1775 Record.push_back(Strings.size());
1776
1777 // Emit the sizes of the strings in the blob.
1778 SmallString<256> Blob;
1779 {
1780 BitstreamWriter W(Blob);
1781 for (const Metadata *MD : Strings)
1782 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1783 W.FlushToWord();
1784 }
1785
1786 // Add the offset to the strings to the record.
1787 Record.push_back(Blob.size());
1788
1789 // Add the strings to the blob.
1790 for (const Metadata *MD : Strings)
1791 Blob.append(cast<MDString>(MD)->getString());
1792
1793 // Emit the final record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001794 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001795 Record.clear();
1796}
1797
Mehdi Aminie98f9252016-12-28 22:30:28 +00001798// Generates an enum to use as an index in the Abbrev array of Metadata record.
1799enum MetadataAbbrev : unsigned {
1800#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1801#include "llvm/IR/Metadata.def"
1802 LastPlusOne
1803};
1804
Teresa Johnson37687f32016-04-23 04:30:47 +00001805void ModuleBitcodeWriter::writeMetadataRecords(
Mehdi Aminie98f9252016-12-28 22:30:28 +00001806 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
1807 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001808 if (MDs.empty())
Duncan P. N. Exon Smith2fcf60e2015-01-12 22:30:34 +00001809 return;
1810
Duncan P. N. Exon Smith6b7b6802015-02-04 21:54:12 +00001811 // Initialize MDNode abbreviations.
1812#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1813#include "llvm/IR/Metadata.def"
1814
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001815 for (const Metadata *MD : MDs) {
Mehdi Aminie98f9252016-12-28 22:30:28 +00001816 if (IndexPos)
1817 IndexPos->push_back(Stream.GetCurrentBitNo());
Duncan P. N. Exon Smith73d5aae2015-01-12 22:31:35 +00001818 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
Duncan P. N. Exon Smith79f8d112015-03-17 00:16:35 +00001819 assert(N->isResolved() && "Expected forward references to be resolved");
1820
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001821 switch (N->getMetadataID()) {
1822 default:
1823 llvm_unreachable("Invalid MDNode subclass");
1824#define HANDLE_MDNODE_LEAF(CLASS) \
1825 case Metadata::CLASS##Kind: \
Mehdi Aminie98f9252016-12-28 22:30:28 +00001826 if (MDAbbrevs) \
1827 write##CLASS(cast<CLASS>(N), Record, \
1828 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
1829 else \
1830 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001831 continue;
1832#include "llvm/IR/Metadata.def"
1833 }
Devang Patel8cca7b42009-08-04 05:01:35 +00001834 }
Teresa Johnson37687f32016-04-23 04:30:47 +00001835 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
Devang Patel8cca7b42009-08-04 05:01:35 +00001836 }
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001837}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001838
Teresa Johnson37687f32016-04-23 04:30:47 +00001839void ModuleBitcodeWriter::writeModuleMetadata() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001840 if (!VE.hasMDs() && M.named_metadata_empty())
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001841 return;
1842
Mehdi Aminie98f9252016-12-28 22:30:28 +00001843 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001844 SmallVector<uint64_t, 64> Record;
Mehdi Aminie98f9252016-12-28 22:30:28 +00001845
1846 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1847 // block and load any metadata.
1848 std::vector<unsigned> MDAbbrevs;
1849
1850 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
1851 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
1852 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
1853 createGenericDINodeAbbrev();
1854
David Blaikie7ad9dc12017-01-04 22:36:33 +00001855 auto Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminie98f9252016-12-28 22:30:28 +00001856 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
Mehdi Amini5022bb72016-12-28 23:45:54 +00001857 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1858 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001859 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminie98f9252016-12-28 22:30:28 +00001860
David Blaikie7ad9dc12017-01-04 22:36:33 +00001861 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminie98f9252016-12-28 22:30:28 +00001862 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
1863 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1864 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001865 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminie98f9252016-12-28 22:30:28 +00001866
1867 // Emit MDStrings together upfront.
Teresa Johnson37687f32016-04-23 04:30:47 +00001868 writeMetadataStrings(VE.getMDStrings(), Record);
Mehdi Aminie98f9252016-12-28 22:30:28 +00001869
1870 // We only emit an index for the metadata record if we have more than a given
1871 // (naive) threshold of metadatas, otherwise it is not worth it.
1872 if (VE.getNonMDStrings().size() > IndexThreshold) {
1873 // Write a placeholder value in for the offset of the metadata index,
1874 // which is written after the records, so that it can include
1875 // the offset of each entry. The placeholder offset will be
1876 // updated after all records are emitted.
Mehdi Amini5022bb72016-12-28 23:45:54 +00001877 uint64_t Vals[] = {0, 0};
Mehdi Aminie98f9252016-12-28 22:30:28 +00001878 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
1879 }
1880
1881 // Compute and save the bit offset to the current position, which will be
1882 // patched when we emit the index later. We can simply subtract the 64-bit
1883 // fixed size from the current bit number to get the location to backpatch.
1884 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
1885
1886 // This index will contain the bitpos for each individual record.
1887 std::vector<uint64_t> IndexPos;
1888 IndexPos.reserve(VE.getNonMDStrings().size());
1889
1890 // Write all the records
1891 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
1892
1893 if (VE.getNonMDStrings().size() > IndexThreshold) {
1894 // Now that we have emitted all the records we will emit the index. But
1895 // first
1896 // backpatch the forward reference so that the reader can skip the records
1897 // efficiently.
1898 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
1899 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
1900
1901 // Delta encode the index.
1902 uint64_t PreviousValue = IndexOffsetRecordBitPos;
1903 for (auto &Elt : IndexPos) {
1904 auto EltDelta = Elt - PreviousValue;
1905 PreviousValue = Elt;
1906 Elt = EltDelta;
1907 }
1908 // Emit the index record.
1909 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
1910 IndexPos.clear();
1911 }
1912
1913 // Write the named metadata now.
Teresa Johnson37687f32016-04-23 04:30:47 +00001914 writeNamedMetadata(Record);
Peter Collingbourne21521892016-06-21 23:42:48 +00001915
1916 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
1917 SmallVector<uint64_t, 4> Record;
1918 Record.push_back(VE.getValueID(&GO));
1919 pushGlobalMetadataAttachment(Record, GO);
1920 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
1921 };
1922 for (const Function &F : M)
1923 if (F.isDeclaration() && F.hasMetadata())
1924 AddDeclAttachedMetadata(F);
1925 // FIXME: Only store metadata for declarations here, and move data for global
1926 // variable definitions to a separate block (PR28134).
1927 for (const GlobalVariable &GV : M.globals())
1928 if (GV.hasMetadata())
1929 AddDeclAttachedMetadata(GV);
1930
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001931 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00001932}
1933
Teresa Johnson37687f32016-04-23 04:30:47 +00001934void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
Duncan P. N. Exon Smith93429112016-04-02 15:09:42 +00001935 if (!VE.hasMDs())
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00001936 return;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001937
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001938 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00001939 SmallVector<uint64_t, 64> Record;
Teresa Johnson37687f32016-04-23 04:30:47 +00001940 writeMetadataStrings(VE.getMDStrings(), Record);
1941 writeMetadataRecords(VE.getNonMDStrings(), Record);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001942 Stream.ExitBlock();
Victor Hernandezb00a6be2010-01-13 19:37:33 +00001943}
1944
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001945void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
1946 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
1947 // [n x [id, mdnode]]
1948 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1949 GO.getAllMetadata(MDs);
1950 for (const auto &I : MDs) {
1951 Record.push_back(I.first);
1952 Record.push_back(VE.getMetadataID(I.second));
1953 }
1954}
1955
1956void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001957 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
Chris Lattner07d09ed2010-04-03 02:17:50 +00001958
Devang Patelaf206b82009-09-18 19:26:43 +00001959 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001960
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001961 if (F.hasMetadata()) {
1962 pushGlobalMetadataAttachment(Record, F);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001963 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001964 Record.clear();
1965 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001966
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001967 // Write metadata attachments
1968 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1969 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00001970 for (const BasicBlock &BB : F)
1971 for (const Instruction &I : BB) {
Devang Patel6da5dbf2009-10-22 18:55:16 +00001972 MDs.clear();
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00001973 I.getAllMetadataOtherThanDebugLoc(MDs);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001974
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001975 // If no metadata, ignore instruction.
1976 if (MDs.empty()) continue;
1977
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00001978 Record.push_back(VE.getInstructionID(&I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001979
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001980 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1981 Record.push_back(MDs[i].first);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001982 Record.push_back(VE.getMetadataID(MDs[i].second));
Devang Patelaf206b82009-09-18 19:26:43 +00001983 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001984 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001985 Record.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00001986 }
1987
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001988 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00001989}
1990
Peter Collingbourne21521892016-06-21 23:42:48 +00001991void ModuleBitcodeWriter::writeModuleMetadataKinds() {
Devang Patelaf206b82009-09-18 19:26:43 +00001992 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001993
Devang Patelaf206b82009-09-18 19:26:43 +00001994 // Write metadata kinds
1995 // METADATA_KIND - [n x [id, name]]
Michael Ilseman979dfbb2012-12-03 22:57:47 +00001996 SmallVector<StringRef, 8> Names;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001997 M.getMDKindNames(Names);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001998
Dan Gohman43aa8f02010-07-20 21:42:28 +00001999 if (Names.empty()) return;
Chris Lattnerc9558df2009-12-28 20:10:43 +00002000
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002001 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002002
Dan Gohman43aa8f02010-07-20 21:42:28 +00002003 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
Chris Lattnerc9558df2009-12-28 20:10:43 +00002004 Record.push_back(MDKindID);
2005 StringRef KName = Names[MDKindID];
2006 Record.append(KName.begin(), KName.end());
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002007
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002008 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
Devang Patelaf206b82009-09-18 19:26:43 +00002009 Record.clear();
2010 }
2011
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002012 Stream.ExitBlock();
Devang Patel8cca7b42009-08-04 05:01:35 +00002013}
2014
Teresa Johnson37687f32016-04-23 04:30:47 +00002015void ModuleBitcodeWriter::writeOperandBundleTags() {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002016 // Write metadata kinds
2017 //
2018 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2019 //
2020 // OPERAND_BUNDLE_TAG - [strchr x N]
2021
2022 SmallVector<StringRef, 8> Tags;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002023 M.getOperandBundleTags(Tags);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002024
2025 if (Tags.empty())
2026 return;
2027
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002028 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002029
2030 SmallVector<uint64_t, 64> Record;
2031
2032 for (auto Tag : Tags) {
2033 Record.append(Tag.begin(), Tag.end());
2034
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002035 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002036 Record.clear();
2037 }
2038
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002039 Stream.ExitBlock();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002040}
2041
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002042void ModuleBitcodeWriter::writeSyncScopeNames() {
2043 SmallVector<StringRef, 8> SSNs;
2044 M.getContext().getSyncScopeNames(SSNs);
2045 if (SSNs.empty())
2046 return;
2047
2048 Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
2049
2050 SmallVector<uint64_t, 64> Record;
2051 for (auto SSN : SSNs) {
2052 Record.append(SSN.begin(), SSN.end());
2053 Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2054 Record.clear();
2055 }
2056
2057 Stream.ExitBlock();
2058}
2059
Jan Wen Voungafaced02012-10-11 20:20:40 +00002060static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2061 if ((int64_t)V >= 0)
2062 Vals.push_back(V << 1);
2063 else
2064 Vals.push_back((-V << 1) | 1);
2065}
2066
Teresa Johnson37687f32016-04-23 04:30:47 +00002067void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2068 bool isGlobal) {
Devang Patel8cca7b42009-08-04 05:01:35 +00002069 if (FirstVal == LastVal) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002070
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002071 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
Devang Patel8cca7b42009-08-04 05:01:35 +00002072
2073 unsigned AggregateAbbrev = 0;
2074 unsigned String8Abbrev = 0;
2075 unsigned CString7Abbrev = 0;
2076 unsigned CString6Abbrev = 0;
2077 // If this is a constant pool for the module, emit module-specific abbrevs.
2078 if (isGlobal) {
2079 // Abbrev for CST_CODE_AGGREGATE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002080 auto Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002081 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2082 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2083 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002084 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002085
2086 // Abbrev for CST_CODE_STRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002087 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002088 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2089 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2090 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002091 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002092 // Abbrev for CST_CODE_CSTRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002093 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002094 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2095 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2096 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002097 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002098 // Abbrev for CST_CODE_CSTRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002099 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002100 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2101 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2102 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002103 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002104 }
2105
Devang Patel8cca7b42009-08-04 05:01:35 +00002106 SmallVector<uint64_t, 64> Record;
2107
2108 const ValueEnumerator::ValueList &Vals = VE.getValues();
Craig Topper2617dcc2014-04-15 06:32:26 +00002109 Type *LastTy = nullptr;
Devang Patel8cca7b42009-08-04 05:01:35 +00002110 for (unsigned i = FirstVal; i != LastVal; ++i) {
2111 const Value *V = Vals[i].first;
Chris Lattner52523562007-04-24 00:16:04 +00002112 // If we need to switch types, do so now.
2113 if (V->getType() != LastTy) {
2114 LastTy = V->getType();
2115 Record.push_back(VE.getTypeID(LastTy));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002116 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2117 CONSTANTS_SETTYPE_ABBREV);
Chris Lattner52523562007-04-24 00:16:04 +00002118 Record.clear();
2119 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002120
Chris Lattner52523562007-04-24 00:16:04 +00002121 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
Dale Johannesenfd04c742009-10-13 20:46:56 +00002122 Record.push_back(unsigned(IA->hasSideEffects()) |
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002123 unsigned(IA->isAlignStack()) << 1 |
2124 unsigned(IA->getDialect()&1) << 2);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002125
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002126 // Add the asm string.
2127 const std::string &AsmStr = IA->getAsmString();
2128 Record.push_back(AsmStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002129 Record.append(AsmStr.begin(), AsmStr.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002130
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002131 // Add the constraint string.
2132 const std::string &ConstraintStr = IA->getConstraintString();
2133 Record.push_back(ConstraintStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002134 Record.append(ConstraintStr.begin(), ConstraintStr.end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002135 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002136 Record.clear();
Chris Lattner52523562007-04-24 00:16:04 +00002137 continue;
2138 }
2139 const Constant *C = cast<Constant>(V);
2140 unsigned Code = -1U;
2141 unsigned AbbrevToUse = 0;
2142 if (C->isNullValue()) {
2143 Code = bitc::CST_CODE_NULL;
2144 } else if (isa<UndefValue>(C)) {
2145 Code = bitc::CST_CODE_UNDEF;
2146 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
Bob Wilsone4077362013-09-09 19:14:35 +00002147 if (IV->getBitWidth() <= 64) {
2148 uint64_t V = IV->getSExtValue();
2149 emitSignedInt64(Record, V);
2150 Code = bitc::CST_CODE_INTEGER;
2151 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2152 } else { // Wide integers, > 64 bits in size.
2153 // We have an arbitrary precision integer value to write whose
2154 // bit width is > 64. However, in canonical unsigned integer
2155 // format it is likely that the high bits are going to be zero.
2156 // So, we only write the number of active words.
2157 unsigned NWords = IV->getValue().getActiveWords();
2158 const uint64_t *RawWords = IV->getValue().getRawData();
2159 for (unsigned i = 0; i != NWords; ++i) {
2160 emitSignedInt64(Record, RawWords[i]);
2161 }
2162 Code = bitc::CST_CODE_WIDE_INTEGER;
2163 }
Chris Lattner52523562007-04-24 00:16:04 +00002164 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2165 Code = bitc::CST_CODE_FLOAT;
Chris Lattner229907c2011-07-18 04:54:35 +00002166 Type *Ty = CFP->getType();
Dan Gohman518cda42011-12-17 00:04:22 +00002167 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002168 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
Chris Lattnerfdd87902009-10-05 05:54:46 +00002169 } else if (Ty->isX86_FP80Ty()) {
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002170 // api needed to prevent premature destruction
Dale Johannesen93eefa02009-03-23 21:16:53 +00002171 // bits are not in the same order as a normal i80 APInt, compensate.
Dale Johannesen54306fe2008-10-09 18:53:47 +00002172 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002173 const uint64_t *p = api.getRawData();
Dale Johannesen93eefa02009-03-23 21:16:53 +00002174 Record.push_back((p[1] << 48) | (p[0] >> 16));
2175 Record.push_back(p[0] & 0xffffLL);
Chris Lattnerfdd87902009-10-05 05:54:46 +00002176 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002177 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002178 const uint64_t *p = api.getRawData();
Dale Johannesen245dceb2007-09-11 18:32:33 +00002179 Record.push_back(p[0]);
2180 Record.push_back(p[1]);
Dale Johannesenbdad8092007-08-09 22:51:36 +00002181 } else {
2182 assert (0 && "Unknown FP type!");
Chris Lattner52523562007-04-24 00:16:04 +00002183 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002184 } else if (isa<ConstantDataSequential>(C) &&
2185 cast<ConstantDataSequential>(C)->isString()) {
2186 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2187 // Emit constant strings specially.
2188 unsigned NumElts = Str->getNumElements();
2189 // If this is a null-terminated string, use the denser CSTRING encoding.
2190 if (Str->isCString()) {
2191 Code = bitc::CST_CODE_CSTRING;
2192 --NumElts; // Don't encode the null, which isn't allowed by char6.
2193 } else {
2194 Code = bitc::CST_CODE_STRING;
2195 AbbrevToUse = String8Abbrev;
2196 }
2197 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2198 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2199 for (unsigned i = 0; i != NumElts; ++i) {
2200 unsigned char V = Str->getElementAsInteger(i);
2201 Record.push_back(V);
2202 isCStr7 &= (V & 128) == 0;
2203 if (isCStrChar6)
2204 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2205 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002206
Chris Lattner372dd1e2012-01-30 00:51:16 +00002207 if (isCStrChar6)
2208 AbbrevToUse = CString6Abbrev;
2209 else if (isCStr7)
2210 AbbrevToUse = CString7Abbrev;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002211 } else if (const ConstantDataSequential *CDS =
Chris Lattner372dd1e2012-01-30 00:51:16 +00002212 dyn_cast<ConstantDataSequential>(C)) {
Chris Lattner5d917072012-01-30 07:36:01 +00002213 Code = bitc::CST_CODE_DATA;
Chris Lattner372dd1e2012-01-30 00:51:16 +00002214 Type *EltTy = CDS->getType()->getElementType();
2215 if (isa<IntegerType>(EltTy)) {
2216 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2217 Record.push_back(CDS->getElementAsInteger(i));
Chris Lattner372dd1e2012-01-30 00:51:16 +00002218 } else {
Justin Bognera43eacb2016-01-06 22:31:32 +00002219 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2220 Record.push_back(
2221 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002222 }
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00002223 } else if (isa<ConstantAggregate>(C)) {
Chris Lattner52523562007-04-24 00:16:04 +00002224 Code = bitc::CST_CODE_AGGREGATE;
Pete Cooper125ad172015-06-25 20:51:38 +00002225 for (const Value *Op : C->operands())
2226 Record.push_back(VE.getValueID(Op));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002227 AbbrevToUse = AggregateAbbrev;
Chris Lattner52523562007-04-24 00:16:04 +00002228 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002229 switch (CE->getOpcode()) {
2230 default:
2231 if (Instruction::isCast(CE->getOpcode())) {
2232 Code = bitc::CST_CODE_CE_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002233 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002234 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2235 Record.push_back(VE.getValueID(C->getOperand(0)));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002236 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002237 } else {
2238 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2239 Code = bitc::CST_CODE_CE_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002240 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002241 Record.push_back(VE.getValueID(C->getOperand(0)));
2242 Record.push_back(VE.getValueID(C->getOperand(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002243 uint64_t Flags = getOptimizationFlags(CE);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002244 if (Flags != 0)
2245 Record.push_back(Flags);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002246 }
2247 break;
David Blaikieb9263572015-03-13 21:03:36 +00002248 case Instruction::GetElementPtr: {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002249 Code = bitc::CST_CODE_CE_GEP;
David Blaikieb9263572015-03-13 21:03:36 +00002250 const auto *GO = cast<GEPOperator>(C);
David Blaikieb9263572015-03-13 21:03:36 +00002251 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
Peter Collingbourned93620b2016-11-10 22:34:55 +00002252 if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2253 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2254 Record.push_back((*Idx << 1) | GO->isInBounds());
2255 } else if (GO->isInBounds())
2256 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002257 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2258 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2259 Record.push_back(VE.getValueID(C->getOperand(i)));
2260 }
2261 break;
David Blaikieb9263572015-03-13 21:03:36 +00002262 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002263 case Instruction::Select:
2264 Code = bitc::CST_CODE_CE_SELECT;
2265 Record.push_back(VE.getValueID(C->getOperand(0)));
2266 Record.push_back(VE.getValueID(C->getOperand(1)));
2267 Record.push_back(VE.getValueID(C->getOperand(2)));
2268 break;
2269 case Instruction::ExtractElement:
2270 Code = bitc::CST_CODE_CE_EXTRACTELT;
2271 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2272 Record.push_back(VE.getValueID(C->getOperand(0)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002273 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002274 Record.push_back(VE.getValueID(C->getOperand(1)));
2275 break;
2276 case Instruction::InsertElement:
2277 Code = bitc::CST_CODE_CE_INSERTELT;
2278 Record.push_back(VE.getValueID(C->getOperand(0)));
2279 Record.push_back(VE.getValueID(C->getOperand(1)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002280 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002281 Record.push_back(VE.getValueID(C->getOperand(2)));
2282 break;
2283 case Instruction::ShuffleVector:
Nate Begeman94aa38d2009-02-12 21:28:33 +00002284 // If the return type and argument types are the same, this is a
2285 // standard shufflevector instruction. If the types are different,
2286 // then the shuffle is widening or truncating the input vectors, and
2287 // the argument type must also be encoded.
2288 if (C->getType() == C->getOperand(0)->getType()) {
2289 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2290 } else {
2291 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2292 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2293 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002294 Record.push_back(VE.getValueID(C->getOperand(0)));
2295 Record.push_back(VE.getValueID(C->getOperand(1)));
2296 Record.push_back(VE.getValueID(C->getOperand(2)));
2297 break;
2298 case Instruction::ICmp:
2299 case Instruction::FCmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002300 Code = bitc::CST_CODE_CE_CMP;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002301 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2302 Record.push_back(VE.getValueID(C->getOperand(0)));
2303 Record.push_back(VE.getValueID(C->getOperand(1)));
2304 Record.push_back(CE->getPredicate());
2305 break;
2306 }
Chris Lattnerf540d742009-10-28 05:24:40 +00002307 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
Chris Lattnerf540d742009-10-28 05:24:40 +00002308 Code = bitc::CST_CODE_BLOCKADDRESS;
2309 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2310 Record.push_back(VE.getValueID(BA->getFunction()));
2311 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
Chris Lattner52523562007-04-24 00:16:04 +00002312 } else {
Dan Gohman47dc8fd2010-07-21 21:18:37 +00002313#ifndef NDEBUG
2314 C->dump();
2315#endif
Torok Edwinfbcc6632009-07-14 16:55:14 +00002316 llvm_unreachable("Unknown constant!");
Chris Lattner52523562007-04-24 00:16:04 +00002317 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002318 Stream.EmitRecord(Code, Record, AbbrevToUse);
Chris Lattner52523562007-04-24 00:16:04 +00002319 Record.clear();
2320 }
2321
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002322 Stream.ExitBlock();
Chris Lattner52523562007-04-24 00:16:04 +00002323}
2324
Teresa Johnson37687f32016-04-23 04:30:47 +00002325void ModuleBitcodeWriter::writeModuleConstants() {
Chris Lattner52523562007-04-24 00:16:04 +00002326 const ValueEnumerator::ValueList &Vals = VE.getValues();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002327
Chris Lattner52523562007-04-24 00:16:04 +00002328 // Find the first constant to emit, which is the first non-globalvalue value.
2329 // We know globalvalues have been emitted by WriteModuleInfo.
2330 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2331 if (!isa<GlobalValue>(Vals[i].first)) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002332 writeConstants(i, Vals.size(), true);
Chris Lattner52523562007-04-24 00:16:04 +00002333 return;
2334 }
2335 }
2336}
Chris Lattner215e9cd2007-04-23 20:35:01 +00002337
Teresa Johnson37687f32016-04-23 04:30:47 +00002338/// pushValueAndType - The file has to encode both the value and type id for
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002339/// many values, because we need to know what type to create for forward
2340/// references. However, most operands are not forward references, so this type
2341/// field is not needed.
2342///
2343/// This function adds V's value ID to Vals. If the value ID is higher than the
2344/// instruction ID, then it is a forward reference, and it also includes the
Jan Wen Voungafaced02012-10-11 20:20:40 +00002345/// type ID. The value ID that is written is encoded relative to the InstID.
Teresa Johnson37687f32016-04-23 04:30:47 +00002346bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2347 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002348 unsigned ValID = VE.getValueID(V);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002349 // Make encoding relative to the InstID.
2350 Vals.push_back(InstID - ValID);
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002351 if (ValID >= InstID) {
2352 Vals.push_back(VE.getTypeID(V->getType()));
2353 return true;
2354 }
2355 return false;
2356}
2357
Teresa Johnson37687f32016-04-23 04:30:47 +00002358void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2359 unsigned InstID) {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002360 SmallVector<unsigned, 64> Record;
2361 LLVMContext &C = CS.getInstruction()->getContext();
2362
2363 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
Sanjoy Das54c3ca62015-11-07 01:56:04 +00002364 const auto &Bundle = CS.getOperandBundleAt(i);
Sanjoy Dasb9ca6dc2015-11-10 20:13:15 +00002365 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002366
2367 for (auto &Input : Bundle.Inputs)
Teresa Johnson37687f32016-04-23 04:30:47 +00002368 pushValueAndType(Input, InstID, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002369
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002370 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002371 Record.clear();
2372 }
2373}
2374
Teresa Johnson37687f32016-04-23 04:30:47 +00002375/// pushValue - Like pushValueAndType, but where the type of the value is
Jan Wen Voungafaced02012-10-11 20:20:40 +00002376/// omitted (perhaps it was already encoded in an earlier operand).
Teresa Johnson37687f32016-04-23 04:30:47 +00002377void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2378 SmallVectorImpl<unsigned> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002379 unsigned ValID = VE.getValueID(V);
2380 Vals.push_back(InstID - ValID);
2381}
2382
Teresa Johnson37687f32016-04-23 04:30:47 +00002383void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2384 SmallVectorImpl<uint64_t> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002385 unsigned ValID = VE.getValueID(V);
2386 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2387 emitSignedInt64(Vals, diff);
2388}
2389
Chris Lattnere6e364c2007-04-26 05:53:54 +00002390/// WriteInstruction - Emit an instruction to the specified stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00002391void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2392 unsigned InstID,
2393 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnere6e364c2007-04-26 05:53:54 +00002394 unsigned Code = 0;
2395 unsigned AbbrevToUse = 0;
Devang Patelaf206b82009-09-18 19:26:43 +00002396 VE.setInstructionID(&I);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002397 switch (I.getOpcode()) {
2398 default:
2399 if (Instruction::isCast(I.getOpcode())) {
Chris Lattner0a603252007-05-01 02:13:26 +00002400 Code = bitc::FUNC_CODE_INST_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002401 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002402 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002403 Vals.push_back(VE.getTypeID(I.getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002404 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
Chris Lattnere6e364c2007-04-26 05:53:54 +00002405 } else {
2406 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
Chris Lattner9f35f912007-05-02 04:26:36 +00002407 Code = bitc::FUNC_CODE_INST_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002408 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002409 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
Teresa Johnson37687f32016-04-23 04:30:47 +00002410 pushValue(I.getOperand(1), InstID, Vals);
2411 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2412 uint64_t Flags = getOptimizationFlags(&I);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002413 if (Flags != 0) {
2414 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2415 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2416 Vals.push_back(Flags);
2417 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002418 }
2419 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002420
David Blaikieb5b5efd2015-02-25 01:08:52 +00002421 case Instruction::GetElementPtr: {
Chris Lattner0a603252007-05-01 02:13:26 +00002422 Code = bitc::FUNC_CODE_INST_GEP;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002423 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2424 auto &GEPInst = cast<GetElementPtrInst>(I);
2425 Vals.push_back(GEPInst.isInBounds());
2426 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002427 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002428 pushValueAndType(I.getOperand(i), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002429 break;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002430 }
Dan Gohmanca0256a2008-05-31 19:11:15 +00002431 case Instruction::ExtractValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002432 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002433 pushValueAndType(I.getOperand(0), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002434 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002435 Vals.append(EVI->idx_begin(), EVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002436 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002437 }
2438 case Instruction::InsertValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002439 Code = bitc::FUNC_CODE_INST_INSERTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002440 pushValueAndType(I.getOperand(0), InstID, Vals);
2441 pushValueAndType(I.getOperand(1), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002442 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002443 Vals.append(IVI->idx_begin(), IVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002444 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002445 }
Chris Lattner0a603252007-05-01 02:13:26 +00002446 case Instruction::Select:
Dan Gohmanc5d28922008-09-16 01:01:33 +00002447 Code = bitc::FUNC_CODE_INST_VSELECT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002448 pushValueAndType(I.getOperand(1), InstID, Vals);
2449 pushValue(I.getOperand(2), InstID, Vals);
2450 pushValueAndType(I.getOperand(0), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002451 break;
2452 case Instruction::ExtractElement:
2453 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002454 pushValueAndType(I.getOperand(0), InstID, Vals);
2455 pushValueAndType(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002456 break;
2457 case Instruction::InsertElement:
2458 Code = bitc::FUNC_CODE_INST_INSERTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002459 pushValueAndType(I.getOperand(0), InstID, Vals);
2460 pushValue(I.getOperand(1), InstID, Vals);
2461 pushValueAndType(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002462 break;
2463 case Instruction::ShuffleVector:
2464 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002465 pushValueAndType(I.getOperand(0), InstID, Vals);
2466 pushValue(I.getOperand(1), InstID, Vals);
2467 pushValue(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002468 break;
2469 case Instruction::ICmp:
James Molloy88eb5352015-07-10 12:52:00 +00002470 case Instruction::FCmp: {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002471 // compare returning Int1Ty or vector of Int1Ty
2472 Code = bitc::FUNC_CODE_INST_CMP2;
Teresa Johnson37687f32016-04-23 04:30:47 +00002473 pushValueAndType(I.getOperand(0), InstID, Vals);
2474 pushValue(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002475 Vals.push_back(cast<CmpInst>(I).getPredicate());
Teresa Johnson37687f32016-04-23 04:30:47 +00002476 uint64_t Flags = getOptimizationFlags(&I);
James Molloy88eb5352015-07-10 12:52:00 +00002477 if (Flags != 0)
2478 Vals.push_back(Flags);
Chris Lattner0a603252007-05-01 02:13:26 +00002479 break;
James Molloy88eb5352015-07-10 12:52:00 +00002480 }
Chris Lattner0a603252007-05-01 02:13:26 +00002481
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002482 case Instruction::Ret:
Devang Patelbbfd8742008-02-26 01:29:32 +00002483 {
2484 Code = bitc::FUNC_CODE_INST_RET;
2485 unsigned NumOperands = I.getNumOperands();
Devang Patelbbfd8742008-02-26 01:29:32 +00002486 if (NumOperands == 0)
2487 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2488 else if (NumOperands == 1) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002489 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Devang Patelbbfd8742008-02-26 01:29:32 +00002490 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2491 } else {
2492 for (unsigned i = 0, e = NumOperands; i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002493 pushValueAndType(I.getOperand(i), InstID, Vals);
Devang Patelbbfd8742008-02-26 01:29:32 +00002494 }
2495 }
Chris Lattner0a603252007-05-01 02:13:26 +00002496 break;
2497 case Instruction::Br:
Gabor Greif1933b002009-01-30 18:27:21 +00002498 {
2499 Code = bitc::FUNC_CODE_INST_BR;
David Blaikieb78e9e52013-02-11 01:16:51 +00002500 const BranchInst &II = cast<BranchInst>(I);
Gabor Greif1933b002009-01-30 18:27:21 +00002501 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2502 if (II.isConditional()) {
2503 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002504 pushValue(II.getCondition(), InstID, Vals);
Gabor Greif1933b002009-01-30 18:27:21 +00002505 }
Chris Lattner0a603252007-05-01 02:13:26 +00002506 }
2507 break;
2508 case Instruction::Switch:
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002509 {
2510 Code = bitc::FUNC_CODE_INST_SWITCH;
David Blaikieb78e9e52013-02-11 01:16:51 +00002511 const SwitchInst &SI = cast<SwitchInst>(I);
Bob Wilsone4077362013-09-09 19:14:35 +00002512 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002513 pushValue(SI.getCondition(), InstID, Vals);
Bob Wilsone4077362013-09-09 19:14:35 +00002514 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
Chandler Carruth927d8e62017-04-12 07:27:28 +00002515 for (auto Case : SI.cases()) {
Sanjay Patel225d65f2015-11-13 16:21:23 +00002516 Vals.push_back(VE.getValueID(Case.getCaseValue()));
2517 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002518 }
2519 }
Chris Lattner0a603252007-05-01 02:13:26 +00002520 break;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00002521 case Instruction::IndirectBr:
2522 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
Chris Lattner3ed871f2009-10-27 19:13:16 +00002523 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Jan Wen Voungafaced02012-10-11 20:20:40 +00002524 // Encode the address operand as relative, but not the basic blocks.
Teresa Johnson37687f32016-04-23 04:30:47 +00002525 pushValue(I.getOperand(0), InstID, Vals);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002526 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
Chris Lattner3ed871f2009-10-27 19:13:16 +00002527 Vals.push_back(VE.getValueID(I.getOperand(i)));
2528 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002529
Chris Lattnerb811e952007-05-01 07:03:37 +00002530 case Instruction::Invoke: {
Gabor Greif4b79e472009-01-16 18:40:27 +00002531 const InvokeInst *II = cast<InvokeInst>(&I);
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002532 const Value *Callee = II->getCalledValue();
2533 FunctionType *FTy = II->getFunctionType();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002534
2535 if (II->hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002536 writeOperandBundles(II, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002537
Chris Lattner0a603252007-05-01 02:13:26 +00002538 Code = bitc::FUNC_CODE_INST_INVOKE;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002539
Reid Klecknerb4a2d182017-04-24 20:38:30 +00002540 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002541 Vals.push_back(II->getCallingConv() | 1 << 13);
Gabor Greif6ecd6f42009-01-07 22:39:29 +00002542 Vals.push_back(VE.getValueID(II->getNormalDest()));
2543 Vals.push_back(VE.getValueID(II->getUnwindDest()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002544 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002545 pushValueAndType(Callee, InstID, Vals);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002546
Chris Lattner0a603252007-05-01 02:13:26 +00002547 // Emit value #'s for the fixed parameters.
Chris Lattner0a603252007-05-01 02:13:26 +00002548 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002549 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
Chris Lattner0a603252007-05-01 02:13:26 +00002550
2551 // Emit type/value pairs for varargs params.
2552 if (FTy->isVarArg()) {
Mehdi Amini7cf63822016-09-19 21:27:04 +00002553 for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002554 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002555 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
Chris Lattner0a603252007-05-01 02:13:26 +00002556 }
2557 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002558 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00002559 case Instruction::Resume:
2560 Code = bitc::FUNC_CODE_INST_RESUME;
Teresa Johnson37687f32016-04-23 04:30:47 +00002561 pushValueAndType(I.getOperand(0), InstID, Vals);
Bill Wendlingf891bf82011-07-31 06:30:59 +00002562 break;
David Majnemer654e1302015-07-31 17:58:14 +00002563 case Instruction::CleanupRet: {
2564 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2565 const auto &CRI = cast<CleanupReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002566 pushValue(CRI.getCleanupPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002567 if (CRI.hasUnwindDest())
2568 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2569 break;
2570 }
2571 case Instruction::CatchRet: {
2572 Code = bitc::FUNC_CODE_INST_CATCHRET;
2573 const auto &CRI = cast<CatchReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002574 pushValue(CRI.getCatchPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002575 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2576 break;
2577 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00002578 case Instruction::CleanupPad:
David Majnemer654e1302015-07-31 17:58:14 +00002579 case Instruction::CatchPad: {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002580 const auto &FuncletPad = cast<FuncletPadInst>(I);
2581 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2582 : bitc::FUNC_CODE_INST_CLEANUPPAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002583 pushValue(FuncletPad.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002584
2585 unsigned NumArgOperands = FuncletPad.getNumArgOperands();
David Majnemer654e1302015-07-31 17:58:14 +00002586 Vals.push_back(NumArgOperands);
2587 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
Teresa Johnson37687f32016-04-23 04:30:47 +00002588 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002589 break;
2590 }
2591 case Instruction::CatchSwitch: {
2592 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2593 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2594
Teresa Johnson37687f32016-04-23 04:30:47 +00002595 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002596
2597 unsigned NumHandlers = CatchSwitch.getNumHandlers();
2598 Vals.push_back(NumHandlers);
2599 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2600 Vals.push_back(VE.getValueID(CatchPadBB));
2601
2602 if (CatchSwitch.hasUnwindDest())
2603 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
David Majnemer654e1302015-07-31 17:58:14 +00002604 break;
2605 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002606 case Instruction::Unreachable:
2607 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
Chris Lattnercc6d4c92007-05-06 01:28:01 +00002608 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002609 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002610
Jay Foad372ad642011-06-20 14:18:48 +00002611 case Instruction::PHI: {
2612 const PHINode &PN = cast<PHINode>(I);
Chris Lattner0a603252007-05-01 02:13:26 +00002613 Code = bitc::FUNC_CODE_INST_PHI;
Jan Wen Voungafaced02012-10-11 20:20:40 +00002614 // With the newer instruction encoding, forward references could give
2615 // negative valued IDs. This is most common for PHIs, so we use
2616 // signed VBRs.
2617 SmallVector<uint64_t, 128> Vals64;
2618 Vals64.push_back(VE.getTypeID(PN.getType()));
Jay Foad372ad642011-06-20 14:18:48 +00002619 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002620 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002621 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
Jay Foad372ad642011-06-20 14:18:48 +00002622 }
Jan Wen Voungafaced02012-10-11 20:20:40 +00002623 // Emit a Vals64 vector and exit.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002624 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002625 Vals64.clear();
2626 return;
Jay Foad372ad642011-06-20 14:18:48 +00002627 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002628
Bill Wendlingfae14752011-08-12 20:24:12 +00002629 case Instruction::LandingPad: {
2630 const LandingPadInst &LP = cast<LandingPadInst>(I);
2631 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2632 Vals.push_back(VE.getTypeID(LP.getType()));
Bill Wendlingfae14752011-08-12 20:24:12 +00002633 Vals.push_back(LP.isCleanup());
2634 Vals.push_back(LP.getNumClauses());
2635 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2636 if (LP.isCatch(I))
2637 Vals.push_back(LandingPadInst::Catch);
2638 else
2639 Vals.push_back(LandingPadInst::Filter);
Teresa Johnson37687f32016-04-23 04:30:47 +00002640 pushValueAndType(LP.getClause(I), InstID, Vals);
Bill Wendlingfae14752011-08-12 20:24:12 +00002641 }
2642 break;
2643 }
2644
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002645 case Instruction::Alloca: {
Chris Lattner0a603252007-05-01 02:13:26 +00002646 Code = bitc::FUNC_CODE_INST_ALLOCA;
David Blaikiebdb49102015-04-28 16:51:01 +00002647 const AllocaInst &AI = cast<AllocaInst>(I);
2648 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
Dan Gohman9da5bb02010-05-28 01:38:28 +00002649 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002650 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002651 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2652 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2653 "not enough bits for maximum alignment");
2654 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2655 AlignRecord |= AI.isUsedWithInAlloca() << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00002656 AlignRecord |= 1 << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00002657 AlignRecord |= AI.isSwiftError() << 7;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002658 Vals.push_back(AlignRecord);
Chris Lattner0a603252007-05-01 02:13:26 +00002659 break;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002660 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002661
Chris Lattner0a603252007-05-01 02:13:26 +00002662 case Instruction::Load:
Eli Friedman59b66882011-08-09 23:02:53 +00002663 if (cast<LoadInst>(I).isAtomic()) {
2664 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002665 pushValueAndType(I.getOperand(0), InstID, Vals);
Eli Friedman59b66882011-08-09 23:02:53 +00002666 } else {
2667 Code = bitc::FUNC_CODE_INST_LOAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002668 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
Eli Friedman59b66882011-08-09 23:02:53 +00002669 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2670 }
David Blaikie85035652015-02-25 01:07:20 +00002671 Vals.push_back(VE.getTypeID(I.getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002672 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2673 Vals.push_back(cast<LoadInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002674 if (cast<LoadInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002675 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002676 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
Eli Friedman59b66882011-08-09 23:02:53 +00002677 }
Chris Lattner0a603252007-05-01 02:13:26 +00002678 break;
2679 case Instruction::Store:
Eli Friedman59b66882011-08-09 23:02:53 +00002680 if (cast<StoreInst>(I).isAtomic())
2681 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2682 else
2683 Code = bitc::FUNC_CODE_INST_STORE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002684 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2685 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
Chris Lattner0a603252007-05-01 02:13:26 +00002686 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2687 Vals.push_back(cast<StoreInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002688 if (cast<StoreInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002689 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002690 Vals.push_back(
2691 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
Eli Friedman59b66882011-08-09 23:02:53 +00002692 }
Chris Lattner0a603252007-05-01 02:13:26 +00002693 break;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002694 case Instruction::AtomicCmpXchg:
2695 Code = bitc::FUNC_CODE_INST_CMPXCHG;
Teresa Johnson37687f32016-04-23 04:30:47 +00002696 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2697 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2698 pushValue(I.getOperand(2), InstID, Vals); // newval.
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002699 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002700 Vals.push_back(
2701 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2702 Vals.push_back(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002703 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002704 Vals.push_back(
2705 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
Tim Northover420a2162014-06-13 14:24:07 +00002706 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002707 break;
2708 case Instruction::AtomicRMW:
2709 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
Teresa Johnson37687f32016-04-23 04:30:47 +00002710 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2711 pushValue(I.getOperand(1), InstID, Vals); // val.
2712 Vals.push_back(
2713 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002714 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002715 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2716 Vals.push_back(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002717 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002718 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002719 case Instruction::Fence:
2720 Code = bitc::FUNC_CODE_INST_FENCE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002721 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002722 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
Eli Friedmanfee02c62011-07-25 23:16:38 +00002723 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002724 case Instruction::Call: {
Gabor Greife9afee22010-06-26 09:35:09 +00002725 const CallInst &CI = cast<CallInst>(I);
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002726 FunctionType *FTy = CI.getFunctionType();
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002727
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002728 if (CI.hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002729 writeOperandBundles(&CI, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002730
Chris Lattnerc44070802011-06-17 18:17:37 +00002731 Code = bitc::FUNC_CODE_INST_CALL;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002732
Reid Klecknerb4a2d182017-04-24 20:38:30 +00002733 Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002734
Teresa Johnson37687f32016-04-23 04:30:47 +00002735 unsigned Flags = getOptimizationFlags(&I);
Akira Hatanaka97cb3972015-11-07 02:48:49 +00002736 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2737 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2738 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2739 1 << bitc::CALL_EXPLICIT_TYPE |
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002740 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2741 unsigned(Flags != 0) << bitc::CALL_FMF);
2742 if (Flags != 0)
2743 Vals.push_back(Flags);
2744
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002745 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002746 pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002747
Chris Lattner0a603252007-05-01 02:13:26 +00002748 // Emit value #'s for the fixed parameters.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002749 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2750 // Check for labels (can happen with asm labels).
2751 if (FTy->getParamType(i)->isLabelTy())
2752 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2753 else
Teresa Johnson37687f32016-04-23 04:30:47 +00002754 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002755 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002756
Chris Lattnerb811e952007-05-01 07:03:37 +00002757 // Emit type/value pairs for varargs params.
2758 if (FTy->isVarArg()) {
Gabor Greife9afee22010-06-26 09:35:09 +00002759 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002760 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002761 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
Chris Lattner0a603252007-05-01 02:13:26 +00002762 }
2763 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002764 }
Chris Lattner0a603252007-05-01 02:13:26 +00002765 case Instruction::VAArg:
2766 Code = bitc::FUNC_CODE_INST_VAARG;
2767 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
Teresa Johnson37687f32016-04-23 04:30:47 +00002768 pushValue(I.getOperand(0), InstID, Vals); // valist.
Chris Lattner0a603252007-05-01 02:13:26 +00002769 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2770 break;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002771 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002772
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002773 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002774 Vals.clear();
2775}
2776
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002777/// Write a GlobalValue VST to the module. The purpose of this data structure is
2778/// to allow clients to efficiently find the function body.
2779void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
2780 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
2781 // Get the offset of the VST we are writing, and backpatch it into
2782 // the VST forward declaration record.
2783 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2784 // The BitcodeStartBit was the stream offset of the identification block.
2785 VSTOffset -= bitcodeStartBit();
2786 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2787 // Note that we add 1 here because the offset is relative to one word
2788 // before the start of the identification block, which was historically
2789 // always the start of the regular bitcode header.
2790 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002791
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002792 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
Chris Lattner2eae59f2007-05-04 20:34:50 +00002793
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002794 auto Abbv = std::make_shared<BitCodeAbbrev>();
2795 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2796 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2797 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2798 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnsonff642b92015-09-17 20:12:00 +00002799
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002800 for (const Function &F : M) {
2801 uint64_t Record[2];
Teresa Johnsonff642b92015-09-17 20:12:00 +00002802
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002803 if (F.isDeclaration())
2804 continue;
Teresa Johnsoncd21a642016-07-17 14:47:01 +00002805
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002806 Record[0] = VE.getValueID(&F);
2807
2808 // Save the word offset of the function (from the start of the
2809 // actual bitcode written to the stream).
2810 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
2811 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2812 // Note that we add 1 here because the offset is relative to one word
2813 // before the start of the identification block, which was historically
2814 // always the start of the regular bitcode header.
2815 Record[1] = BitcodeIndex / 32 + 1;
2816
2817 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002818 }
2819
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002820 Stream.ExitBlock();
2821}
2822
2823/// Emit names for arguments, instructions and basic blocks in a function.
2824void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
2825 const ValueSymbolTable &VST) {
2826 if (VST.empty())
2827 return;
2828
2829 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2830
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002831 // FIXME: Set up the abbrev, we know how many values there are!
2832 // FIXME: We know if the type names can use 7-bit ascii.
Teresa Johnsoncd21a642016-07-17 14:47:01 +00002833 SmallVector<uint64_t, 64> NameVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002834
Yaron Keren001e2e42015-08-10 07:04:29 +00002835 for (const ValueName &Name : VST) {
Chris Lattner4d925982007-05-04 20:52:02 +00002836 // Figure out the encoding to use for the name.
David Blaikieb6b42e02017-06-02 17:24:26 +00002837 StringEncoding Bits = getStringEncoding(Name.getKey());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002838
Chris Lattnera0987962007-05-04 21:31:13 +00002839 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
Teresa Johnsonff642b92015-09-17 20:12:00 +00002840 NameVals.push_back(VE.getValueID(Name.getValue()));
2841
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002842 // VST_CODE_ENTRY: [valueid, namechar x N]
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002843 // VST_CODE_BBENTRY: [bbid, namechar x N]
Chris Lattner6be58c62007-05-03 22:18:21 +00002844 unsigned Code;
Yaron Keren001e2e42015-08-10 07:04:29 +00002845 if (isa<BasicBlock>(Name.getValue())) {
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002846 Code = bitc::VST_CODE_BBENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002847 if (Bits == SE_Char6)
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002848 AbbrevToUse = VST_BBENTRY_6_ABBREV;
Chris Lattner6be58c62007-05-03 22:18:21 +00002849 } else {
2850 Code = bitc::VST_CODE_ENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002851 if (Bits == SE_Char6)
Chris Lattnere760d6f2007-05-05 01:26:50 +00002852 AbbrevToUse = VST_ENTRY_6_ABBREV;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002853 else if (Bits == SE_Fixed7)
Chris Lattnere760d6f2007-05-05 01:26:50 +00002854 AbbrevToUse = VST_ENTRY_7_ABBREV;
Chris Lattner6be58c62007-05-03 22:18:21 +00002855 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002856
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002857 for (const auto P : Name.getKey())
2858 NameVals.push_back((unsigned char)P);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002859
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002860 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002861 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002862 NameVals.clear();
2863 }
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002864
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002865 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00002866}
2867
Teresa Johnson37687f32016-04-23 04:30:47 +00002868void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002869 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2870 unsigned Code;
2871 if (isa<BasicBlock>(Order.V))
2872 Code = bitc::USELIST_CODE_BB;
2873 else
2874 Code = bitc::USELIST_CODE_DEFAULT;
2875
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002876 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002877 Record.push_back(VE.getValueID(Order.V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002878 Stream.EmitRecord(Code, Record);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002879}
2880
Teresa Johnson37687f32016-04-23 04:30:47 +00002881void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00002882 assert(VE.shouldPreserveUseListOrder() &&
2883 "Expected to be preserving use-list order");
2884
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002885 auto hasMore = [&]() {
2886 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2887 };
2888 if (!hasMore())
2889 // Nothing to do.
2890 return;
2891
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002892 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002893 while (hasMore()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002894 writeUseList(std::move(VE.UseListOrders.back()));
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002895 VE.UseListOrders.pop_back();
2896 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002897 Stream.ExitBlock();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002898}
2899
Teresa Johnson403a7872015-10-04 14:33:43 +00002900/// Emit a function body to the module stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00002901void ModuleBitcodeWriter::writeFunction(
2902 const Function &F,
2903 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00002904 // Save the bitcode index of the start of this function block for recording
2905 // in the VST.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002906 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002907
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002908 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
Chad Rosier6a11b642011-06-03 17:02:19 +00002909 VE.incorporateFunction(F);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002910
2911 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002912
Chris Lattnere6e364c2007-04-26 05:53:54 +00002913 // Emit the number of basic blocks, so the reader can create them ahead of
2914 // time.
2915 Vals.push_back(VE.getBasicBlocks().size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002916 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002917 Vals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002918
Chris Lattnere6e364c2007-04-26 05:53:54 +00002919 // If there are function-local constants, emit them now.
2920 unsigned CstStart, CstEnd;
2921 VE.getFunctionConstantRange(CstStart, CstEnd);
Teresa Johnson37687f32016-04-23 04:30:47 +00002922 writeConstants(CstStart, CstEnd, false);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002923
Victor Hernandez6c730de2010-01-14 01:50:08 +00002924 // If there is function-local metadata, emit it now.
Teresa Johnson37687f32016-04-23 04:30:47 +00002925 writeFunctionMetadata(F);
Victor Hernandez6c730de2010-01-14 01:50:08 +00002926
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002927 // Keep a running idea of what the instruction ID is.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002928 unsigned InstID = CstEnd;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002929
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002930 bool NeedsMetadataAttachment = F.hasMetadata();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002931
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002932 DILocation *LastDL = nullptr;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002933 // Finally, emit all the instructions, in order.
Nick Lewycky4d43d3c2008-04-25 16:53:59 +00002934 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002935 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2936 I != E; ++I) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002937 writeInstruction(*I, InstID, Vals);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002938
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002939 if (!I->getType()->isVoidTy())
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002940 ++InstID;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002941
Chris Lattner07d09ed2010-04-03 02:17:50 +00002942 // If the instruction has metadata, write a metadata attachment later.
2943 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002944
Chris Lattner07d09ed2010-04-03 02:17:50 +00002945 // If the instruction has a debug location, emit it.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002946 DILocation *DL = I->getDebugLoc();
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00002947 if (!DL)
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002948 continue;
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002949
2950 if (DL == LastDL) {
Chris Lattner07d09ed2010-04-03 02:17:50 +00002951 // Just repeat the same debug loc as last time.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002952 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002953 continue;
Chris Lattner07d09ed2010-04-03 02:17:50 +00002954 }
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002955
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00002956 Vals.push_back(DL->getLine());
2957 Vals.push_back(DL->getColumn());
2958 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2959 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002960 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002961 Vals.clear();
Duncan P. N. Exon Smith538ef562015-05-06 22:51:12 +00002962
2963 LastDL = DL;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002964 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002965
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002966 // Emit names for all the instructions etc.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002967 if (auto *Symtab = F.getValueSymbolTable())
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002968 writeFunctionLevelValueSymbolTable(*Symtab);
Devang Patelaf206b82009-09-18 19:26:43 +00002969
Chris Lattner07d09ed2010-04-03 02:17:50 +00002970 if (NeedsMetadataAttachment)
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002971 writeFunctionMetadataAttachment(F);
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00002972 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00002973 writeUseListBlock(&F);
Chad Rosier6a11b642011-06-03 17:02:19 +00002974 VE.purgeFunction();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002975 Stream.ExitBlock();
Chris Lattner831d4202007-04-26 03:27:58 +00002976}
2977
Chris Lattner702658c2007-05-04 18:26:27 +00002978// Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00002979void ModuleBitcodeWriter::writeBlockInfo() {
Chris Lattner702658c2007-05-04 18:26:27 +00002980 // We only want to emit block info records for blocks that have multiple
Jan Wen Voungafaced02012-10-11 20:20:40 +00002981 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
Jan Wen Voung8c9e9412012-10-11 21:45:16 +00002982 // Other blocks can define their abbrevs inline.
Peter Collingbourned3a6c702016-11-01 01:18:57 +00002983 Stream.EnterBlockInfoBlock();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002984
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002985 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002986 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00002987 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2988 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2989 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2990 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002991 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002992 VST_ENTRY_8_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002993 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00002994 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002995
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002996 { // 7-bit fixed width VST_CODE_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002997 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00002998 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2999 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3000 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3001 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003002 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003003 VST_ENTRY_7_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003004 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00003005 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003006 { // 6-bit char6 VST_CODE_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003007 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnere760d6f2007-05-05 01:26:50 +00003008 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3009 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3010 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3011 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003012 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003013 VST_ENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003014 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnere760d6f2007-05-05 01:26:50 +00003015 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003016 { // 6-bit char6 VST_CODE_BBENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003017 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00003018 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3019 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3020 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chris Lattnere760d6f2007-05-05 01:26:50 +00003021 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003022 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003023 VST_BBENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003024 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00003025 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00003026
3027
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003028
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003029 { // SETTYPE abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003030 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003031 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3032 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
David Blaikie7b028102015-02-25 00:51:52 +00003033 VE.computeBitsRequiredForTypeIndicies()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003034 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003035 CONSTANTS_SETTYPE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003036 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003037 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003038
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003039 { // INTEGER abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003040 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003041 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3042 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003043 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003044 CONSTANTS_INTEGER_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003045 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003046 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003047
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003048 { // CE_CAST abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003049 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003050 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3051 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3052 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
David Blaikie7b028102015-02-25 00:51:52 +00003053 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003054 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3055
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003056 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003057 CONSTANTS_CE_CAST_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003058 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003059 }
3060 { // NULL abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003061 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003062 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003063 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003064 CONSTANTS_NULL_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003065 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003066 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003067
Chris Lattnerb80751d2007-05-05 07:44:49 +00003068 // FIXME: This should only use space for first class types!
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003069
Chris Lattnerb80751d2007-05-05 07:44:49 +00003070 { // INST_LOAD abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003071 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb80751d2007-05-05 07:44:49 +00003072 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
Chris Lattnerb80751d2007-05-05 07:44:49 +00003073 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
David Blaikie85035652015-02-25 01:07:20 +00003074 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3075 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerb80751d2007-05-05 07:44:49 +00003076 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3077 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003078 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003079 FUNCTION_INST_LOAD_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003080 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerb80751d2007-05-05 07:44:49 +00003081 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003082 { // INST_BINOP abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003083 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003084 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3085 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3086 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3087 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003088 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003089 FUNCTION_INST_BINOP_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003090 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003091 }
Dan Gohman0ebd6962009-07-20 21:19:07 +00003092 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003093 auto Abbv = std::make_shared<BitCodeAbbrev>();
Dan Gohman0ebd6962009-07-20 21:19:07 +00003094 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3095 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3096 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3097 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3098 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003099 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003100 FUNCTION_INST_BINOP_FLAGS_ABBREV)
Dan Gohman0ebd6962009-07-20 21:19:07 +00003101 llvm_unreachable("Unexpected abbrev ordering!");
3102 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003103 { // INST_CAST abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003104 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003105 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3106 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3107 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
David Blaikie7b028102015-02-25 00:51:52 +00003108 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003109 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003110 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003111 FUNCTION_INST_CAST_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003112 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003113 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003114
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003115 { // INST_RET abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003116 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003117 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003118 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003119 FUNCTION_INST_RET_VOID_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003120 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003121 }
3122 { // INST_RET abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003123 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003124 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3125 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003126 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003127 FUNCTION_INST_RET_VAL_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003128 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003129 }
3130 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003131 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003132 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003133 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003134 FUNCTION_INST_UNREACHABLE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003135 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003136 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00003137 {
David Blaikie7ad9dc12017-01-04 22:36:33 +00003138 auto Abbv = std::make_shared<BitCodeAbbrev>();
David Blaikieb5b5efd2015-02-25 01:08:52 +00003139 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3140 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3141 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3142 Log2_32_Ceil(VE.getTypes().size() + 1)));
3143 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3144 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003145 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
David Blaikieb5b5efd2015-02-25 01:08:52 +00003146 FUNCTION_INST_GEP_ABBREV)
3147 llvm_unreachable("Unexpected abbrev ordering!");
3148 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003149
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003150 Stream.ExitBlock();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003151}
3152
Teresa Johnson403a7872015-10-04 14:33:43 +00003153/// Write the module path strings, currently only used when generating
3154/// a combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003155void IndexBitcodeWriter::writeModStrings() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003156 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
Teresa Johnson403a7872015-10-04 14:33:43 +00003157
3158 // TODO: See which abbrev sizes we actually need to emit
3159
3160 // 8-bit fixed-width MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003161 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003162 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3163 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3164 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3165 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003166 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003167
3168 // 7-bit fixed width MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003169 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003170 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3171 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3172 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3173 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003174 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003175
3176 // 6-bit char6 MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003177 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003178 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3179 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3180 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3181 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003182 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003183
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003184 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003185 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003186 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3187 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3188 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3189 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3190 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3191 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003192 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003193
3194 SmallVector<unsigned, 64> Vals;
Teresa Johnson7a27b132017-06-02 01:56:02 +00003195 forEachModule(
3196 [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
David Blaikieb6b42e02017-06-02 17:24:26 +00003197 StringRef Key = MPSE.getKey();
3198 const auto &Value = MPSE.getValue();
3199 StringEncoding Bits = getStringEncoding(Key);
Teresa Johnson7a27b132017-06-02 01:56:02 +00003200 unsigned AbbrevToUse = Abbrev8Bit;
3201 if (Bits == SE_Char6)
3202 AbbrevToUse = Abbrev6Bit;
3203 else if (Bits == SE_Fixed7)
3204 AbbrevToUse = Abbrev7Bit;
Teresa Johnson403a7872015-10-04 14:33:43 +00003205
David Blaikieb6b42e02017-06-02 17:24:26 +00003206 Vals.push_back(Value.first);
3207 Vals.append(Key.begin(), Key.end());
Teresa Johnson403a7872015-10-04 14:33:43 +00003208
Teresa Johnson7a27b132017-06-02 01:56:02 +00003209 // Emit the finished record.
3210 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003211
Teresa Johnson7a27b132017-06-02 01:56:02 +00003212 // Emit an optional hash for the module now
David Blaikieb6b42e02017-06-02 17:24:26 +00003213 const auto &Hash = Value.second;
3214 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3215 Vals.assign(Hash.begin(), Hash.end());
Teresa Johnson7a27b132017-06-02 01:56:02 +00003216 // Emit the hash record.
3217 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3218 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003219
Teresa Johnson7a27b132017-06-02 01:56:02 +00003220 Vals.clear();
3221 });
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003222 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003223}
3224
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003225/// Write the function type metadata related records that need to appear before
3226/// a function summary entry (whether per-module or combined).
3227static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3228 FunctionSummary *FS) {
3229 if (!FS->type_tests().empty())
3230 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3231
3232 SmallVector<uint64_t, 64> Record;
3233
3234 auto WriteVFuncIdVec = [&](uint64_t Ty,
3235 ArrayRef<FunctionSummary::VFuncId> VFs) {
3236 if (VFs.empty())
3237 return;
3238 Record.clear();
3239 for (auto &VF : VFs) {
3240 Record.push_back(VF.GUID);
3241 Record.push_back(VF.Offset);
3242 }
3243 Stream.EmitRecord(Ty, Record);
3244 };
3245
3246 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3247 FS->type_test_assume_vcalls());
3248 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3249 FS->type_checked_load_vcalls());
3250
3251 auto WriteConstVCallVec = [&](uint64_t Ty,
3252 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3253 for (auto &VC : VCs) {
3254 Record.clear();
3255 Record.push_back(VC.VFunc.GUID);
3256 Record.push_back(VC.VFunc.Offset);
3257 Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
3258 Stream.EmitRecord(Ty, Record);
3259 }
3260 };
3261
3262 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3263 FS->type_test_assume_const_vcalls());
3264 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3265 FS->type_checked_load_const_vcalls());
3266}
3267
Teresa Johnson403a7872015-10-04 14:33:43 +00003268// Helper to emit a single function summary record.
Teresa Johnson37687f32016-04-23 04:30:47 +00003269void ModuleBitcodeWriter::writePerModuleFunctionSummaryRecord(
Teresa Johnson28e457b2016-04-24 14:57:11 +00003270 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
Teresa Johnson37687f32016-04-23 04:30:47 +00003271 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3272 const Function &F) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003273 NameVals.push_back(ValueID);
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003274
Teresa Johnson28e457b2016-04-24 14:57:11 +00003275 FunctionSummary *FS = cast<FunctionSummary>(Summary);
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003276 writeFunctionTypeMetadataRecords(Stream, FS);
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00003277
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003278 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
Teresa Johnson403a7872015-10-04 14:33:43 +00003279 NameVals.push_back(FS->instCount());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003280 NameVals.push_back(FS->refs().size());
3281
3282 for (auto &RI : FS->refs())
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003283 NameVals.push_back(VE.getValueID(RI.getValue()));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003284
3285 bool HasProfileData = F.getEntryCount().hasValue();
Peter Collingbourne0c30f082016-12-20 21:12:28 +00003286 for (auto &ECI : FS->calls()) {
Teresa Johnsoncd21a642016-07-17 14:47:01 +00003287 NameVals.push_back(getValueId(ECI.first));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003288 if (HasProfileData)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003289 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003290 }
3291
3292 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3293 unsigned Code =
3294 (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
Teresa Johnson403a7872015-10-04 14:33:43 +00003295
3296 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003297 Stream.EmitRecord(Code, NameVals, FSAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003298 NameVals.clear();
3299}
3300
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003301// Collect the global value references in the given variable's initializer,
3302// and emit them in a summary record.
Teresa Johnson37687f32016-04-23 04:30:47 +00003303void ModuleBitcodeWriter::writeModuleLevelReferences(
3304 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3305 unsigned FSModRefsAbbrev) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00003306 auto VI = Index->getValueInfo(GlobalValue::getGUID(V.getName()));
3307 if (!VI || VI.getSummaryList().empty()) {
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003308 // Only declarations should not have a summary (a declaration might however
3309 // have a summary if the def was in module level asm).
3310 assert(V.isDeclaration());
Teresa Johnson13968092016-03-15 19:35:45 +00003311 return;
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003312 }
Peter Collingbourne9667b912017-05-04 18:03:25 +00003313 auto *Summary = VI.getSummaryList()[0].get();
Teresa Johnson13968092016-03-15 19:35:45 +00003314 NameVals.push_back(VE.getValueID(&V));
Teresa Johnson28e457b2016-04-24 14:57:11 +00003315 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
Teresa Johnson7c31cb12016-10-28 19:36:00 +00003316 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003317
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003318 unsigned SizeBeforeRefs = NameVals.size();
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003319 for (auto &RI : VS->refs())
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003320 NameVals.push_back(VE.getValueID(RI.getValue()));
3321 // Sort the refs for determinism output, the vector returned by FS->refs() has
3322 // been initialized from a DenseSet.
3323 std::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003324
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003325 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3326 FSModRefsAbbrev);
Teresa Johnson13968092016-03-15 19:35:45 +00003327 NameVals.clear();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003328}
Teresa Johnson403a7872015-10-04 14:33:43 +00003329
Mehdi Amini8fe69362016-04-24 03:18:11 +00003330// Current version for the summary.
3331// This is bumped whenever we introduce changes in the way some record are
3332// interpreted, like flags for instance.
Teresa Johnson519465b2017-01-05 14:32:16 +00003333static const uint64_t INDEX_VERSION = 3;
Mehdi Amini8fe69362016-04-24 03:18:11 +00003334
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003335/// Emit the per-module summary section alongside the rest of
3336/// the module's bitcode.
Teresa Johnson37687f32016-04-23 04:30:47 +00003337void ModuleBitcodeWriter::writePerModuleGlobalValueSummary() {
Peter Collingbournee357fbd2017-06-08 23:01:49 +00003338 // By default we compile with ThinLTO if the module has a summary, but the
3339 // client can request full LTO with a module flag.
3340 bool IsThinLTO = true;
3341 if (auto *MD =
3342 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3343 IsThinLTO = MD->getZExtValue();
3344 Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
3345 : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
3346 4);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003347
Mehdi Amini8fe69362016-04-24 03:18:11 +00003348 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3349
Teresa Johnson620c1402016-09-20 23:07:17 +00003350 if (Index->begin() == Index->end()) {
3351 Stream.ExitBlock();
3352 return;
3353 }
3354
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003355 for (const auto &GVI : valueIds()) {
3356 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3357 ArrayRef<uint64_t>{GVI.second, GVI.first});
3358 }
3359
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003360 // Abbrev for FS_PERMODULE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003361 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003362 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003363 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003364 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003365 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003366 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003367 // numrefs x valueid, n x (valueid)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003368 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3369 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003370 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003371
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003372 // Abbrev for FS_PERMODULE_PROFILE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003373 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003374 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3375 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003376 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003377 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3378 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003379 // numrefs x valueid, n x (valueid, hotness)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003380 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3381 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003382 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003383
3384 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003385 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003386 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3387 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003388 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003389 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3390 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003391 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003392
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003393 // Abbrev for FS_ALIAS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003394 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003395 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3396 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003397 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003398 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
David Blaikie7ad9dc12017-01-04 22:36:33 +00003399 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003400
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003401 SmallVector<uint64_t, 64> NameVals;
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003402 // Iterate over the list of functions instead of the Index to
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003403 // ensure the ordering is stable.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003404 for (const Function &F : M) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003405 // Summary emission does not support anonymous functions, they have to
3406 // renamed using the anonymous function renaming pass.
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003407 if (!F.hasName())
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003408 report_fatal_error("Unexpected anonymous function when writing summary");
Teresa Johnson403a7872015-10-04 14:33:43 +00003409
Peter Collingbourne9667b912017-05-04 18:03:25 +00003410 ValueInfo VI = Index->getValueInfo(GlobalValue::getGUID(F.getName()));
3411 if (!VI || VI.getSummaryList().empty()) {
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003412 // Only declarations should not have a summary (a declaration might
3413 // however have a summary if the def was in module level asm).
3414 assert(F.isDeclaration());
3415 continue;
3416 }
Peter Collingbourne9667b912017-05-04 18:03:25 +00003417 auto *Summary = VI.getSummaryList()[0].get();
Peter Collingbourne832e7fa2016-05-06 02:41:23 +00003418 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3419 FSCallsAbbrev, FSCallsProfileAbbrev, F);
Teresa Johnson403a7872015-10-04 14:33:43 +00003420 }
3421
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003422 // Capture references from GlobalVariable initializers, which are outside
3423 // of a function scope.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003424 for (const GlobalVariable &G : M.globals())
Teresa Johnson37687f32016-04-23 04:30:47 +00003425 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003426
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003427 for (const GlobalAlias &A : M.aliases()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003428 auto *Aliasee = A.getBaseObject();
3429 if (!Aliasee->hasName())
3430 // Nameless function don't have an entry in the summary, skip it.
3431 continue;
3432 auto AliasId = VE.getValueID(&A);
3433 auto AliaseeId = VE.getValueID(Aliasee);
3434 NameVals.push_back(AliasId);
Teresa Johnson02563cd2016-10-28 02:39:38 +00003435 auto *Summary = Index->getGlobalValueSummary(A);
3436 AliasSummary *AS = cast<AliasSummary>(Summary);
3437 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003438 NameVals.push_back(AliaseeId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003439 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003440 NameVals.clear();
3441 }
3442
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003443 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003444}
3445
Teresa Johnson26ab5772016-03-15 00:04:37 +00003446/// Emit the combined summary section into the combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003447void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003448 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
Mehdi Amini8fe69362016-04-24 03:18:11 +00003449 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
Teresa Johnson403a7872015-10-04 14:33:43 +00003450
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003451 for (const auto &GVI : valueIds()) {
3452 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3453 ArrayRef<uint64_t>{GVI.second, GVI.first});
3454 }
3455
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003456 // Abbrev for FS_COMBINED.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003457 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003458 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
Teresa Johnson02e98332016-04-27 13:28:35 +00003459 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003460 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003461 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003462 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3463 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003464 // numrefs x valueid, n x (valueid)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003465 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3466 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003467 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003468
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003469 // Abbrev for FS_COMBINED_PROFILE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003470 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003471 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
Teresa Johnson02e98332016-04-27 13:28:35 +00003472 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003473 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003474 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003475 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3476 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003477 // numrefs x valueid, n x (valueid, hotness)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003478 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3479 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003480 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003481
3482 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003483 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003484 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003485 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003486 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003487 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003488 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3489 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003490 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003491
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003492 // Abbrev for FS_COMBINED_ALIAS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003493 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003494 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003495 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003496 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003497 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson02e98332016-04-27 13:28:35 +00003498 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
David Blaikie7ad9dc12017-01-04 22:36:33 +00003499 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003500
Teresa Johnson02e98332016-04-27 13:28:35 +00003501 // The aliases are emitted as a post-pass, and will point to the value
3502 // id of the aliasee. Save them in a vector for post-processing.
Teresa Johnson28e457b2016-04-24 14:57:11 +00003503 SmallVector<AliasSummary *, 64> Aliases;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003504
Teresa Johnson02e98332016-04-27 13:28:35 +00003505 // Save the value id for each summary for alias emission.
3506 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3507
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003508 SmallVector<uint64_t, 64> NameVals;
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003509
3510 // For local linkage, we also emit the original name separately
3511 // immediately after the record.
3512 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3513 if (!GlobalValue::isLocalLinkage(S.linkage()))
3514 return;
3515 NameVals.push_back(S.getOriginalName());
3516 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3517 NameVals.clear();
3518 };
3519
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003520 forEachSummary([&](GVInfo I) {
Teresa Johnson84174c32016-05-10 13:48:23 +00003521 GlobalValueSummary *S = I.second;
3522 assert(S);
Teresa Johnson02e98332016-04-27 13:28:35 +00003523
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003524 auto ValueId = getValueId(I.first);
3525 assert(ValueId);
3526 SummaryToValueIdMap[S] = *ValueId;
Teresa Johnson02e98332016-04-27 13:28:35 +00003527
Teresa Johnson84174c32016-05-10 13:48:23 +00003528 if (auto *AS = dyn_cast<AliasSummary>(S)) {
3529 // Will process aliases as a post-pass because the reader wants all
3530 // global to be loaded first.
3531 Aliases.push_back(AS);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003532 return;
Teresa Johnson84174c32016-05-10 13:48:23 +00003533 }
Teresa Johnson403a7872015-10-04 14:33:43 +00003534
Teresa Johnson84174c32016-05-10 13:48:23 +00003535 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003536 NameVals.push_back(*ValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003537 NameVals.push_back(Index.getModuleId(VS->modulePath()));
3538 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3539 for (auto &RI : VS->refs()) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003540 auto RefValueId = getValueId(RI.getGUID());
3541 if (!RefValueId)
3542 continue;
3543 NameVals.push_back(*RefValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003544 }
3545
Teresa Johnson403a7872015-10-04 14:33:43 +00003546 // Emit the finished record.
Teresa Johnson84174c32016-05-10 13:48:23 +00003547 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3548 FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003549 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003550 MaybeEmitOriginalName(*S);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003551 return;
Teresa Johnson403a7872015-10-04 14:33:43 +00003552 }
Teresa Johnson84174c32016-05-10 13:48:23 +00003553
3554 auto *FS = cast<FunctionSummary>(S);
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003555 writeFunctionTypeMetadataRecords(Stream, FS);
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00003556
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003557 NameVals.push_back(*ValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003558 NameVals.push_back(Index.getModuleId(FS->modulePath()));
3559 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3560 NameVals.push_back(FS->instCount());
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003561 // Fill in below
3562 NameVals.push_back(0);
Teresa Johnson84174c32016-05-10 13:48:23 +00003563
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003564 unsigned Count = 0;
Teresa Johnson84174c32016-05-10 13:48:23 +00003565 for (auto &RI : FS->refs()) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003566 auto RefValueId = getValueId(RI.getGUID());
3567 if (!RefValueId)
3568 continue;
3569 NameVals.push_back(*RefValueId);
3570 Count++;
Teresa Johnson84174c32016-05-10 13:48:23 +00003571 }
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003572 NameVals[4] = Count;
Teresa Johnson84174c32016-05-10 13:48:23 +00003573
3574 bool HasProfileData = false;
3575 for (auto &EI : FS->calls()) {
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003576 HasProfileData |= EI.second.Hotness != CalleeInfo::HotnessType::Unknown;
Teresa Johnson84174c32016-05-10 13:48:23 +00003577 if (HasProfileData)
3578 break;
3579 }
3580
3581 for (auto &EI : FS->calls()) {
3582 // If this GUID doesn't have a value id, it doesn't have a function
3583 // summary and we don't need to record any calls to it.
Dehao Chen4a435e02017-03-14 17:33:01 +00003584 GlobalValue::GUID GUID = EI.first.getGUID();
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003585 auto CallValueId = getValueId(GUID);
3586 if (!CallValueId) {
Dehao Chen4a435e02017-03-14 17:33:01 +00003587 // For SamplePGO, the indirect call targets for local functions will
3588 // have its original name annotated in profile. We try to find the
3589 // corresponding PGOFuncName as the GUID.
3590 GUID = Index.getGUIDFromOriginalID(GUID);
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003591 if (GUID == 0)
3592 continue;
3593 CallValueId = getValueId(GUID);
3594 if (!CallValueId)
Dehao Chen4a435e02017-03-14 17:33:01 +00003595 continue;
3596 }
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003597 NameVals.push_back(*CallValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003598 if (HasProfileData)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003599 NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
Teresa Johnson84174c32016-05-10 13:48:23 +00003600 }
3601
3602 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3603 unsigned Code =
3604 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3605
3606 // Emit the finished record.
3607 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3608 NameVals.clear();
3609 MaybeEmitOriginalName(*S);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003610 });
Teresa Johnson403a7872015-10-04 14:33:43 +00003611
Teresa Johnson28e457b2016-04-24 14:57:11 +00003612 for (auto *AS : Aliases) {
Teresa Johnson02e98332016-04-27 13:28:35 +00003613 auto AliasValueId = SummaryToValueIdMap[AS];
3614 assert(AliasValueId);
3615 NameVals.push_back(AliasValueId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003616 NameVals.push_back(Index.getModuleId(AS->modulePath()));
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003617 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
Teresa Johnson02e98332016-04-27 13:28:35 +00003618 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3619 assert(AliaseeValueId);
3620 NameVals.push_back(AliaseeValueId);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003621
3622 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003623 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003624 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003625 MaybeEmitOriginalName(*AS);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003626 }
3627
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00003628 if (!Index.cfiFunctionDefs().empty()) {
3629 for (auto &S : Index.cfiFunctionDefs()) {
3630 NameVals.push_back(StrtabBuilder.add(S));
3631 NameVals.push_back(S.size());
3632 }
3633 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
3634 NameVals.clear();
3635 }
3636
3637 if (!Index.cfiFunctionDecls().empty()) {
3638 for (auto &S : Index.cfiFunctionDecls()) {
3639 NameVals.push_back(StrtabBuilder.add(S));
3640 NameVals.push_back(S.size());
3641 }
3642 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
3643 NameVals.clear();
3644 }
3645
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003646 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003647}
3648
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003649/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3650/// current llvm version, and a record for the epoch number.
Benjamin Kramerefcf06f2017-02-11 11:06:55 +00003651static void writeIdentificationBlock(BitstreamWriter &Stream) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003652 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
Mehdi Amini5d303282015-10-26 18:37:00 +00003653
3654 // Write the "user readable" string identifying the bitcode producer
David Blaikie7ad9dc12017-01-04 22:36:33 +00003655 auto Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini5d303282015-10-26 18:37:00 +00003656 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3657 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3658 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003659 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003660 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
Teresa Johnson37687f32016-04-23 04:30:47 +00003661 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
Mehdi Amini5d303282015-10-26 18:37:00 +00003662
3663 // Write the epoch version
David Blaikie7ad9dc12017-01-04 22:36:33 +00003664 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini5d303282015-10-26 18:37:00 +00003665 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3666 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003667 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini5d303282015-10-26 18:37:00 +00003668 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003669 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3670 Stream.ExitBlock();
Mehdi Amini5d303282015-10-26 18:37:00 +00003671}
3672
Teresa Johnson37687f32016-04-23 04:30:47 +00003673void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003674 // Emit the module's hash.
3675 // MODULE_CODE_HASH: [5*i32]
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003676 if (GenerateHash) {
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003677 uint32_t Vals[5];
3678 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
3679 Buffer.size() - BlockStartPos));
3680 StringRef Hash = Hasher.result();
3681 for (int Pos = 0; Pos < 20; Pos += 4) {
3682 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
3683 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003684
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003685 // Emit the finished record.
3686 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
3687
3688 if (ModHash)
3689 // Save the written hash value.
3690 std::copy(std::begin(Vals), std::end(Vals), std::begin(*ModHash));
3691 } else if (ModHash)
3692 Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003693}
3694
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003695void ModuleBitcodeWriter::write() {
3696 writeIdentificationBlock(Stream);
Teresa Johnson37687f32016-04-23 04:30:47 +00003697
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003698 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3699 size_t BlockStartPos = Buffer.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003700
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003701 writeModuleVersion();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003702
3703 // Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00003704 writeBlockInfo();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003705
Bill Wendlingdc095552013-02-10 23:09:32 +00003706 // Emit information about attribute groups.
Teresa Johnson37687f32016-04-23 04:30:47 +00003707 writeAttributeGroupTable();
Bill Wendlingdc095552013-02-10 23:09:32 +00003708
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003709 // Emit information about parameter attributes.
Teresa Johnson37687f32016-04-23 04:30:47 +00003710 writeAttributeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003711
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003712 // Emit information describing all of the types in the module.
Teresa Johnson37687f32016-04-23 04:30:47 +00003713 writeTypeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003714
Teresa Johnson37687f32016-04-23 04:30:47 +00003715 writeComdats();
David Majnemerdad0a642014-06-27 18:19:56 +00003716
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003717 // Emit top-level description of module, including target triple, inline asm,
3718 // descriptors for global variables, and function prototype info.
Teresa Johnson37687f32016-04-23 04:30:47 +00003719 writeModuleInfo();
Devang Patel7428d8a2009-07-22 17:43:22 +00003720
Devang Patele059ba6e2009-07-23 01:07:34 +00003721 // Emit constants.
Teresa Johnson37687f32016-04-23 04:30:47 +00003722 writeModuleConstants();
Devang Patele059ba6e2009-07-23 01:07:34 +00003723
Peter Collingbourne21521892016-06-21 23:42:48 +00003724 // Emit metadata kind names.
3725 writeModuleMetadataKinds();
Devang Patel8cca7b42009-08-04 05:01:35 +00003726
Devang Patelaf206b82009-09-18 19:26:43 +00003727 // Emit metadata.
Peter Collingbourne21521892016-06-21 23:42:48 +00003728 writeModuleMetadata();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003729
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003730 // Emit module-level use-lists.
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00003731 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00003732 writeUseListBlock(nullptr);
Chad Rosierca2567b2011-12-07 21:44:12 +00003733
Teresa Johnson37687f32016-04-23 04:30:47 +00003734 writeOperandBundleTags();
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00003735 writeSyncScopeNames();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003736
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003737 // Emit function bodies.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003738 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003739 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003740 if (!F->isDeclaration())
Teresa Johnson37687f32016-04-23 04:30:47 +00003741 writeFunction(*F, FunctionToBitcodeIndex);
Teresa Johnson403a7872015-10-04 14:33:43 +00003742
3743 // Need to write after the above call to WriteFunction which populates
3744 // the summary information in the index.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003745 if (Index)
Teresa Johnson37687f32016-04-23 04:30:47 +00003746 writePerModuleGlobalValueSummary();
Teresa Johnsonff642b92015-09-17 20:12:00 +00003747
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003748 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003749
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003750 writeModuleHash(BlockStartPos);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003751
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003752 Stream.ExitBlock();
Chris Lattner702658c2007-05-04 18:26:27 +00003753}
3754
Teresa Johnson37687f32016-04-23 04:30:47 +00003755static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3756 uint32_t &Position) {
3757 support::endian::write32le(&Buffer[Position], Value);
3758 Position += 4;
3759}
3760
3761/// If generating a bc file on darwin, we have to emit a
Chris Lattnera660f4b2008-07-09 05:14:23 +00003762/// header and trailer to make it compatible with the system archiver. To do
3763/// this we emit the following header, and then emit a trailer that pads the
3764/// file out to be a multiple of 16 bytes.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003765///
Chris Lattnera660f4b2008-07-09 05:14:23 +00003766/// struct bc_header {
3767/// uint32_t Magic; // 0x0B17C0DE
3768/// uint32_t Version; // Version, currently always 0.
3769/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3770/// uint32_t BitcodeSize; // Size of traditional bitcode file.
3771/// uint32_t CPUType; // CPU specifier.
3772/// ... potentially more later ...
3773/// };
Teresa Johnson37687f32016-04-23 04:30:47 +00003774static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003775 const Triple &TT) {
Chris Lattnera660f4b2008-07-09 05:14:23 +00003776 unsigned CPUType = ~0U;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003777
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003778 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
Evan Cheng545d3602010-02-12 20:39:35 +00003779 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3780 // number from /usr/include/mach/machine.h. It is ok to reproduce the
3781 // specific constants here because they are implicitly part of the Darwin ABI.
Chris Lattnera660f4b2008-07-09 05:14:23 +00003782 enum {
3783 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
3784 DARWIN_CPU_TYPE_X86 = 7,
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003785 DARWIN_CPU_TYPE_ARM = 12,
Chris Lattnera660f4b2008-07-09 05:14:23 +00003786 DARWIN_CPU_TYPE_POWERPC = 18
3787 };
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003788
Evan Chengcffdcae2011-06-14 01:51:33 +00003789 Triple::ArchType Arch = TT.getArch();
3790 if (Arch == Triple::x86_64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003791 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00003792 else if (Arch == Triple::x86)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003793 CPUType = DARWIN_CPU_TYPE_X86;
Evan Chengcffdcae2011-06-14 01:51:33 +00003794 else if (Arch == Triple::ppc)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003795 CPUType = DARWIN_CPU_TYPE_POWERPC;
Evan Chengcffdcae2011-06-14 01:51:33 +00003796 else if (Arch == Triple::ppc64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003797 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00003798 else if (Arch == Triple::arm || Arch == Triple::thumb)
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003799 CPUType = DARWIN_CPU_TYPE_ARM;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003800
Chris Lattnera660f4b2008-07-09 05:14:23 +00003801 // Traditional Bitcode starts after header.
Akira Hatanaka4f472a882016-01-29 05:55:09 +00003802 assert(Buffer.size() >= BWH_HeaderSize &&
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003803 "Expected header size to be reserved");
Akira Hatanaka4f472a882016-01-29 05:55:09 +00003804 unsigned BCOffset = BWH_HeaderSize;
3805 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003806
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003807 // Write the magic and version.
3808 unsigned Position = 0;
Teresa Johnson37687f32016-04-23 04:30:47 +00003809 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
3810 writeInt32ToBuffer(0, Buffer, Position); // Version.
3811 writeInt32ToBuffer(BCOffset, Buffer, Position);
3812 writeInt32ToBuffer(BCSize, Buffer, Position);
3813 writeInt32ToBuffer(CPUType, Buffer, Position);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003814
Chris Lattnera660f4b2008-07-09 05:14:23 +00003815 // If the file is not a multiple of 16 bytes, insert dummy padding.
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003816 while (Buffer.size() & 15)
3817 Buffer.push_back(0);
Chris Lattnera660f4b2008-07-09 05:14:23 +00003818}
3819
Teresa Johnson403a7872015-10-04 14:33:43 +00003820/// Helper to write the header common to all bitcode files.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003821static void writeBitcodeHeader(BitstreamWriter &Stream) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003822 // Emit the file header.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003823 Stream.Emit((unsigned)'B', 8);
3824 Stream.Emit((unsigned)'C', 8);
3825 Stream.Emit(0x0, 4);
3826 Stream.Emit(0xC, 4);
3827 Stream.Emit(0xE, 4);
3828 Stream.Emit(0xD, 4);
Teresa Johnson403a7872015-10-04 14:33:43 +00003829}
3830
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003831BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
3832 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
3833 writeBitcodeHeader(*Stream);
3834}
3835
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003836BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
3837
3838void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
3839 Stream->EnterSubblock(Block, 3);
3840
3841 auto Abbv = std::make_shared<BitCodeAbbrev>();
3842 Abbv->Add(BitCodeAbbrevOp(Record));
3843 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3844 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
3845
3846 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
3847
3848 Stream->ExitBlock();
3849}
3850
Peter Collingbourne92648c22017-06-27 23:50:11 +00003851void BitcodeWriter::writeSymtab() {
3852 assert(!WroteStrtab && !WroteSymtab);
3853
3854 // If any module has module-level inline asm, we will require a registered asm
3855 // parser for the target so that we can create an accurate symbol table for
3856 // the module.
3857 for (Module *M : Mods) {
3858 if (M->getModuleInlineAsm().empty())
3859 continue;
3860
3861 std::string Err;
3862 const Triple TT(M->getTargetTriple());
3863 const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
3864 if (!T || !T->hasMCAsmParser())
3865 return;
3866 }
3867
3868 WroteSymtab = true;
3869 SmallVector<char, 0> Symtab;
3870 // The irsymtab::build function may be unable to create a symbol table if the
3871 // module is malformed (e.g. it contains an invalid alias). Writing a symbol
3872 // table is not required for correctness, but we still want to be able to
3873 // write malformed modules to bitcode files, so swallow the error.
3874 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
3875 consumeError(std::move(E));
3876 return;
3877 }
3878
3879 writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
3880 {Symtab.data(), Symtab.size()});
3881}
3882
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003883void BitcodeWriter::writeStrtab() {
3884 assert(!WroteStrtab);
3885
3886 std::vector<char> Strtab;
3887 StrtabBuilder.finalizeInOrder();
3888 Strtab.resize(StrtabBuilder.getSize());
3889 StrtabBuilder.write((uint8_t *)Strtab.data());
3890
3891 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
3892 {Strtab.data(), Strtab.size()});
3893
3894 WroteStrtab = true;
3895}
3896
3897void BitcodeWriter::copyStrtab(StringRef Strtab) {
3898 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
3899 WroteStrtab = true;
3900}
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003901
3902void BitcodeWriter::writeModule(const Module *M,
3903 bool ShouldPreserveUseListOrder,
3904 const ModuleSummaryIndex *Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003905 bool GenerateHash, ModuleHash *ModHash) {
Peter Collingbourne92648c22017-06-27 23:50:11 +00003906 assert(!WroteStrtab);
3907
3908 // The Mods vector is used by irsymtab::build, which requires non-const
3909 // Modules in case it needs to materialize metadata. But the bitcode writer
3910 // requires that the module is materialized, so we can cast to non-const here,
3911 // after checking that it is in fact materialized.
3912 assert(M->isMaterialized());
3913 Mods.push_back(const_cast<Module *>(M));
3914
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003915 ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003916 ShouldPreserveUseListOrder, Index,
3917 GenerateHash, ModHash);
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003918 ModuleWriter.write();
3919}
3920
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00003921void BitcodeWriter::writeIndex(
3922 const ModuleSummaryIndex *Index,
3923 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
3924 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
3925 ModuleToSummariesForIndex);
3926 IndexWriter.write();
3927}
3928
Chris Lattnerc1d10d62007-04-22 06:24:45 +00003929/// WriteBitcodeToFile - Write the specified module to the specified output
3930/// stream.
Duncan P. N. Exon Smitha052ed62015-04-15 00:10:50 +00003931void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
Teresa Johnson403a7872015-10-04 14:33:43 +00003932 bool ShouldPreserveUseListOrder,
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003933 const ModuleSummaryIndex *Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003934 bool GenerateHash, ModuleHash *ModHash) {
Michael Ilsemane26658d2012-12-03 21:29:36 +00003935 SmallVector<char, 0> Buffer;
Chris Lattnerc1d10d62007-04-22 06:24:45 +00003936 Buffer.reserve(256*1024);
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00003937
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003938 // If this is darwin or another generic macho target, reserve space for the
3939 // header.
3940 Triple TT(M->getTargetTriple());
Akira Hatanaka1235d282016-01-23 16:02:10 +00003941 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Akira Hatanaka4f472a882016-01-29 05:55:09 +00003942 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003943
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003944 BitcodeWriter Writer(Buffer);
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003945 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
3946 ModHash);
Peter Collingbourne92648c22017-06-27 23:50:11 +00003947 Writer.writeSymtab();
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003948 Writer.writeStrtab();
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003949
Akira Hatanaka1235d282016-01-23 16:02:10 +00003950 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Teresa Johnson37687f32016-04-23 04:30:47 +00003951 emitDarwinBCHeaderAndTrailer(Buffer, TT);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003952
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00003953 // Write the generated bitstream to "Out".
3954 Out.write((char*)&Buffer.front(), Buffer.size());
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00003955}
Teresa Johnson403a7872015-10-04 14:33:43 +00003956
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003957void IndexBitcodeWriter::write() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003958 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
Teresa Johnson37687f32016-04-23 04:30:47 +00003959
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003960 writeModuleVersion();
Teresa Johnson37687f32016-04-23 04:30:47 +00003961
3962 // Write the module paths in the combined index.
3963 writeModStrings();
3964
3965 // Write the summary combined index records.
3966 writeCombinedGlobalValueSummary();
3967
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003968 Stream.ExitBlock();
Teresa Johnson37687f32016-04-23 04:30:47 +00003969}
3970
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003971// Write the specified module summary index to the given raw output stream,
Teresa Johnson403a7872015-10-04 14:33:43 +00003972// where it will be written in a new bitcode block. This is used when
Teresa Johnson84174c32016-05-10 13:48:23 +00003973// writing the combined index file for ThinLTO. When writing a subset of the
3974// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
3975void llvm::WriteIndexToFile(
3976 const ModuleSummaryIndex &Index, raw_ostream &Out,
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +00003977 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003978 SmallVector<char, 0> Buffer;
3979 Buffer.reserve(256 * 1024);
3980
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00003981 BitcodeWriter Writer(Buffer);
3982 Writer.writeIndex(&Index, ModuleToSummariesForIndex);
3983 Writer.writeStrtab();
Teresa Johnson403a7872015-10-04 14:33:43 +00003984
3985 Out.write((char *)&Buffer.front(), Buffer.size());
3986}