blob: 1b8d81a6020165a2ff125ea1c824321f1aa37bd4 [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"
Torok Edwin56d06592009-07-11 20:10:48 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattnerc1d10d62007-04-22 06:24:45 +000033#include "llvm/Support/MathExtras.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000034#include "llvm/Support/Program.h"
Mehdi Aminid7ad2212016-04-01 05:33:11 +000035#include "llvm/Support/SHA1.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000036#include "llvm/Support/raw_ostream.h"
Nick Lewycky0de20af2010-12-19 20:43:38 +000037#include <cctype>
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000038#include <map>
Chris Lattnerc1d10d62007-04-22 06:24:45 +000039using namespace llvm;
40
Benjamin Kramera65b6102016-05-15 15:18:11 +000041namespace {
Mehdi Aminie98f9252016-12-28 22:30:28 +000042
43cl::opt<unsigned>
44 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
45 cl::desc("Number of metadatas above which we emit an index "
46 "to enable lazy-loading"));
Chris Lattner4d925982007-05-04 20:52:02 +000047/// These are manifest constants used by the bitcode writer. They do not need to
48/// be kept in sync with the reader, but need to be consistent within this file.
49enum {
Chris Lattner4d925982007-05-04 20:52:02 +000050 // VALUE_SYMTAB_BLOCK abbrev id's.
51 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
Chris Lattnerfd1ad102007-05-04 20:58:35 +000052 VST_ENTRY_7_ABBREV,
Chris Lattnere760d6f2007-05-05 01:26:50 +000053 VST_ENTRY_6_ABBREV,
Chris Lattnerda5e5d22007-05-05 07:36:14 +000054 VST_BBENTRY_6_ABBREV,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000055
Chris Lattnerda5e5d22007-05-05 07:36:14 +000056 // CONSTANTS_BLOCK abbrev id's.
57 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
58 CONSTANTS_INTEGER_ABBREV,
59 CONSTANTS_CE_CAST_Abbrev,
Chris Lattnerb80751d2007-05-05 07:44:49 +000060 CONSTANTS_NULL_Abbrev,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000061
Chris Lattnerb80751d2007-05-05 07:44:49 +000062 // FUNCTION_BLOCK abbrev id's.
Chris Lattnercc6d4c92007-05-06 01:28:01 +000063 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
Chris Lattnerc67e6d92007-05-06 02:38:57 +000064 FUNCTION_INST_BINOP_ABBREV,
Dan Gohman0ebd6962009-07-20 21:19:07 +000065 FUNCTION_INST_BINOP_FLAGS_ABBREV,
Chris Lattnerc67e6d92007-05-06 02:38:57 +000066 FUNCTION_INST_CAST_ABBREV,
Chris Lattnercc6d4c92007-05-06 01:28:01 +000067 FUNCTION_INST_RET_VOID_ABBREV,
68 FUNCTION_INST_RET_VAL_ABBREV,
David Blaikieb5b5efd2015-02-25 01:08:52 +000069 FUNCTION_INST_UNREACHABLE_ABBREV,
70 FUNCTION_INST_GEP_ABBREV,
Chris Lattner4d925982007-05-04 20:52:02 +000071};
72
Teresa Johnsonc814e0c2016-04-23 04:31:20 +000073/// Abstract class to manage the bitcode writing, subclassed for each bitcode
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +000074/// file type.
75class BitcodeWriterBase {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +000076protected:
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +000077 /// The stream created and owned by the client.
78 BitstreamWriter &Stream;
Teresa Johnson37687f32016-04-23 04:30:47 +000079
Teresa Johnson37687f32016-04-23 04:30:47 +000080public:
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +000081 /// Constructs a BitcodeWriterBase object that writes to the provided
82 /// \p Stream.
83 BitcodeWriterBase(BitstreamWriter &Stream) : Stream(Stream) {}
Teresa Johnson37687f32016-04-23 04:30:47 +000084
85protected:
Teresa Johnson37687f32016-04-23 04:30:47 +000086 void writeBitcodeHeader();
Peter Collingbournea0f371a2017-04-17 17:51:36 +000087 void writeModuleVersion();
Teresa Johnson37687f32016-04-23 04:30:47 +000088};
89
Peter Collingbournea0f371a2017-04-17 17:51:36 +000090void BitcodeWriterBase::writeModuleVersion() {
91 // VERSION: [version#]
92 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
93}
94
Teresa Johnson37687f32016-04-23 04:30:47 +000095/// Class to manage the bitcode writing for a module.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +000096class ModuleBitcodeWriter : public BitcodeWriterBase {
97 /// Pointer to the buffer allocated by caller for bitcode writing.
98 const SmallVectorImpl<char> &Buffer;
99
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000100 StringTableBuilder &StrtabBuilder;
101
Teresa Johnson37687f32016-04-23 04:30:47 +0000102 /// The Module to write to bitcode.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000103 const Module &M;
Teresa Johnson37687f32016-04-23 04:30:47 +0000104
105 /// Enumerates ids for all values in the module.
106 ValueEnumerator VE;
107
108 /// Optional per-module index to write for ThinLTO.
109 const ModuleSummaryIndex *Index;
110
111 /// True if a module hash record should be written.
112 bool GenerateHash;
113
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000114 /// If non-null, when GenerateHash is true, the resulting hash is written
115 /// into ModHash. When GenerateHash is false, that specified value
116 /// is used as the hash instead of computing from the generated bitcode.
117 /// Can be used to produce the same module hash for a minimized bitcode
118 /// used just for the thin link as in the regular full bitcode that will
119 /// be used in the backend.
120 ModuleHash *ModHash;
121
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000122 /// The start bit of the identification block.
123 uint64_t BitcodeStartBit;
Teresa Johnson37687f32016-04-23 04:30:47 +0000124
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000125 /// Map that holds the correspondence between GUIDs in the summary index,
126 /// that came from indirect call profiles, and a value id generated by this
127 /// class to use in the VST and summary block records.
128 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
129
130 /// Tracks the last value id recorded in the GUIDToValueMap.
131 unsigned GlobalValueId;
132
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000133 /// Saves the offset of the VSTOffset record that must eventually be
134 /// backpatched with the offset of the actual VST.
135 uint64_t VSTOffsetPlaceholder = 0;
136
Teresa Johnson37687f32016-04-23 04:30:47 +0000137public:
138 /// Constructs a ModuleBitcodeWriter object for the given Module,
139 /// writing to the provided \p Buffer.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000140 ModuleBitcodeWriter(const Module *M, SmallVectorImpl<char> &Buffer,
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000141 StringTableBuilder &StrtabBuilder,
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000142 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000143 const ModuleSummaryIndex *Index, bool GenerateHash,
144 ModuleHash *ModHash = nullptr)
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000145 : BitcodeWriterBase(Stream), Buffer(Buffer), StrtabBuilder(StrtabBuilder),
146 M(*M), VE(*M, ShouldPreserveUseListOrder), Index(Index),
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000147 GenerateHash(GenerateHash), ModHash(ModHash),
148 BitcodeStartBit(Stream.GetCurrentBitNo()) {
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000149 // Assign ValueIds to any callee values in the index that came from
150 // indirect call profiles and were recorded as a GUID not a Value*
151 // (which would have been assigned an ID by the ValueEnumerator).
152 // The starting ValueId is just after the number of values in the
153 // ValueEnumerator, so that they can be emitted in the VST.
154 GlobalValueId = VE.getValues().size();
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000155 if (!Index)
156 return;
157 for (const auto &GUIDSummaryLists : *Index)
158 // Examine all summaries for this GUID.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000159 for (auto &Summary : GUIDSummaryLists.second.SummaryList)
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000160 if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
161 // For each call in the function summary, see if the call
162 // is to a GUID (which means it is for an indirect call,
163 // otherwise we would have a Value for it). If so, synthesize
164 // a value id.
165 for (auto &CallEdge : FS->calls())
Peter Collingbourne9667b912017-05-04 18:03:25 +0000166 if (!CallEdge.first.getValue())
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000167 assignValueId(CallEdge.first.getGUID());
Teresa Johnson37687f32016-04-23 04:30:47 +0000168 }
169
Teresa Johnson37687f32016-04-23 04:30:47 +0000170 /// Emit the current module to the bitstream.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000171 void write();
Teresa Johnson37687f32016-04-23 04:30:47 +0000172
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000173private:
Teresa Johnson37687f32016-04-23 04:30:47 +0000174 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
175
Teresa Johnson37687f32016-04-23 04:30:47 +0000176 void writeAttributeGroupTable();
177 void writeAttributeTable();
178 void writeTypeTable();
179 void writeComdats();
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000180 void writeValueSymbolTableForwardDecl();
Teresa Johnson37687f32016-04-23 04:30:47 +0000181 void writeModuleInfo();
182 void writeValueAsMetadata(const ValueAsMetadata *MD,
183 SmallVectorImpl<uint64_t> &Record);
184 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
185 unsigned Abbrev);
186 unsigned createDILocationAbbrev();
187 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
188 unsigned &Abbrev);
189 unsigned createGenericDINodeAbbrev();
190 void writeGenericDINode(const GenericDINode *N,
191 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
192 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
193 unsigned Abbrev);
194 void writeDIEnumerator(const DIEnumerator *N,
195 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
196 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
197 unsigned Abbrev);
198 void writeDIDerivedType(const DIDerivedType *N,
199 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
200 void writeDICompositeType(const DICompositeType *N,
201 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
202 void writeDISubroutineType(const DISubroutineType *N,
203 SmallVectorImpl<uint64_t> &Record,
204 unsigned Abbrev);
205 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
206 unsigned Abbrev);
207 void writeDICompileUnit(const DICompileUnit *N,
208 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
209 void writeDISubprogram(const DISubprogram *N,
210 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
211 void writeDILexicalBlock(const DILexicalBlock *N,
212 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
213 void writeDILexicalBlockFile(const DILexicalBlockFile *N,
214 SmallVectorImpl<uint64_t> &Record,
215 unsigned Abbrev);
216 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
217 unsigned Abbrev);
218 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
219 unsigned Abbrev);
220 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
221 unsigned Abbrev);
222 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
223 unsigned Abbrev);
224 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
225 SmallVectorImpl<uint64_t> &Record,
226 unsigned Abbrev);
227 void writeDITemplateValueParameter(const DITemplateValueParameter *N,
228 SmallVectorImpl<uint64_t> &Record,
229 unsigned Abbrev);
230 void writeDIGlobalVariable(const DIGlobalVariable *N,
231 SmallVectorImpl<uint64_t> &Record,
232 unsigned Abbrev);
233 void writeDILocalVariable(const DILocalVariable *N,
234 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
235 void writeDIExpression(const DIExpression *N,
236 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000237 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
238 SmallVectorImpl<uint64_t> &Record,
239 unsigned Abbrev);
Teresa Johnson37687f32016-04-23 04:30:47 +0000240 void writeDIObjCProperty(const DIObjCProperty *N,
241 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
242 void writeDIImportedEntity(const DIImportedEntity *N,
243 SmallVectorImpl<uint64_t> &Record,
244 unsigned Abbrev);
245 unsigned createNamedMetadataAbbrev();
246 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
247 unsigned createMetadataStringsAbbrev();
248 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
249 SmallVectorImpl<uint64_t> &Record);
250 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
Mehdi Aminie98f9252016-12-28 22:30:28 +0000251 SmallVectorImpl<uint64_t> &Record,
252 std::vector<unsigned> *MDAbbrevs = nullptr,
253 std::vector<uint64_t> *IndexPos = nullptr);
Teresa Johnson37687f32016-04-23 04:30:47 +0000254 void writeModuleMetadata();
255 void writeFunctionMetadata(const Function &F);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000256 void writeFunctionMetadataAttachment(const Function &F);
257 void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
258 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
259 const GlobalObject &GO);
Peter Collingbourne21521892016-06-21 23:42:48 +0000260 void writeModuleMetadataKinds();
Teresa Johnson37687f32016-04-23 04:30:47 +0000261 void writeOperandBundleTags();
262 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
263 void writeModuleConstants();
264 bool pushValueAndType(const Value *V, unsigned InstID,
265 SmallVectorImpl<unsigned> &Vals);
266 void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
267 void pushValue(const Value *V, unsigned InstID,
268 SmallVectorImpl<unsigned> &Vals);
269 void pushValueSigned(const Value *V, unsigned InstID,
270 SmallVectorImpl<uint64_t> &Vals);
271 void writeInstruction(const Instruction &I, unsigned InstID,
272 SmallVectorImpl<unsigned> &Vals);
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000273 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
274 void writeGlobalValueSymbolTable(
275 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
Teresa Johnson37687f32016-04-23 04:30:47 +0000276 void writeUseList(UseListOrder &&Order);
277 void writeUseListBlock(const Function *F);
278 void
279 writeFunction(const Function &F,
280 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
281 void writeBlockInfo();
282 void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
Teresa Johnson28e457b2016-04-24 14:57:11 +0000283 GlobalValueSummary *Summary,
Teresa Johnson37687f32016-04-23 04:30:47 +0000284 unsigned ValueID,
285 unsigned FSCallsAbbrev,
286 unsigned FSCallsProfileAbbrev,
287 const Function &F);
288 void writeModuleLevelReferences(const GlobalVariable &V,
289 SmallVector<uint64_t, 64> &NameVals,
290 unsigned FSModRefsAbbrev);
291 void writePerModuleGlobalValueSummary();
292 void writeModuleHash(size_t BlockStartPos);
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000293
294 void assignValueId(GlobalValue::GUID ValGUID) {
295 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
296 }
297 unsigned getValueId(GlobalValue::GUID ValGUID) {
298 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000299 // Expect that any GUID value had a value Id assigned by an
300 // earlier call to assignValueId.
301 assert(VMI != GUIDToValueIdMap.end() &&
302 "GUID does not have assigned value Id");
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000303 return VMI->second;
304 }
305 // Helper to get the valueId for the type of value recorded in VI.
306 unsigned getValueId(ValueInfo VI) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000307 if (!VI.getValue())
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000308 return getValueId(VI.getGUID());
309 return VE.getValueID(VI.getValue());
310 }
311 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
Teresa Johnson37687f32016-04-23 04:30:47 +0000312};
313
314/// Class to manage the bitcode writing for a combined index.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000315class IndexBitcodeWriter : public BitcodeWriterBase {
Teresa Johnson37687f32016-04-23 04:30:47 +0000316 /// The combined index to write to bitcode.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000317 const ModuleSummaryIndex &Index;
Teresa Johnson37687f32016-04-23 04:30:47 +0000318
Teresa Johnson84174c32016-05-10 13:48:23 +0000319 /// When writing a subset of the index for distributed backends, client
320 /// provides a map of modules to the corresponding GUIDs/summaries to write.
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +0000321 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
Teresa Johnson84174c32016-05-10 13:48:23 +0000322
Teresa Johnson37687f32016-04-23 04:30:47 +0000323 /// Map that holds the correspondence between the GUID used in the combined
324 /// index and a value id generated by this class to use in references.
325 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
326
327 /// Tracks the last value id recorded in the GUIDToValueMap.
328 unsigned GlobalValueId = 0;
329
330public:
331 /// Constructs a IndexBitcodeWriter object for the given combined index,
Teresa Johnson84174c32016-05-10 13:48:23 +0000332 /// writing to the provided \p Buffer. When writing a subset of the index
333 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000334 IndexBitcodeWriter(BitstreamWriter &Stream, const ModuleSummaryIndex &Index,
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +0000335 const std::map<std::string, GVSummaryMapTy>
Teresa Johnson84174c32016-05-10 13:48:23 +0000336 *ModuleToSummariesForIndex = nullptr)
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000337 : BitcodeWriterBase(Stream), Index(Index),
Teresa Johnson84174c32016-05-10 13:48:23 +0000338 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
339 // Assign unique value ids to all summaries to be written, for use
Teresa Johnson37687f32016-04-23 04:30:47 +0000340 // in writing out the call graph edges. Save the mapping from GUID
341 // to the new global value id to use when writing those edges, which
342 // are currently saved in the index in terms of GUID.
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000343 forEachSummary([&](GVInfo I) {
Teresa Johnson84174c32016-05-10 13:48:23 +0000344 GUIDToValueIdMap[I.first] = ++GlobalValueId;
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000345 });
Teresa Johnson37687f32016-04-23 04:30:47 +0000346 }
347
Teresa Johnson84174c32016-05-10 13:48:23 +0000348 /// The below iterator returns the GUID and associated summary.
349 typedef std::pair<GlobalValue::GUID, GlobalValueSummary *> GVInfo;
350
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000351 /// Calls the callback for each value GUID and summary to be written to
352 /// bitcode. This hides the details of whether they are being pulled from the
353 /// entire index or just those in a provided ModuleToSummariesForIndex map.
354 void forEachSummary(std::function<void(GVInfo)> Callback) {
355 if (ModuleToSummariesForIndex) {
356 for (auto &M : *ModuleToSummariesForIndex)
357 for (auto &Summary : M.second)
358 Callback(Summary);
359 } else {
360 for (auto &Summaries : Index)
Peter Collingbourne9667b912017-05-04 18:03:25 +0000361 for (auto &Summary : Summaries.second.SummaryList)
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000362 Callback({Summaries.first, Summary.get()});
Teresa Johnson84174c32016-05-10 13:48:23 +0000363 }
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000364 }
Teresa Johnson84174c32016-05-10 13:48:23 +0000365
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000366 /// Main entry point for writing a combined index to bitcode.
367 void write();
Teresa Johnson37687f32016-04-23 04:30:47 +0000368
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000369private:
Teresa Johnson37687f32016-04-23 04:30:47 +0000370 void writeModStrings();
Teresa Johnson37687f32016-04-23 04:30:47 +0000371 void writeCombinedGlobalValueSummary();
372
Teresa Johnson84174c32016-05-10 13:48:23 +0000373 /// Indicates whether the provided \p ModulePath should be written into
374 /// the module string table, e.g. if full index written or if it is in
375 /// the provided subset.
376 bool doIncludeModule(StringRef ModulePath) {
377 return !ModuleToSummariesForIndex ||
378 ModuleToSummariesForIndex->count(ModulePath);
379 }
380
Teresa Johnson37687f32016-04-23 04:30:47 +0000381 bool hasValueId(GlobalValue::GUID ValGUID) {
382 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
383 return VMI != GUIDToValueIdMap.end();
384 }
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000385 void assignValueId(GlobalValue::GUID ValGUID) {
386 unsigned &ValueId = GUIDToValueIdMap[ValGUID];
387 if (ValueId == 0)
388 ValueId = ++GlobalValueId;
389 }
Teresa Johnson37687f32016-04-23 04:30:47 +0000390 unsigned getValueId(GlobalValue::GUID ValGUID) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000391 auto VMI = GUIDToValueIdMap.find(ValGUID);
392 assert(VMI != GUIDToValueIdMap.end());
393 return VMI->second;
Teresa Johnson37687f32016-04-23 04:30:47 +0000394 }
Teresa Johnson37687f32016-04-23 04:30:47 +0000395 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
396};
Benjamin Kramera65b6102016-05-15 15:18:11 +0000397} // end anonymous namespace
Teresa Johnson37687f32016-04-23 04:30:47 +0000398
399static unsigned getEncodedCastOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000400 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000401 default: llvm_unreachable("Unknown cast instruction!");
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000402 case Instruction::Trunc : return bitc::CAST_TRUNC;
403 case Instruction::ZExt : return bitc::CAST_ZEXT;
404 case Instruction::SExt : return bitc::CAST_SEXT;
405 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
406 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
407 case Instruction::UIToFP : return bitc::CAST_UITOFP;
408 case Instruction::SIToFP : return bitc::CAST_SITOFP;
409 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
410 case Instruction::FPExt : return bitc::CAST_FPEXT;
411 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
412 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
413 case Instruction::BitCast : return bitc::CAST_BITCAST;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000414 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000415 }
416}
417
Teresa Johnson37687f32016-04-23 04:30:47 +0000418static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000419 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000420 default: llvm_unreachable("Unknown binary instruction!");
Dan Gohmana5b96452009-06-04 22:49:04 +0000421 case Instruction::Add:
422 case Instruction::FAdd: return bitc::BINOP_ADD;
423 case Instruction::Sub:
424 case Instruction::FSub: return bitc::BINOP_SUB;
425 case Instruction::Mul:
426 case Instruction::FMul: return bitc::BINOP_MUL;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000427 case Instruction::UDiv: return bitc::BINOP_UDIV;
428 case Instruction::FDiv:
429 case Instruction::SDiv: return bitc::BINOP_SDIV;
430 case Instruction::URem: return bitc::BINOP_UREM;
431 case Instruction::FRem:
432 case Instruction::SRem: return bitc::BINOP_SREM;
433 case Instruction::Shl: return bitc::BINOP_SHL;
434 case Instruction::LShr: return bitc::BINOP_LSHR;
435 case Instruction::AShr: return bitc::BINOP_ASHR;
436 case Instruction::And: return bitc::BINOP_AND;
437 case Instruction::Or: return bitc::BINOP_OR;
438 case Instruction::Xor: return bitc::BINOP_XOR;
439 }
440}
441
Teresa Johnson37687f32016-04-23 04:30:47 +0000442static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000443 switch (Op) {
444 default: llvm_unreachable("Unknown RMW operation!");
445 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
446 case AtomicRMWInst::Add: return bitc::RMW_ADD;
447 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
448 case AtomicRMWInst::And: return bitc::RMW_AND;
449 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
450 case AtomicRMWInst::Or: return bitc::RMW_OR;
451 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
452 case AtomicRMWInst::Max: return bitc::RMW_MAX;
453 case AtomicRMWInst::Min: return bitc::RMW_MIN;
454 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
455 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
456 }
457}
458
Teresa Johnson37687f32016-04-23 04:30:47 +0000459static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000460 switch (Ordering) {
JF Bastien800f87a2016-04-06 21:19:33 +0000461 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
462 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
463 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
464 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
465 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
466 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
467 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000468 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000469 llvm_unreachable("Invalid ordering");
Eli Friedmanfee02c62011-07-25 23:16:38 +0000470}
471
Teresa Johnson37687f32016-04-23 04:30:47 +0000472static unsigned getEncodedSynchScope(SynchronizationScope SynchScope) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000473 switch (SynchScope) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000474 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
475 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
476 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000477 llvm_unreachable("Invalid synch scope");
Eli Friedmanfee02c62011-07-25 23:16:38 +0000478}
479
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000480static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
481 StringRef Str, unsigned AbbrevToUse) {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000482 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000483
Chris Lattnere14cb882007-05-04 19:11:41 +0000484 // Code: [strchar x N]
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000485 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
486 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
487 AbbrevToUse = 0;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000488 Vals.push_back(Str[i]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000489 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000490
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000491 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000492 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000493}
494
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000495static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
496 switch (Kind) {
497 case Attribute::Alignment:
498 return bitc::ATTR_KIND_ALIGNMENT;
George Burgess IV278199f2016-04-12 01:05:35 +0000499 case Attribute::AllocSize:
500 return bitc::ATTR_KIND_ALLOC_SIZE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000501 case Attribute::AlwaysInline:
502 return bitc::ATTR_KIND_ALWAYS_INLINE;
Igor Laevsky39d662f2015-07-11 10:30:36 +0000503 case Attribute::ArgMemOnly:
504 return bitc::ATTR_KIND_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000505 case Attribute::Builtin:
506 return bitc::ATTR_KIND_BUILTIN;
507 case Attribute::ByVal:
508 return bitc::ATTR_KIND_BY_VAL;
Owen Anderson85fa7d52015-05-26 23:48:40 +0000509 case Attribute::Convergent:
510 return bitc::ATTR_KIND_CONVERGENT;
Reid Klecknera534a382013-12-19 02:14:12 +0000511 case Attribute::InAlloca:
512 return bitc::ATTR_KIND_IN_ALLOCA;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000513 case Attribute::Cold:
514 return bitc::ATTR_KIND_COLD;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +0000515 case Attribute::InaccessibleMemOnly:
516 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
517 case Attribute::InaccessibleMemOrArgMemOnly:
518 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000519 case Attribute::InlineHint:
520 return bitc::ATTR_KIND_INLINE_HINT;
521 case Attribute::InReg:
522 return bitc::ATTR_KIND_IN_REG;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000523 case Attribute::JumpTable:
524 return bitc::ATTR_KIND_JUMP_TABLE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000525 case Attribute::MinSize:
526 return bitc::ATTR_KIND_MIN_SIZE;
527 case Attribute::Naked:
528 return bitc::ATTR_KIND_NAKED;
529 case Attribute::Nest:
530 return bitc::ATTR_KIND_NEST;
531 case Attribute::NoAlias:
532 return bitc::ATTR_KIND_NO_ALIAS;
533 case Attribute::NoBuiltin:
534 return bitc::ATTR_KIND_NO_BUILTIN;
535 case Attribute::NoCapture:
536 return bitc::ATTR_KIND_NO_CAPTURE;
537 case Attribute::NoDuplicate:
538 return bitc::ATTR_KIND_NO_DUPLICATE;
539 case Attribute::NoImplicitFloat:
540 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
541 case Attribute::NoInline:
542 return bitc::ATTR_KIND_NO_INLINE;
James Molloye6f87ca2015-11-06 10:32:53 +0000543 case Attribute::NoRecurse:
544 return bitc::ATTR_KIND_NO_RECURSE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000545 case Attribute::NonLazyBind:
546 return bitc::ATTR_KIND_NON_LAZY_BIND;
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000547 case Attribute::NonNull:
548 return bitc::ATTR_KIND_NON_NULL;
Hal Finkelb0407ba2014-07-18 15:51:28 +0000549 case Attribute::Dereferenceable:
550 return bitc::ATTR_KIND_DEREFERENCEABLE;
Sanjoy Das31ea6d12015-04-16 20:29:50 +0000551 case Attribute::DereferenceableOrNull:
552 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000553 case Attribute::NoRedZone:
554 return bitc::ATTR_KIND_NO_RED_ZONE;
555 case Attribute::NoReturn:
556 return bitc::ATTR_KIND_NO_RETURN;
557 case Attribute::NoUnwind:
558 return bitc::ATTR_KIND_NO_UNWIND;
559 case Attribute::OptimizeForSize:
560 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000561 case Attribute::OptimizeNone:
562 return bitc::ATTR_KIND_OPTIMIZE_NONE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000563 case Attribute::ReadNone:
564 return bitc::ATTR_KIND_READ_NONE;
565 case Attribute::ReadOnly:
566 return bitc::ATTR_KIND_READ_ONLY;
567 case Attribute::Returned:
568 return bitc::ATTR_KIND_RETURNED;
569 case Attribute::ReturnsTwice:
570 return bitc::ATTR_KIND_RETURNS_TWICE;
571 case Attribute::SExt:
572 return bitc::ATTR_KIND_S_EXT;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +0000573 case Attribute::Speculatable:
574 return bitc::ATTR_KIND_SPECULATABLE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000575 case Attribute::StackAlignment:
576 return bitc::ATTR_KIND_STACK_ALIGNMENT;
577 case Attribute::StackProtect:
578 return bitc::ATTR_KIND_STACK_PROTECT;
579 case Attribute::StackProtectReq:
580 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
581 case Attribute::StackProtectStrong:
582 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000583 case Attribute::SafeStack:
584 return bitc::ATTR_KIND_SAFESTACK;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000585 case Attribute::StructRet:
586 return bitc::ATTR_KIND_STRUCT_RET;
587 case Attribute::SanitizeAddress:
588 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
589 case Attribute::SanitizeThread:
590 return bitc::ATTR_KIND_SANITIZE_THREAD;
591 case Attribute::SanitizeMemory:
592 return bitc::ATTR_KIND_SANITIZE_MEMORY;
Manman Ren9bfd0d02016-04-01 21:41:15 +0000593 case Attribute::SwiftError:
594 return bitc::ATTR_KIND_SWIFT_ERROR;
Manman Renf46262e2016-03-29 17:37:21 +0000595 case Attribute::SwiftSelf:
596 return bitc::ATTR_KIND_SWIFT_SELF;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000597 case Attribute::UWTable:
598 return bitc::ATTR_KIND_UW_TABLE;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +0000599 case Attribute::WriteOnly:
600 return bitc::ATTR_KIND_WRITEONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000601 case Attribute::ZExt:
602 return bitc::ATTR_KIND_Z_EXT;
603 case Attribute::EndAttrKinds:
604 llvm_unreachable("Can not encode end-attribute kinds marker.");
605 case Attribute::None:
606 llvm_unreachable("Can not encode none-attribute.");
607 }
608
609 llvm_unreachable("Trying to encode unknown attribute");
610}
611
Teresa Johnson37687f32016-04-23 04:30:47 +0000612void ModuleBitcodeWriter::writeAttributeGroupTable() {
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000613 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
614 VE.getAttributeGroups();
Bill Wendling92ed7002013-02-11 22:33:26 +0000615 if (AttrGrps.empty()) return;
Bill Wendlingdc095552013-02-10 23:09:32 +0000616
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000617 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
Bill Wendlingdc095552013-02-10 23:09:32 +0000618
619 SmallVector<uint64_t, 64> Record;
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000620 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
621 unsigned AttrListIndex = Pair.first;
622 AttributeSet AS = Pair.second;
623 Record.push_back(VE.getAttributeGroupID(Pair));
624 Record.push_back(AttrListIndex);
Bill Wendlingdc095552013-02-10 23:09:32 +0000625
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000626 for (Attribute Attr : AS) {
627 if (Attr.isEnumAttribute()) {
628 Record.push_back(0);
629 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
630 } else if (Attr.isIntAttribute()) {
631 Record.push_back(1);
632 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
633 Record.push_back(Attr.getValueAsInt());
634 } else {
635 StringRef Kind = Attr.getKindAsString();
636 StringRef Val = Attr.getValueAsString();
Bill Wendlingdc095552013-02-10 23:09:32 +0000637
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000638 Record.push_back(Val.empty() ? 3 : 4);
639 Record.append(Kind.begin(), Kind.end());
640 Record.push_back(0);
641 if (!Val.empty()) {
642 Record.append(Val.begin(), Val.end());
Bill Wendlingdc095552013-02-10 23:09:32 +0000643 Record.push_back(0);
Bill Wendlingdc095552013-02-10 23:09:32 +0000644 }
645 }
Bill Wendlingdc095552013-02-10 23:09:32 +0000646 }
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000647
648 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
649 Record.clear();
Bill Wendlingdc095552013-02-10 23:09:32 +0000650 }
651
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000652 Stream.ExitBlock();
Bill Wendlingdc095552013-02-10 23:09:32 +0000653}
654
Teresa Johnson37687f32016-04-23 04:30:47 +0000655void ModuleBitcodeWriter::writeAttributeTable() {
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000656 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000657 if (Attrs.empty()) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000658
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000659 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000660
661 SmallVector<uint64_t, 64> Record;
662 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
Reid Klecknerb5180542017-03-21 16:57:19 +0000663 const AttributeList &A = Attrs[i];
Bill Wendling0dc08912013-02-12 08:13:50 +0000664 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000665 Record.push_back(
Reid Kleckner63b26f02017-04-24 22:25:02 +0000666 VE.getAttributeGroupID({A.getSlotIndex(i), A.getSlotAttributes(i)}));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000667
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000668 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000669 Record.clear();
670 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000671
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000672 Stream.ExitBlock();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000673}
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000674
675/// WriteTypeTable - Write out the type table for a module.
Teresa Johnson37687f32016-04-23 04:30:47 +0000676void ModuleBitcodeWriter::writeTypeTable() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000677 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000678
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000679 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000680 SmallVector<uint64_t, 64> TypeVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000681
David Blaikie7b028102015-02-25 00:51:52 +0000682 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
Chad Rosier9646c0d2011-12-08 00:38:45 +0000683
Chris Lattnerccee7062007-05-05 06:30:12 +0000684 // Abbrev for TYPE_CODE_POINTER.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000685 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000686 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000687 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
Christopher Lamb25f50762007-12-12 08:44:39 +0000688 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
David Blaikie7ad9dc12017-01-04 22:36:33 +0000689 unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000690
Chris Lattnerccee7062007-05-05 06:30:12 +0000691 // Abbrev for TYPE_CODE_FUNCTION.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000692 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000693 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
694 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
Chris Lattnerccee7062007-05-05 06:30:12 +0000695 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000696 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
697
David Blaikie7ad9dc12017-01-04 22:36:33 +0000698 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000699
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000700 // Abbrev for TYPE_CODE_STRUCT_ANON.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000701 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000702 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
Chris Lattnerccee7062007-05-05 06:30:12 +0000703 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
704 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000705 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
706
David Blaikie7ad9dc12017-01-04 22:36:33 +0000707 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000708
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000709 // Abbrev for TYPE_CODE_STRUCT_NAME.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000710 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000711 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
712 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
713 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000714 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000715
716 // Abbrev for TYPE_CODE_STRUCT_NAMED.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000717 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000718 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
719 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
720 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000721 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
722
David Blaikie7ad9dc12017-01-04 22:36:33 +0000723 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000724
Chris Lattnerccee7062007-05-05 06:30:12 +0000725 // Abbrev for TYPE_CODE_ARRAY.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000726 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000727 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
728 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
Chad Rosier9646c0d2011-12-08 00:38:45 +0000729 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
730
David Blaikie7ad9dc12017-01-04 22:36:33 +0000731 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000732
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000733 // Emit an entry count so the reader can reserve space.
734 TypeVals.push_back(TypeList.size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000735 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000736 TypeVals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000737
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000738 // Loop over all of the types, emitting each in turn.
739 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +0000740 Type *T = TypeList[i];
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000741 int AbbrevToUse = 0;
742 unsigned Code = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000743
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000744 switch (T->getTypeID()) {
Joe Abbey2ad8df22012-11-25 15:23:39 +0000745 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
746 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
747 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
748 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
749 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
750 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000751 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
Joe Abbey2ad8df22012-11-25 15:23:39 +0000752 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
753 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
754 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
David Majnemerb611e3f2015-08-14 05:09:07 +0000755 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000756 case Type::IntegerTyID:
757 // INTEGER: [width]
758 Code = bitc::TYPE_CODE_INTEGER;
759 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
760 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000761 case Type::PointerTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000762 PointerType *PTy = cast<PointerType>(T);
Christopher Lamb25f50762007-12-12 08:44:39 +0000763 // POINTER: [pointee type, address space]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000764 Code = bitc::TYPE_CODE_POINTER;
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000765 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
Christopher Lamb25f50762007-12-12 08:44:39 +0000766 unsigned AddressSpace = PTy->getAddressSpace();
767 TypeVals.push_back(AddressSpace);
768 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000769 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000770 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000771 case Type::FunctionTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000772 FunctionType *FT = cast<FunctionType>(T);
Chad Rosier95898722011-11-03 00:14:01 +0000773 // FUNCTION: [isvararg, retty, paramty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000774 Code = bitc::TYPE_CODE_FUNCTION;
775 TypeVals.push_back(FT->isVarArg());
776 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000777 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
778 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
Chris Lattnerccee7062007-05-05 06:30:12 +0000779 AbbrevToUse = FunctionAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000780 break;
781 }
782 case Type::StructTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000783 StructType *ST = cast<StructType>(T);
Chris Lattnerccee7062007-05-05 06:30:12 +0000784 // STRUCT: [ispacked, eltty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000785 TypeVals.push_back(ST->isPacked());
Chris Lattnere14cb882007-05-04 19:11:41 +0000786 // Output all of the element types.
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000787 for (StructType::element_iterator I = ST->element_begin(),
788 E = ST->element_end(); I != E; ++I)
789 TypeVals.push_back(VE.getTypeID(*I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000790
Chris Lattner335d3992011-08-12 18:06:37 +0000791 if (ST->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000792 Code = bitc::TYPE_CODE_STRUCT_ANON;
793 AbbrevToUse = StructAnonAbbrev;
794 } else {
795 if (ST->isOpaque()) {
796 Code = bitc::TYPE_CODE_OPAQUE;
797 } else {
798 Code = bitc::TYPE_CODE_STRUCT_NAMED;
799 AbbrevToUse = StructNamedAbbrev;
800 }
801
802 // Emit the name if it is present.
803 if (!ST->getName().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000804 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
Teresa Johnson37687f32016-04-23 04:30:47 +0000805 StructNameAbbrev);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000806 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000807 break;
808 }
809 case Type::ArrayTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000810 ArrayType *AT = cast<ArrayType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000811 // ARRAY: [numelts, eltty]
812 Code = bitc::TYPE_CODE_ARRAY;
813 TypeVals.push_back(AT->getNumElements());
814 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
Chris Lattnerccee7062007-05-05 06:30:12 +0000815 AbbrevToUse = ArrayAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000816 break;
817 }
818 case Type::VectorTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000819 VectorType *VT = cast<VectorType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000820 // VECTOR [numelts, eltty]
821 Code = bitc::TYPE_CODE_VECTOR;
822 TypeVals.push_back(VT->getNumElements());
823 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
824 break;
825 }
826 }
827
828 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000829 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000830 TypeVals.clear();
831 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000832
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000833 Stream.ExitBlock();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000834}
835
Teresa Johnson5e22e442016-02-06 16:07:35 +0000836static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
837 switch (Linkage) {
Rafael Espindola261d25b2015-01-08 16:25:01 +0000838 case GlobalValue::ExternalLinkage:
839 return 0;
840 case GlobalValue::WeakAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000841 return 16;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000842 case GlobalValue::AppendingLinkage:
843 return 2;
844 case GlobalValue::InternalLinkage:
845 return 3;
846 case GlobalValue::LinkOnceAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000847 return 18;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000848 case GlobalValue::ExternalWeakLinkage:
849 return 7;
850 case GlobalValue::CommonLinkage:
851 return 8;
852 case GlobalValue::PrivateLinkage:
853 return 9;
854 case GlobalValue::WeakODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000855 return 17;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000856 case GlobalValue::LinkOnceODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000857 return 19;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000858 case GlobalValue::AvailableExternallyLinkage:
859 return 12;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000860 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000861 llvm_unreachable("Invalid linkage");
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000862}
863
Teresa Johnson5e22e442016-02-06 16:07:35 +0000864static unsigned getEncodedLinkage(const GlobalValue &GV) {
865 return getEncodedLinkage(GV.getLinkage());
866}
867
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000868// Decode the flags for GlobalValue in the summary
869static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
870 uint64_t RawFlags = 0;
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000871
Mehdi Amini1380edf2017-02-03 07:41:43 +0000872 RawFlags |= Flags.NotEligibleToImport; // bool
873 RawFlags |= (Flags.LiveRoot << 1);
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000874 // Linkage don't need to be remapped at that time for the summary. Any future
875 // change to the getEncodedLinkage() function will need to be taken into
876 // account here as well.
Mehdi Amini1380edf2017-02-03 07:41:43 +0000877 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
878
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000879 return RawFlags;
880}
881
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000882static unsigned getEncodedVisibility(const GlobalValue &GV) {
883 switch (GV.getVisibility()) {
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000884 case GlobalValue::DefaultVisibility: return 0;
885 case GlobalValue::HiddenVisibility: return 1;
886 case GlobalValue::ProtectedVisibility: return 2;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000887 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000888 llvm_unreachable("Invalid visibility");
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000889}
890
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000891static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
892 switch (GV.getDLLStorageClass()) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000893 case GlobalValue::DefaultStorageClass: return 0;
894 case GlobalValue::DLLImportStorageClass: return 1;
895 case GlobalValue::DLLExportStorageClass: return 2;
896 }
897 llvm_unreachable("Invalid DLL storage class");
898}
899
Rafael Espindola59f7eba2014-05-28 18:15:43 +0000900static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000901 switch (GV.getThreadLocalMode()) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000902 case GlobalVariable::NotThreadLocal: return 0;
903 case GlobalVariable::GeneralDynamicTLSModel: return 1;
904 case GlobalVariable::LocalDynamicTLSModel: return 2;
905 case GlobalVariable::InitialExecTLSModel: return 3;
906 case GlobalVariable::LocalExecTLSModel: return 4;
907 }
908 llvm_unreachable("Invalid TLS model");
909}
910
David Majnemerdad0a642014-06-27 18:19:56 +0000911static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
912 switch (C.getSelectionKind()) {
913 case Comdat::Any:
914 return bitc::COMDAT_SELECTION_KIND_ANY;
915 case Comdat::ExactMatch:
916 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
917 case Comdat::Largest:
918 return bitc::COMDAT_SELECTION_KIND_LARGEST;
919 case Comdat::NoDuplicates:
920 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
921 case Comdat::SameSize:
922 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
923 }
924 llvm_unreachable("Invalid selection kind");
925}
926
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000927static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
928 switch (GV.getUnnamedAddr()) {
929 case GlobalValue::UnnamedAddr::None: return 0;
930 case GlobalValue::UnnamedAddr::Local: return 2;
931 case GlobalValue::UnnamedAddr::Global: return 1;
932 }
933 llvm_unreachable("Invalid unnamed_addr");
934}
935
Teresa Johnson37687f32016-04-23 04:30:47 +0000936void ModuleBitcodeWriter::writeComdats() {
David Majnemer90a021f2016-03-13 08:01:03 +0000937 SmallVector<unsigned, 64> Vals;
David Majnemerdad0a642014-06-27 18:19:56 +0000938 for (const Comdat *C : VE.getComdats()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000939 // COMDAT: [strtab offset, strtab size, selection_kind]
940 Vals.push_back(StrtabBuilder.add(C->getName()));
941 Vals.push_back(C->getName().size());
David Majnemerdad0a642014-06-27 18:19:56 +0000942 Vals.push_back(getEncodedComdatSelectionKind(*C));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000943 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
David Majnemerdad0a642014-06-27 18:19:56 +0000944 Vals.clear();
945 }
946}
947
Teresa Johnsonff642b92015-09-17 20:12:00 +0000948/// Write a record that will eventually hold the word offset of the
949/// module-level VST. For now the offset is 0, which will be backpatched
Teresa Johnson37687f32016-04-23 04:30:47 +0000950/// after the real VST is written. Saves the bit offset to backpatch.
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000951void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
Teresa Johnsonff642b92015-09-17 20:12:00 +0000952 // Write a placeholder value in for the offset of the real VST,
953 // which is written after the function blocks so that it can include
954 // the offset of each function. The placeholder offset will be
955 // updated when the real VST is written.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000956 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnsonff642b92015-09-17 20:12:00 +0000957 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
958 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
959 // hold the real VST offset. Must use fixed instead of VBR as we don't
960 // know how many VBR chunks to reserve ahead of time.
961 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000962 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnsonff642b92015-09-17 20:12:00 +0000963
964 // Emit the placeholder
965 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000966 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
Teresa Johnsonff642b92015-09-17 20:12:00 +0000967
Teresa Johnson37687f32016-04-23 04:30:47 +0000968 // Compute and save the bit offset to the placeholder, which will be
Teresa Johnsonff642b92015-09-17 20:12:00 +0000969 // patched when the real VST is written. We can simply subtract the 32-bit
970 // fixed size from the current bit number to get the location to backpatch.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000971 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
Teresa Johnsonff642b92015-09-17 20:12:00 +0000972}
973
Teresa Johnsone1164de2016-02-10 21:55:02 +0000974enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
975
976/// Determine the encoding to use for the given string name and length.
977static StringEncoding getStringEncoding(const char *Str, unsigned StrLen) {
978 bool isChar6 = true;
979 for (const char *C = Str, *E = C + StrLen; C != E; ++C) {
980 if (isChar6)
981 isChar6 = BitCodeAbbrevOp::isChar6(*C);
982 if ((unsigned char)*C & 128)
983 // don't bother scanning the rest.
984 return SE_Fixed8;
985 }
986 if (isChar6)
987 return SE_Char6;
988 else
989 return SE_Fixed7;
990}
991
Teresa Johnsonff642b92015-09-17 20:12:00 +0000992/// Emit top-level description of module, including target triple, inline asm,
993/// descriptors for global variables, and function prototype info.
994/// Returns the bit offset to backpatch with the location of the real VST.
Teresa Johnson37687f32016-04-23 04:30:47 +0000995void ModuleBitcodeWriter::writeModuleInfo() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000996 // Emit various pieces of data attached to a module.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000997 if (!M.getTargetTriple().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000998 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
Teresa Johnson37687f32016-04-23 04:30:47 +0000999 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001000 const std::string &DL = M.getDataLayoutStr();
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001001 if (!DL.empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001002 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001003 if (!M.getModuleInlineAsm().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001004 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001005 0 /*TODO*/);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001006
Gordon Henriksend930f912008-08-17 18:44:35 +00001007 // Emit information about sections and GC, computing how many there are. Also
1008 // compute the maximum alignment value.
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001009 std::map<std::string, unsigned> SectionMap;
Gordon Henriksend930f912008-08-17 18:44:35 +00001010 std::map<std::string, unsigned> GCMap;
Chris Lattner4b00d922007-04-23 16:04:05 +00001011 unsigned MaxAlignment = 0;
Chris Lattnerb5491372007-04-23 18:58:34 +00001012 unsigned MaxGlobalType = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001013 for (const GlobalValue &GV : M.globals()) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001014 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
David Blaikie1a848da2015-04-27 19:58:56 +00001015 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001016 if (GV.hasSection()) {
Chad Rosier75ec09c2011-08-12 16:45:18 +00001017 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001018 unsigned &Entry = SectionMap[GV.getSection()];
Chad Rosier75ec09c2011-08-12 16:45:18 +00001019 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001020 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001021 0 /*TODO*/);
Chad Rosier75ec09c2011-08-12 16:45:18 +00001022 Entry = SectionMap.size();
1023 }
1024 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001025 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001026 for (const Function &F : M) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001027 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
1028 if (F.hasSection()) {
Gordon Henriksen71183b62007-12-10 03:18:06 +00001029 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001030 unsigned &Entry = SectionMap[F.getSection()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001031 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001032 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001033 0 /*TODO*/);
Gordon Henriksen71183b62007-12-10 03:18:06 +00001034 Entry = SectionMap.size();
1035 }
1036 }
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001037 if (F.hasGC()) {
Gordon Henriksend930f912008-08-17 18:44:35 +00001038 // Same for GC names.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001039 unsigned &Entry = GCMap[F.getGC()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001040 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001041 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1042 0 /*TODO*/);
Gordon Henriksend930f912008-08-17 18:44:35 +00001043 Entry = GCMap.size();
Gordon Henriksen71183b62007-12-10 03:18:06 +00001044 }
1045 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001046 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001047
Chris Lattner4b00d922007-04-23 16:04:05 +00001048 // Emit abbrev for globals, now that we know # sections and max alignment.
1049 unsigned SimpleGVarAbbrev = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001050 if (!M.global_empty()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001051 // Add an abbrev for common globals with no visibility or thread localness.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001052 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner4b00d922007-04-23 16:04:05 +00001053 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001054 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1055 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Chris Lattner2eae59f2007-05-04 20:34:50 +00001056 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001057 Log2_32_Ceil(MaxGlobalType+1)));
David Blaikie1a848da2015-04-27 19:58:56 +00001058 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1059 //| explicitType << 1
1060 //| constant
1061 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1062 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1063 if (MaxAlignment == 0) // Alignment.
Chris Lattner4b00d922007-04-23 16:04:05 +00001064 Abbv->Add(BitCodeAbbrevOp(0));
1065 else {
1066 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
Chris Lattner2eae59f2007-05-04 20:34:50 +00001067 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001068 Log2_32_Ceil(MaxEncAlignment+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001069 }
1070 if (SectionMap.empty()) // Section.
1071 Abbv->Add(BitCodeAbbrevOp(0));
1072 else
Chris Lattner2eae59f2007-05-04 20:34:50 +00001073 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattner1e50c292007-04-24 03:29:47 +00001074 Log2_32_Ceil(SectionMap.size()+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001075 // Don't bother emitting vis + thread local.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001076 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Chris Lattner4b00d922007-04-23 16:04:05 +00001077 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001078
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001079 SmallVector<unsigned, 64> Vals;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001080 // Emit the module's source file name.
1081 {
1082 StringEncoding Bits = getStringEncoding(M.getSourceFileName().data(),
1083 M.getSourceFileName().size());
1084 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1085 if (Bits == SE_Char6)
1086 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1087 else if (Bits == SE_Fixed7)
1088 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1089
1090 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1091 auto Abbv = std::make_shared<BitCodeAbbrev>();
1092 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1093 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1094 Abbv->Add(AbbrevOpToUse);
1095 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1096
1097 for (const auto P : M.getSourceFileName())
1098 Vals.push_back((unsigned char)P);
1099
1100 // Emit the finished record.
1101 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1102 Vals.clear();
1103 }
1104
1105 // Emit the global variable information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001106 for (const GlobalVariable &GV : M.globals()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001107 unsigned AbbrevToUse = 0;
1108
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001109 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00001110 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00001111 // unnamed_addr, externally_initialized, dllstorageclass,
1112 // comdat]
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001113 Vals.push_back(StrtabBuilder.add(GV.getName()));
1114 Vals.push_back(GV.getName().size());
David Blaikie1a848da2015-04-27 19:58:56 +00001115 Vals.push_back(VE.getTypeID(GV.getValueType()));
1116 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001117 Vals.push_back(GV.isDeclaration() ? 0 :
1118 (VE.getValueID(GV.getInitializer()) + 1));
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001119 Vals.push_back(getEncodedLinkage(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001120 Vals.push_back(Log2_32(GV.getAlignment())+1);
1121 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
1122 if (GV.isThreadLocal() ||
1123 GV.getVisibility() != GlobalValue::DefaultVisibility ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001124 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1125 GV.isExternallyInitialized() ||
David Majnemerdad0a642014-06-27 18:19:56 +00001126 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1127 GV.hasComdat()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001128 Vals.push_back(getEncodedVisibility(GV));
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001129 Vals.push_back(getEncodedThreadLocalMode(GV));
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001130 Vals.push_back(getEncodedUnnamedAddr(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001131 Vals.push_back(GV.isExternallyInitialized());
Nico Rieck7157bb72014-01-14 15:22:47 +00001132 Vals.push_back(getEncodedDLLStorageClass(GV));
David Majnemerdad0a642014-06-27 18:19:56 +00001133 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
Chris Lattner4b00d922007-04-23 16:04:05 +00001134 } else {
1135 AbbrevToUse = SimpleGVarAbbrev;
1136 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001137
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001138 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001139 Vals.clear();
1140 }
1141
1142 // Emit the function proto information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001143 for (const Function &F : M) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001144 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1145 // linkage, paramattrs, alignment, section, visibility, gc,
1146 // unnamed_addr, prologuedata, dllstorageclass, comdat,
1147 // prefixdata, personalityfn]
1148 Vals.push_back(StrtabBuilder.add(F.getName()));
1149 Vals.push_back(F.getName().size());
David Blaikie561a1572015-04-17 16:28:26 +00001150 Vals.push_back(VE.getTypeID(F.getFunctionType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001151 Vals.push_back(F.getCallingConv());
1152 Vals.push_back(F.isDeclaration());
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001153 Vals.push_back(getEncodedLinkage(F));
Reid Klecknerb4a2d182017-04-24 20:38:30 +00001154 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001155 Vals.push_back(Log2_32(F.getAlignment())+1);
1156 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001157 Vals.push_back(getEncodedVisibility(F));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001158 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001159 Vals.push_back(getEncodedUnnamedAddr(F));
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001160 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1161 : 0);
Nico Rieck7157bb72014-01-14 15:22:47 +00001162 Vals.push_back(getEncodedDLLStorageClass(F));
David Majnemerdad0a642014-06-27 18:19:56 +00001163 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001164 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1165 : 0);
David Majnemer7fddecc2015-06-17 20:52:32 +00001166 Vals.push_back(
1167 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001168
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001169 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001170 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001171 Vals.clear();
1172 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001173
Chris Lattner44c17072007-04-26 02:46:40 +00001174 // Emit the alias information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001175 for (const GlobalAlias &A : M.aliases()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001176 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1177 // visibility, dllstorageclass, threadlocal, unnamed_addr]
1178 Vals.push_back(StrtabBuilder.add(A.getName()));
1179 Vals.push_back(A.getName().size());
David Blaikie6a51dbd2015-09-17 22:18:59 +00001180 Vals.push_back(VE.getTypeID(A.getValueType()));
1181 Vals.push_back(A.getType()->getAddressSpace());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001182 Vals.push_back(VE.getValueID(A.getAliasee()));
1183 Vals.push_back(getEncodedLinkage(A));
1184 Vals.push_back(getEncodedVisibility(A));
1185 Vals.push_back(getEncodedDLLStorageClass(A));
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001186 Vals.push_back(getEncodedThreadLocalMode(A));
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001187 Vals.push_back(getEncodedUnnamedAddr(A));
Chris Lattner44c17072007-04-26 02:46:40 +00001188 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001189 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
Chris Lattner44c17072007-04-26 02:46:40 +00001190 Vals.clear();
1191 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001192
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001193 // Emit the ifunc information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001194 for (const GlobalIFunc &I : M.ifuncs()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001195 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1196 // val#, linkage, visibility]
1197 Vals.push_back(StrtabBuilder.add(I.getName()));
1198 Vals.push_back(I.getName().size());
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001199 Vals.push_back(VE.getTypeID(I.getValueType()));
1200 Vals.push_back(I.getType()->getAddressSpace());
1201 Vals.push_back(VE.getValueID(I.getResolver()));
1202 Vals.push_back(getEncodedLinkage(I));
1203 Vals.push_back(getEncodedVisibility(I));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001204 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001205 Vals.clear();
1206 }
1207
Teresa Johnson37687f32016-04-23 04:30:47 +00001208 writeValueSymbolTableForwardDecl();
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001209}
1210
Teresa Johnson37687f32016-04-23 04:30:47 +00001211static uint64_t getOptimizationFlags(const Value *V) {
Dan Gohman0ebd6962009-07-20 21:19:07 +00001212 uint64_t Flags = 0;
1213
Sanjay Patelc00017d2014-10-15 17:45:13 +00001214 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
Dan Gohman16f54152009-08-20 17:11:38 +00001215 if (OBO->hasNoSignedWrap())
1216 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1217 if (OBO->hasNoUnsignedWrap())
1218 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001219 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
Chris Lattner35315d02011-02-06 21:44:57 +00001220 if (PEO->isExact())
1221 Flags |= 1 << bitc::PEO_EXACT;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001222 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001223 if (FPMO->hasUnsafeAlgebra())
Michael Ilseman65f14352012-12-09 21:12:04 +00001224 Flags |= FastMathFlags::UnsafeAlgebra;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001225 if (FPMO->hasNoNaNs())
Michael Ilseman65f14352012-12-09 21:12:04 +00001226 Flags |= FastMathFlags::NoNaNs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001227 if (FPMO->hasNoInfs())
Michael Ilseman65f14352012-12-09 21:12:04 +00001228 Flags |= FastMathFlags::NoInfs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001229 if (FPMO->hasNoSignedZeros())
Michael Ilseman65f14352012-12-09 21:12:04 +00001230 Flags |= FastMathFlags::NoSignedZeros;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001231 if (FPMO->hasAllowReciprocal())
Michael Ilseman65f14352012-12-09 21:12:04 +00001232 Flags |= FastMathFlags::AllowReciprocal;
Adam Nemetcd847a82017-03-28 20:11:52 +00001233 if (FPMO->hasAllowContract())
1234 Flags |= FastMathFlags::AllowContract;
Dan Gohman0ebd6962009-07-20 21:19:07 +00001235 }
1236
1237 return Flags;
1238}
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001239
Teresa Johnson37687f32016-04-23 04:30:47 +00001240void ModuleBitcodeWriter::writeValueAsMetadata(
1241 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001242 // Mimic an MDNode with a value as one operand.
1243 Value *V = MD->getValue();
1244 Record.push_back(VE.getTypeID(V->getType()));
1245 Record.push_back(VE.getValueID(V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001246 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001247 Record.clear();
1248}
1249
Teresa Johnson37687f32016-04-23 04:30:47 +00001250void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1251 SmallVectorImpl<uint64_t> &Record,
1252 unsigned Abbrev) {
Chris Lattner9b493022009-12-31 01:22:29 +00001253 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001254 Metadata *MD = N->getOperand(i);
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001255 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1256 "Unexpected function-local metadata");
1257 Record.push_back(VE.getMetadataOrNullID(MD));
Devang Patel8cca7b42009-08-04 05:01:35 +00001258 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001259 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1260 : bitc::METADATA_NODE,
1261 Record, Abbrev);
Devang Patel8cca7b42009-08-04 05:01:35 +00001262 Record.clear();
1263}
Devang Patele059ba6e2009-07-23 01:07:34 +00001264
Teresa Johnson37687f32016-04-23 04:30:47 +00001265unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001266 // Assume the column is usually under 128, and always output the inlined-at
1267 // location (it's never more expensive than building an array size 1).
David Blaikie7ad9dc12017-01-04 22:36:33 +00001268 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001269 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1270 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1271 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1272 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1273 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1274 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001275 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001276}
1277
Teresa Johnson37687f32016-04-23 04:30:47 +00001278void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1279 SmallVectorImpl<uint64_t> &Record,
1280 unsigned &Abbrev) {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001281 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001282 Abbrev = createDILocationAbbrev();
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001283
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001284 Record.push_back(N->isDistinct());
1285 Record.push_back(N->getLine());
1286 Record.push_back(N->getColumn());
1287 Record.push_back(VE.getMetadataID(N->getScope()));
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001288 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001289
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001290 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001291 Record.clear();
1292}
1293
Teresa Johnson37687f32016-04-23 04:30:47 +00001294unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001295 // Assume the column is usually under 128, and always output the inlined-at
1296 // location (it's never more expensive than building an array size 1).
David Blaikie7ad9dc12017-01-04 22:36:33 +00001297 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001298 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1299 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1300 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1301 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1302 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1303 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1304 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001305 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001306}
1307
Teresa Johnson37687f32016-04-23 04:30:47 +00001308void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1309 SmallVectorImpl<uint64_t> &Record,
1310 unsigned &Abbrev) {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001311 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001312 Abbrev = createGenericDINodeAbbrev();
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001313
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001314 Record.push_back(N->isDistinct());
1315 Record.push_back(N->getTag());
1316 Record.push_back(0); // Per-tag version field; unused for now.
1317
1318 for (auto &I : N->operands())
1319 Record.push_back(VE.getMetadataOrNullID(I));
1320
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001321 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001322 Record.clear();
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001323}
1324
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001325static uint64_t rotateSign(int64_t I) {
1326 uint64_t U = I;
1327 return I < 0 ? ~(U << 1) : U << 1;
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001328}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001329
Teresa Johnson37687f32016-04-23 04:30:47 +00001330void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1331 SmallVectorImpl<uint64_t> &Record,
1332 unsigned Abbrev) {
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001333 Record.push_back(N->isDistinct());
1334 Record.push_back(N->getCount());
Duncan P. N. Exon Smith5dcf6212015-04-07 00:39:59 +00001335 Record.push_back(rotateSign(N->getLowerBound()));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001336
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001337 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001338 Record.clear();
1339}
1340
Teresa Johnson37687f32016-04-23 04:30:47 +00001341void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1342 SmallVectorImpl<uint64_t> &Record,
1343 unsigned Abbrev) {
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001344 Record.push_back(N->isDistinct());
1345 Record.push_back(rotateSign(N->getValue()));
1346 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1347
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001348 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001349 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001350}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001351
Teresa Johnson37687f32016-04-23 04:30:47 +00001352void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1353 SmallVectorImpl<uint64_t> &Record,
1354 unsigned Abbrev) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001355 Record.push_back(N->isDistinct());
1356 Record.push_back(N->getTag());
1357 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1358 Record.push_back(N->getSizeInBits());
1359 Record.push_back(N->getAlignInBits());
1360 Record.push_back(N->getEncoding());
1361
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001362 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001363 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001364}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001365
Teresa Johnson37687f32016-04-23 04:30:47 +00001366void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1367 SmallVectorImpl<uint64_t> &Record,
1368 unsigned Abbrev) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001369 Record.push_back(N->isDistinct());
1370 Record.push_back(N->getTag());
1371 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1372 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1373 Record.push_back(N->getLine());
1374 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001375 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001376 Record.push_back(N->getSizeInBits());
1377 Record.push_back(N->getAlignInBits());
1378 Record.push_back(N->getOffsetInBits());
1379 Record.push_back(N->getFlags());
1380 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1381
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00001382 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1383 // that there is no DWARF address space associated with DIDerivedType.
1384 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1385 Record.push_back(*DWARFAddressSpace + 1);
1386 else
1387 Record.push_back(0);
1388
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001389 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001390 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001391}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001392
Teresa Johnson37687f32016-04-23 04:30:47 +00001393void ModuleBitcodeWriter::writeDICompositeType(
1394 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1395 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001396 const unsigned IsNotUsedInOldTypeRef = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001397 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001398 Record.push_back(N->getTag());
1399 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1400 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1401 Record.push_back(N->getLine());
1402 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1403 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1404 Record.push_back(N->getSizeInBits());
1405 Record.push_back(N->getAlignInBits());
1406 Record.push_back(N->getOffsetInBits());
1407 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001408 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001409 Record.push_back(N->getRuntimeLang());
1410 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001411 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001412 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1413
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001414 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001415 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001416}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001417
Teresa Johnson37687f32016-04-23 04:30:47 +00001418void ModuleBitcodeWriter::writeDISubroutineType(
1419 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1420 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001421 const unsigned HasNoOldTypeRefs = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001422 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001423 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001424 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001425 Record.push_back(N->getCC());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001426
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001427 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001428 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001429}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001430
Teresa Johnson37687f32016-04-23 04:30:47 +00001431void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1432 SmallVectorImpl<uint64_t> &Record,
1433 unsigned Abbrev) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001434 Record.push_back(N->isDistinct());
1435 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1436 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
Amjad Aboud7faeecc2016-12-25 10:12:09 +00001437 Record.push_back(N->getChecksumKind());
1438 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001439
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001440 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001441 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001442}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001443
Teresa Johnson37687f32016-04-23 04:30:47 +00001444void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1445 SmallVectorImpl<uint64_t> &Record,
1446 unsigned Abbrev) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00001447 assert(N->isDistinct() && "Expected distinct compile units");
1448 Record.push_back(/* IsDistinct */ true);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001449 Record.push_back(N->getSourceLanguage());
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001450 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001451 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1452 Record.push_back(N->isOptimized());
1453 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1454 Record.push_back(N->getRuntimeVersion());
1455 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1456 Record.push_back(N->getEmissionKind());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001457 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1458 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
Adrian Prantl75819ae2016-04-15 15:57:41 +00001459 Record.push_back(/* subprograms */ 0);
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001460 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1461 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
Adrian Prantl1f599f92015-05-21 20:37:30 +00001462 Record.push_back(N->getDWOId());
Amjad Abouda9bcf162015-12-10 12:56:35 +00001463 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
David Blaikiea01f2952016-08-24 18:29:49 +00001464 Record.push_back(N->getSplitDebugInlining());
Dehao Chen0944a8c2017-02-01 22:45:09 +00001465 Record.push_back(N->getDebugInfoForProfiling());
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001466
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001467 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001468 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001469}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001470
Teresa Johnson37687f32016-04-23 04:30:47 +00001471void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1472 SmallVectorImpl<uint64_t> &Record,
1473 unsigned Abbrev) {
Adrian Prantl85338cb2016-05-06 22:53:06 +00001474 uint64_t HasUnitFlag = 1 << 1;
1475 Record.push_back(N->isDistinct() | HasUnitFlag);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001476 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1477 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1478 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1479 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1480 Record.push_back(N->getLine());
1481 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1482 Record.push_back(N->isLocalToUnit());
1483 Record.push_back(N->isDefinition());
1484 Record.push_back(N->getScopeLine());
1485 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1486 Record.push_back(N->getVirtuality());
1487 Record.push_back(N->getVirtualIndex());
1488 Record.push_back(N->getFlags());
1489 Record.push_back(N->isOptimized());
Adrian Prantl75819ae2016-04-15 15:57:41 +00001490 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001491 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001492 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001493 Record.push_back(VE.getMetadataOrNullID(N->getVariables().get()));
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001494 Record.push_back(N->getThisAdjustment());
Adrian Prantl1d12b882017-04-26 22:56:44 +00001495 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001496
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001497 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001498 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001499}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001500
Teresa Johnson37687f32016-04-23 04:30:47 +00001501void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1502 SmallVectorImpl<uint64_t> &Record,
1503 unsigned Abbrev) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001504 Record.push_back(N->isDistinct());
1505 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1506 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1507 Record.push_back(N->getLine());
1508 Record.push_back(N->getColumn());
1509
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001510 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001511 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001512}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001513
Teresa Johnson37687f32016-04-23 04:30:47 +00001514void ModuleBitcodeWriter::writeDILexicalBlockFile(
1515 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1516 unsigned Abbrev) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001517 Record.push_back(N->isDistinct());
1518 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1519 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1520 Record.push_back(N->getDiscriminator());
1521
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001522 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001523 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001524}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001525
Teresa Johnson37687f32016-04-23 04:30:47 +00001526void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1527 SmallVectorImpl<uint64_t> &Record,
1528 unsigned Abbrev) {
Adrian Prantldbfda632016-11-03 19:42:02 +00001529 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001530 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001531 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001532
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001533 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001534 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001535}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001536
Teresa Johnson37687f32016-04-23 04:30:47 +00001537void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1538 SmallVectorImpl<uint64_t> &Record,
1539 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001540 Record.push_back(N->isDistinct());
1541 Record.push_back(N->getMacinfoType());
1542 Record.push_back(N->getLine());
1543 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1544 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1545
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001546 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001547 Record.clear();
1548}
1549
Teresa Johnson37687f32016-04-23 04:30:47 +00001550void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1551 SmallVectorImpl<uint64_t> &Record,
1552 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001553 Record.push_back(N->isDistinct());
1554 Record.push_back(N->getMacinfoType());
1555 Record.push_back(N->getLine());
1556 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1557 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1558
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001559 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001560 Record.clear();
1561}
1562
Teresa Johnson37687f32016-04-23 04:30:47 +00001563void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1564 SmallVectorImpl<uint64_t> &Record,
1565 unsigned Abbrev) {
Adrian Prantlab1243f2015-06-29 23:03:47 +00001566 Record.push_back(N->isDistinct());
1567 for (auto &I : N->operands())
1568 Record.push_back(VE.getMetadataOrNullID(I));
1569
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001570 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
Adrian Prantlab1243f2015-06-29 23:03:47 +00001571 Record.clear();
1572}
1573
Teresa Johnson37687f32016-04-23 04:30:47 +00001574void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1575 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1576 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001577 Record.push_back(N->isDistinct());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001578 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1579 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1580
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001581 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001582 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001583}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001584
Teresa Johnson37687f32016-04-23 04:30:47 +00001585void ModuleBitcodeWriter::writeDITemplateValueParameter(
1586 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1587 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001588 Record.push_back(N->isDistinct());
1589 Record.push_back(N->getTag());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001590 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1591 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1592 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1593
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001594 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001595 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001596}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001597
Teresa Johnson37687f32016-04-23 04:30:47 +00001598void ModuleBitcodeWriter::writeDIGlobalVariable(
1599 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1600 unsigned Abbrev) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001601 const uint64_t Version = 1 << 1;
1602 Record.push_back((uint64_t)N->isDistinct() | Version);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001603 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1604 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1605 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1606 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1607 Record.push_back(N->getLine());
1608 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1609 Record.push_back(N->isLocalToUnit());
1610 Record.push_back(N->isDefinition());
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001611 Record.push_back(/* expr */ 0);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001612 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
Victor Leschuk2ede1262016-10-20 00:13:12 +00001613 Record.push_back(N->getAlignInBits());
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001614
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001615 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001616 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001617}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001618
Teresa Johnson37687f32016-04-23 04:30:47 +00001619void ModuleBitcodeWriter::writeDILocalVariable(
1620 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1621 unsigned Abbrev) {
Victor Leschuk2ede1262016-10-20 00:13:12 +00001622 // In order to support all possible bitcode formats in BitcodeReader we need
Simon Pilgrim25059362016-10-20 10:42:14 +00001623 // to distinguish the following cases:
Victor Leschuk2ede1262016-10-20 00:13:12 +00001624 // 1) Record has no artificial tag (Record[1]),
1625 // has no obsolete inlinedAt field (Record[9]).
1626 // In this case Record size will be 8, HasAlignment flag is false.
1627 // 2) Record has artificial tag (Record[1]),
1628 // has no obsolete inlignedAt field (Record[9]).
1629 // In this case Record size will be 9, HasAlignment flag is false.
1630 // 3) Record has both artificial tag (Record[1]) and
1631 // obsolete inlignedAt field (Record[9]).
1632 // In this case Record size will be 10, HasAlignment flag is false.
1633 // 4) Record has neither artificial tag, nor inlignedAt field, but
1634 // HasAlignment flag is true and Record[8] contains alignment value.
1635 const uint64_t HasAlignmentFlag = 1 << 1;
Simon Pilgrim071da462016-10-20 10:37:58 +00001636 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001637 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1638 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1639 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1640 Record.push_back(N->getLine());
1641 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1642 Record.push_back(N->getArg());
1643 Record.push_back(N->getFlags());
Victor Leschuk2ede1262016-10-20 00:13:12 +00001644 Record.push_back(N->getAlignInBits());
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001645
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001646 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001647 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001648}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001649
Teresa Johnson37687f32016-04-23 04:30:47 +00001650void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1651 SmallVectorImpl<uint64_t> &Record,
1652 unsigned Abbrev) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001653 Record.reserve(N->getElements().size() + 1);
Adrian Prantl6825fb62017-04-18 01:21:53 +00001654 const uint64_t Version = 2 << 1;
1655 Record.push_back((uint64_t)N->isDistinct() | Version);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001656 Record.append(N->elements_begin(), N->elements_end());
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001657
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001658 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001659 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001660}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001661
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001662void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1663 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1664 unsigned Abbrev) {
1665 Record.push_back(N->isDistinct());
1666 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1667 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
1668
1669 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1670 Record.clear();
1671}
1672
Teresa Johnson37687f32016-04-23 04:30:47 +00001673void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1674 SmallVectorImpl<uint64_t> &Record,
1675 unsigned Abbrev) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001676 Record.push_back(N->isDistinct());
1677 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1678 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1679 Record.push_back(N->getLine());
1680 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1681 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1682 Record.push_back(N->getAttributes());
1683 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1684
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001685 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001686 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001687}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001688
Teresa Johnson37687f32016-04-23 04:30:47 +00001689void ModuleBitcodeWriter::writeDIImportedEntity(
1690 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1691 unsigned Abbrev) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001692 Record.push_back(N->isDistinct());
1693 Record.push_back(N->getTag());
1694 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1695 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1696 Record.push_back(N->getLine());
1697 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1698
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001699 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001700 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001701}
1702
Teresa Johnson37687f32016-04-23 04:30:47 +00001703unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
David Blaikie7ad9dc12017-01-04 22:36:33 +00001704 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001705 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1706 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1707 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001708 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001709}
1710
Teresa Johnson37687f32016-04-23 04:30:47 +00001711void ModuleBitcodeWriter::writeNamedMetadata(
1712 SmallVectorImpl<uint64_t> &Record) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001713 if (M.named_metadata_empty())
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001714 return;
1715
Teresa Johnson37687f32016-04-23 04:30:47 +00001716 unsigned Abbrev = createNamedMetadataAbbrev();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001717 for (const NamedMDNode &NMD : M.named_metadata()) {
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001718 // Write name.
1719 StringRef Str = NMD.getName();
1720 Record.append(Str.bytes_begin(), Str.bytes_end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001721 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001722 Record.clear();
1723
1724 // Write named metadata operands.
1725 for (const MDNode *N : NMD.operands())
1726 Record.push_back(VE.getMetadataID(N));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001727 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001728 Record.clear();
1729 }
1730}
1731
Teresa Johnson37687f32016-04-23 04:30:47 +00001732unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
David Blaikie7ad9dc12017-01-04 22:36:33 +00001733 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001734 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1735 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1736 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1737 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001738 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001739}
1740
1741/// Write out a record for MDString.
1742///
1743/// All the metadata strings in a metadata block are emitted in a single
1744/// record. The sizes and strings themselves are shoved into a blob.
Teresa Johnson37687f32016-04-23 04:30:47 +00001745void ModuleBitcodeWriter::writeMetadataStrings(
1746 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001747 if (Strings.empty())
1748 return;
1749
1750 // Start the record with the number of strings.
1751 Record.push_back(bitc::METADATA_STRINGS);
1752 Record.push_back(Strings.size());
1753
1754 // Emit the sizes of the strings in the blob.
1755 SmallString<256> Blob;
1756 {
1757 BitstreamWriter W(Blob);
1758 for (const Metadata *MD : Strings)
1759 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1760 W.FlushToWord();
1761 }
1762
1763 // Add the offset to the strings to the record.
1764 Record.push_back(Blob.size());
1765
1766 // Add the strings to the blob.
1767 for (const Metadata *MD : Strings)
1768 Blob.append(cast<MDString>(MD)->getString());
1769
1770 // Emit the final record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001771 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001772 Record.clear();
1773}
1774
Mehdi Aminie98f9252016-12-28 22:30:28 +00001775// Generates an enum to use as an index in the Abbrev array of Metadata record.
1776enum MetadataAbbrev : unsigned {
1777#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1778#include "llvm/IR/Metadata.def"
1779 LastPlusOne
1780};
1781
Teresa Johnson37687f32016-04-23 04:30:47 +00001782void ModuleBitcodeWriter::writeMetadataRecords(
Mehdi Aminie98f9252016-12-28 22:30:28 +00001783 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
1784 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001785 if (MDs.empty())
Duncan P. N. Exon Smith2fcf60e2015-01-12 22:30:34 +00001786 return;
1787
Duncan P. N. Exon Smith6b7b6802015-02-04 21:54:12 +00001788 // Initialize MDNode abbreviations.
1789#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1790#include "llvm/IR/Metadata.def"
1791
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001792 for (const Metadata *MD : MDs) {
Mehdi Aminie98f9252016-12-28 22:30:28 +00001793 if (IndexPos)
1794 IndexPos->push_back(Stream.GetCurrentBitNo());
Duncan P. N. Exon Smith73d5aae2015-01-12 22:31:35 +00001795 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
Duncan P. N. Exon Smith79f8d112015-03-17 00:16:35 +00001796 assert(N->isResolved() && "Expected forward references to be resolved");
1797
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001798 switch (N->getMetadataID()) {
1799 default:
1800 llvm_unreachable("Invalid MDNode subclass");
1801#define HANDLE_MDNODE_LEAF(CLASS) \
1802 case Metadata::CLASS##Kind: \
Mehdi Aminie98f9252016-12-28 22:30:28 +00001803 if (MDAbbrevs) \
1804 write##CLASS(cast<CLASS>(N), Record, \
1805 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
1806 else \
1807 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001808 continue;
1809#include "llvm/IR/Metadata.def"
1810 }
Devang Patel8cca7b42009-08-04 05:01:35 +00001811 }
Teresa Johnson37687f32016-04-23 04:30:47 +00001812 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
Devang Patel8cca7b42009-08-04 05:01:35 +00001813 }
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001814}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001815
Teresa Johnson37687f32016-04-23 04:30:47 +00001816void ModuleBitcodeWriter::writeModuleMetadata() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001817 if (!VE.hasMDs() && M.named_metadata_empty())
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001818 return;
1819
Mehdi Aminie98f9252016-12-28 22:30:28 +00001820 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001821 SmallVector<uint64_t, 64> Record;
Mehdi Aminie98f9252016-12-28 22:30:28 +00001822
1823 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1824 // block and load any metadata.
1825 std::vector<unsigned> MDAbbrevs;
1826
1827 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
1828 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
1829 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
1830 createGenericDINodeAbbrev();
1831
David Blaikie7ad9dc12017-01-04 22:36:33 +00001832 auto Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminie98f9252016-12-28 22:30:28 +00001833 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
Mehdi Amini5022bb72016-12-28 23:45:54 +00001834 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1835 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001836 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminie98f9252016-12-28 22:30:28 +00001837
David Blaikie7ad9dc12017-01-04 22:36:33 +00001838 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminie98f9252016-12-28 22:30:28 +00001839 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
1840 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1841 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001842 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminie98f9252016-12-28 22:30:28 +00001843
1844 // Emit MDStrings together upfront.
Teresa Johnson37687f32016-04-23 04:30:47 +00001845 writeMetadataStrings(VE.getMDStrings(), Record);
Mehdi Aminie98f9252016-12-28 22:30:28 +00001846
1847 // We only emit an index for the metadata record if we have more than a given
1848 // (naive) threshold of metadatas, otherwise it is not worth it.
1849 if (VE.getNonMDStrings().size() > IndexThreshold) {
1850 // Write a placeholder value in for the offset of the metadata index,
1851 // which is written after the records, so that it can include
1852 // the offset of each entry. The placeholder offset will be
1853 // updated after all records are emitted.
Mehdi Amini5022bb72016-12-28 23:45:54 +00001854 uint64_t Vals[] = {0, 0};
Mehdi Aminie98f9252016-12-28 22:30:28 +00001855 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
1856 }
1857
1858 // Compute and save the bit offset to the current position, which will be
1859 // patched when we emit the index later. We can simply subtract the 64-bit
1860 // fixed size from the current bit number to get the location to backpatch.
1861 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
1862
1863 // This index will contain the bitpos for each individual record.
1864 std::vector<uint64_t> IndexPos;
1865 IndexPos.reserve(VE.getNonMDStrings().size());
1866
1867 // Write all the records
1868 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
1869
1870 if (VE.getNonMDStrings().size() > IndexThreshold) {
1871 // Now that we have emitted all the records we will emit the index. But
1872 // first
1873 // backpatch the forward reference so that the reader can skip the records
1874 // efficiently.
1875 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
1876 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
1877
1878 // Delta encode the index.
1879 uint64_t PreviousValue = IndexOffsetRecordBitPos;
1880 for (auto &Elt : IndexPos) {
1881 auto EltDelta = Elt - PreviousValue;
1882 PreviousValue = Elt;
1883 Elt = EltDelta;
1884 }
1885 // Emit the index record.
1886 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
1887 IndexPos.clear();
1888 }
1889
1890 // Write the named metadata now.
Teresa Johnson37687f32016-04-23 04:30:47 +00001891 writeNamedMetadata(Record);
Peter Collingbourne21521892016-06-21 23:42:48 +00001892
1893 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
1894 SmallVector<uint64_t, 4> Record;
1895 Record.push_back(VE.getValueID(&GO));
1896 pushGlobalMetadataAttachment(Record, GO);
1897 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
1898 };
1899 for (const Function &F : M)
1900 if (F.isDeclaration() && F.hasMetadata())
1901 AddDeclAttachedMetadata(F);
1902 // FIXME: Only store metadata for declarations here, and move data for global
1903 // variable definitions to a separate block (PR28134).
1904 for (const GlobalVariable &GV : M.globals())
1905 if (GV.hasMetadata())
1906 AddDeclAttachedMetadata(GV);
1907
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001908 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00001909}
1910
Teresa Johnson37687f32016-04-23 04:30:47 +00001911void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
Duncan P. N. Exon Smith93429112016-04-02 15:09:42 +00001912 if (!VE.hasMDs())
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00001913 return;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001914
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001915 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00001916 SmallVector<uint64_t, 64> Record;
Teresa Johnson37687f32016-04-23 04:30:47 +00001917 writeMetadataStrings(VE.getMDStrings(), Record);
1918 writeMetadataRecords(VE.getNonMDStrings(), Record);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001919 Stream.ExitBlock();
Victor Hernandezb00a6be2010-01-13 19:37:33 +00001920}
1921
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001922void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
1923 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
1924 // [n x [id, mdnode]]
1925 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
1926 GO.getAllMetadata(MDs);
1927 for (const auto &I : MDs) {
1928 Record.push_back(I.first);
1929 Record.push_back(VE.getMetadataID(I.second));
1930 }
1931}
1932
1933void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001934 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
Chris Lattner07d09ed2010-04-03 02:17:50 +00001935
Devang Patelaf206b82009-09-18 19:26:43 +00001936 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001937
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001938 if (F.hasMetadata()) {
1939 pushGlobalMetadataAttachment(Record, F);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001940 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00001941 Record.clear();
1942 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001943
Peter Collingbournecceae7f2016-05-31 23:01:54 +00001944 // Write metadata attachments
1945 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
1946 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00001947 for (const BasicBlock &BB : F)
1948 for (const Instruction &I : BB) {
Devang Patel6da5dbf2009-10-22 18:55:16 +00001949 MDs.clear();
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00001950 I.getAllMetadataOtherThanDebugLoc(MDs);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001951
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001952 // If no metadata, ignore instruction.
1953 if (MDs.empty()) continue;
1954
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00001955 Record.push_back(VE.getInstructionID(&I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001956
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001957 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
1958 Record.push_back(MDs[i].first);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001959 Record.push_back(VE.getMetadataID(MDs[i].second));
Devang Patelaf206b82009-09-18 19:26:43 +00001960 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001961 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00001962 Record.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00001963 }
1964
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001965 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00001966}
1967
Peter Collingbourne21521892016-06-21 23:42:48 +00001968void ModuleBitcodeWriter::writeModuleMetadataKinds() {
Devang Patelaf206b82009-09-18 19:26:43 +00001969 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001970
Devang Patelaf206b82009-09-18 19:26:43 +00001971 // Write metadata kinds
1972 // METADATA_KIND - [n x [id, name]]
Michael Ilseman979dfbb2012-12-03 22:57:47 +00001973 SmallVector<StringRef, 8> Names;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001974 M.getMDKindNames(Names);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001975
Dan Gohman43aa8f02010-07-20 21:42:28 +00001976 if (Names.empty()) return;
Chris Lattnerc9558df2009-12-28 20:10:43 +00001977
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001978 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001979
Dan Gohman43aa8f02010-07-20 21:42:28 +00001980 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
Chris Lattnerc9558df2009-12-28 20:10:43 +00001981 Record.push_back(MDKindID);
1982 StringRef KName = Names[MDKindID];
1983 Record.append(KName.begin(), KName.end());
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001984
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001985 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
Devang Patelaf206b82009-09-18 19:26:43 +00001986 Record.clear();
1987 }
1988
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001989 Stream.ExitBlock();
Devang Patel8cca7b42009-08-04 05:01:35 +00001990}
1991
Teresa Johnson37687f32016-04-23 04:30:47 +00001992void ModuleBitcodeWriter::writeOperandBundleTags() {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001993 // Write metadata kinds
1994 //
1995 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
1996 //
1997 // OPERAND_BUNDLE_TAG - [strchr x N]
1998
1999 SmallVector<StringRef, 8> Tags;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002000 M.getOperandBundleTags(Tags);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002001
2002 if (Tags.empty())
2003 return;
2004
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002005 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002006
2007 SmallVector<uint64_t, 64> Record;
2008
2009 for (auto Tag : Tags) {
2010 Record.append(Tag.begin(), Tag.end());
2011
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002012 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002013 Record.clear();
2014 }
2015
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002016 Stream.ExitBlock();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002017}
2018
Jan Wen Voungafaced02012-10-11 20:20:40 +00002019static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2020 if ((int64_t)V >= 0)
2021 Vals.push_back(V << 1);
2022 else
2023 Vals.push_back((-V << 1) | 1);
2024}
2025
Teresa Johnson37687f32016-04-23 04:30:47 +00002026void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2027 bool isGlobal) {
Devang Patel8cca7b42009-08-04 05:01:35 +00002028 if (FirstVal == LastVal) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002029
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002030 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
Devang Patel8cca7b42009-08-04 05:01:35 +00002031
2032 unsigned AggregateAbbrev = 0;
2033 unsigned String8Abbrev = 0;
2034 unsigned CString7Abbrev = 0;
2035 unsigned CString6Abbrev = 0;
2036 // If this is a constant pool for the module, emit module-specific abbrevs.
2037 if (isGlobal) {
2038 // Abbrev for CST_CODE_AGGREGATE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002039 auto Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002040 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2041 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2042 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002043 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002044
2045 // Abbrev for CST_CODE_STRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002046 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002047 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2048 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2049 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002050 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002051 // Abbrev for CST_CODE_CSTRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002052 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002053 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2054 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2055 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002056 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002057 // Abbrev for CST_CODE_CSTRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002058 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002059 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2060 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2061 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002062 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002063 }
2064
Devang Patel8cca7b42009-08-04 05:01:35 +00002065 SmallVector<uint64_t, 64> Record;
2066
2067 const ValueEnumerator::ValueList &Vals = VE.getValues();
Craig Topper2617dcc2014-04-15 06:32:26 +00002068 Type *LastTy = nullptr;
Devang Patel8cca7b42009-08-04 05:01:35 +00002069 for (unsigned i = FirstVal; i != LastVal; ++i) {
2070 const Value *V = Vals[i].first;
Chris Lattner52523562007-04-24 00:16:04 +00002071 // If we need to switch types, do so now.
2072 if (V->getType() != LastTy) {
2073 LastTy = V->getType();
2074 Record.push_back(VE.getTypeID(LastTy));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002075 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2076 CONSTANTS_SETTYPE_ABBREV);
Chris Lattner52523562007-04-24 00:16:04 +00002077 Record.clear();
2078 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002079
Chris Lattner52523562007-04-24 00:16:04 +00002080 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
Dale Johannesenfd04c742009-10-13 20:46:56 +00002081 Record.push_back(unsigned(IA->hasSideEffects()) |
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002082 unsigned(IA->isAlignStack()) << 1 |
2083 unsigned(IA->getDialect()&1) << 2);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002084
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002085 // Add the asm string.
2086 const std::string &AsmStr = IA->getAsmString();
2087 Record.push_back(AsmStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002088 Record.append(AsmStr.begin(), AsmStr.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002089
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002090 // Add the constraint string.
2091 const std::string &ConstraintStr = IA->getConstraintString();
2092 Record.push_back(ConstraintStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002093 Record.append(ConstraintStr.begin(), ConstraintStr.end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002094 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002095 Record.clear();
Chris Lattner52523562007-04-24 00:16:04 +00002096 continue;
2097 }
2098 const Constant *C = cast<Constant>(V);
2099 unsigned Code = -1U;
2100 unsigned AbbrevToUse = 0;
2101 if (C->isNullValue()) {
2102 Code = bitc::CST_CODE_NULL;
2103 } else if (isa<UndefValue>(C)) {
2104 Code = bitc::CST_CODE_UNDEF;
2105 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
Bob Wilsone4077362013-09-09 19:14:35 +00002106 if (IV->getBitWidth() <= 64) {
2107 uint64_t V = IV->getSExtValue();
2108 emitSignedInt64(Record, V);
2109 Code = bitc::CST_CODE_INTEGER;
2110 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2111 } else { // Wide integers, > 64 bits in size.
2112 // We have an arbitrary precision integer value to write whose
2113 // bit width is > 64. However, in canonical unsigned integer
2114 // format it is likely that the high bits are going to be zero.
2115 // So, we only write the number of active words.
2116 unsigned NWords = IV->getValue().getActiveWords();
2117 const uint64_t *RawWords = IV->getValue().getRawData();
2118 for (unsigned i = 0; i != NWords; ++i) {
2119 emitSignedInt64(Record, RawWords[i]);
2120 }
2121 Code = bitc::CST_CODE_WIDE_INTEGER;
2122 }
Chris Lattner52523562007-04-24 00:16:04 +00002123 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2124 Code = bitc::CST_CODE_FLOAT;
Chris Lattner229907c2011-07-18 04:54:35 +00002125 Type *Ty = CFP->getType();
Dan Gohman518cda42011-12-17 00:04:22 +00002126 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002127 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
Chris Lattnerfdd87902009-10-05 05:54:46 +00002128 } else if (Ty->isX86_FP80Ty()) {
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002129 // api needed to prevent premature destruction
Dale Johannesen93eefa02009-03-23 21:16:53 +00002130 // bits are not in the same order as a normal i80 APInt, compensate.
Dale Johannesen54306fe2008-10-09 18:53:47 +00002131 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002132 const uint64_t *p = api.getRawData();
Dale Johannesen93eefa02009-03-23 21:16:53 +00002133 Record.push_back((p[1] << 48) | (p[0] >> 16));
2134 Record.push_back(p[0] & 0xffffLL);
Chris Lattnerfdd87902009-10-05 05:54:46 +00002135 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002136 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002137 const uint64_t *p = api.getRawData();
Dale Johannesen245dceb2007-09-11 18:32:33 +00002138 Record.push_back(p[0]);
2139 Record.push_back(p[1]);
Dale Johannesenbdad8092007-08-09 22:51:36 +00002140 } else {
2141 assert (0 && "Unknown FP type!");
Chris Lattner52523562007-04-24 00:16:04 +00002142 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002143 } else if (isa<ConstantDataSequential>(C) &&
2144 cast<ConstantDataSequential>(C)->isString()) {
2145 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2146 // Emit constant strings specially.
2147 unsigned NumElts = Str->getNumElements();
2148 // If this is a null-terminated string, use the denser CSTRING encoding.
2149 if (Str->isCString()) {
2150 Code = bitc::CST_CODE_CSTRING;
2151 --NumElts; // Don't encode the null, which isn't allowed by char6.
2152 } else {
2153 Code = bitc::CST_CODE_STRING;
2154 AbbrevToUse = String8Abbrev;
2155 }
2156 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2157 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2158 for (unsigned i = 0; i != NumElts; ++i) {
2159 unsigned char V = Str->getElementAsInteger(i);
2160 Record.push_back(V);
2161 isCStr7 &= (V & 128) == 0;
2162 if (isCStrChar6)
2163 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2164 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002165
Chris Lattner372dd1e2012-01-30 00:51:16 +00002166 if (isCStrChar6)
2167 AbbrevToUse = CString6Abbrev;
2168 else if (isCStr7)
2169 AbbrevToUse = CString7Abbrev;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002170 } else if (const ConstantDataSequential *CDS =
Chris Lattner372dd1e2012-01-30 00:51:16 +00002171 dyn_cast<ConstantDataSequential>(C)) {
Chris Lattner5d917072012-01-30 07:36:01 +00002172 Code = bitc::CST_CODE_DATA;
Chris Lattner372dd1e2012-01-30 00:51:16 +00002173 Type *EltTy = CDS->getType()->getElementType();
2174 if (isa<IntegerType>(EltTy)) {
2175 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2176 Record.push_back(CDS->getElementAsInteger(i));
Chris Lattner372dd1e2012-01-30 00:51:16 +00002177 } else {
Justin Bognera43eacb2016-01-06 22:31:32 +00002178 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2179 Record.push_back(
2180 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002181 }
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00002182 } else if (isa<ConstantAggregate>(C)) {
Chris Lattner52523562007-04-24 00:16:04 +00002183 Code = bitc::CST_CODE_AGGREGATE;
Pete Cooper125ad172015-06-25 20:51:38 +00002184 for (const Value *Op : C->operands())
2185 Record.push_back(VE.getValueID(Op));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002186 AbbrevToUse = AggregateAbbrev;
Chris Lattner52523562007-04-24 00:16:04 +00002187 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002188 switch (CE->getOpcode()) {
2189 default:
2190 if (Instruction::isCast(CE->getOpcode())) {
2191 Code = bitc::CST_CODE_CE_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002192 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002193 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2194 Record.push_back(VE.getValueID(C->getOperand(0)));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002195 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002196 } else {
2197 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2198 Code = bitc::CST_CODE_CE_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002199 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002200 Record.push_back(VE.getValueID(C->getOperand(0)));
2201 Record.push_back(VE.getValueID(C->getOperand(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002202 uint64_t Flags = getOptimizationFlags(CE);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002203 if (Flags != 0)
2204 Record.push_back(Flags);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002205 }
2206 break;
David Blaikieb9263572015-03-13 21:03:36 +00002207 case Instruction::GetElementPtr: {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002208 Code = bitc::CST_CODE_CE_GEP;
David Blaikieb9263572015-03-13 21:03:36 +00002209 const auto *GO = cast<GEPOperator>(C);
David Blaikieb9263572015-03-13 21:03:36 +00002210 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
Peter Collingbourned93620b2016-11-10 22:34:55 +00002211 if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2212 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2213 Record.push_back((*Idx << 1) | GO->isInBounds());
2214 } else if (GO->isInBounds())
2215 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002216 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2217 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2218 Record.push_back(VE.getValueID(C->getOperand(i)));
2219 }
2220 break;
David Blaikieb9263572015-03-13 21:03:36 +00002221 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002222 case Instruction::Select:
2223 Code = bitc::CST_CODE_CE_SELECT;
2224 Record.push_back(VE.getValueID(C->getOperand(0)));
2225 Record.push_back(VE.getValueID(C->getOperand(1)));
2226 Record.push_back(VE.getValueID(C->getOperand(2)));
2227 break;
2228 case Instruction::ExtractElement:
2229 Code = bitc::CST_CODE_CE_EXTRACTELT;
2230 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2231 Record.push_back(VE.getValueID(C->getOperand(0)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002232 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002233 Record.push_back(VE.getValueID(C->getOperand(1)));
2234 break;
2235 case Instruction::InsertElement:
2236 Code = bitc::CST_CODE_CE_INSERTELT;
2237 Record.push_back(VE.getValueID(C->getOperand(0)));
2238 Record.push_back(VE.getValueID(C->getOperand(1)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002239 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002240 Record.push_back(VE.getValueID(C->getOperand(2)));
2241 break;
2242 case Instruction::ShuffleVector:
Nate Begeman94aa38d2009-02-12 21:28:33 +00002243 // If the return type and argument types are the same, this is a
2244 // standard shufflevector instruction. If the types are different,
2245 // then the shuffle is widening or truncating the input vectors, and
2246 // the argument type must also be encoded.
2247 if (C->getType() == C->getOperand(0)->getType()) {
2248 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2249 } else {
2250 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2251 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2252 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002253 Record.push_back(VE.getValueID(C->getOperand(0)));
2254 Record.push_back(VE.getValueID(C->getOperand(1)));
2255 Record.push_back(VE.getValueID(C->getOperand(2)));
2256 break;
2257 case Instruction::ICmp:
2258 case Instruction::FCmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002259 Code = bitc::CST_CODE_CE_CMP;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002260 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2261 Record.push_back(VE.getValueID(C->getOperand(0)));
2262 Record.push_back(VE.getValueID(C->getOperand(1)));
2263 Record.push_back(CE->getPredicate());
2264 break;
2265 }
Chris Lattnerf540d742009-10-28 05:24:40 +00002266 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
Chris Lattnerf540d742009-10-28 05:24:40 +00002267 Code = bitc::CST_CODE_BLOCKADDRESS;
2268 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2269 Record.push_back(VE.getValueID(BA->getFunction()));
2270 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
Chris Lattner52523562007-04-24 00:16:04 +00002271 } else {
Dan Gohman47dc8fd2010-07-21 21:18:37 +00002272#ifndef NDEBUG
2273 C->dump();
2274#endif
Torok Edwinfbcc6632009-07-14 16:55:14 +00002275 llvm_unreachable("Unknown constant!");
Chris Lattner52523562007-04-24 00:16:04 +00002276 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002277 Stream.EmitRecord(Code, Record, AbbrevToUse);
Chris Lattner52523562007-04-24 00:16:04 +00002278 Record.clear();
2279 }
2280
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002281 Stream.ExitBlock();
Chris Lattner52523562007-04-24 00:16:04 +00002282}
2283
Teresa Johnson37687f32016-04-23 04:30:47 +00002284void ModuleBitcodeWriter::writeModuleConstants() {
Chris Lattner52523562007-04-24 00:16:04 +00002285 const ValueEnumerator::ValueList &Vals = VE.getValues();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002286
Chris Lattner52523562007-04-24 00:16:04 +00002287 // Find the first constant to emit, which is the first non-globalvalue value.
2288 // We know globalvalues have been emitted by WriteModuleInfo.
2289 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2290 if (!isa<GlobalValue>(Vals[i].first)) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002291 writeConstants(i, Vals.size(), true);
Chris Lattner52523562007-04-24 00:16:04 +00002292 return;
2293 }
2294 }
2295}
Chris Lattner215e9cd2007-04-23 20:35:01 +00002296
Teresa Johnson37687f32016-04-23 04:30:47 +00002297/// pushValueAndType - The file has to encode both the value and type id for
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002298/// many values, because we need to know what type to create for forward
2299/// references. However, most operands are not forward references, so this type
2300/// field is not needed.
2301///
2302/// This function adds V's value ID to Vals. If the value ID is higher than the
2303/// instruction ID, then it is a forward reference, and it also includes the
Jan Wen Voungafaced02012-10-11 20:20:40 +00002304/// type ID. The value ID that is written is encoded relative to the InstID.
Teresa Johnson37687f32016-04-23 04:30:47 +00002305bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2306 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002307 unsigned ValID = VE.getValueID(V);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002308 // Make encoding relative to the InstID.
2309 Vals.push_back(InstID - ValID);
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002310 if (ValID >= InstID) {
2311 Vals.push_back(VE.getTypeID(V->getType()));
2312 return true;
2313 }
2314 return false;
2315}
2316
Teresa Johnson37687f32016-04-23 04:30:47 +00002317void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2318 unsigned InstID) {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002319 SmallVector<unsigned, 64> Record;
2320 LLVMContext &C = CS.getInstruction()->getContext();
2321
2322 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
Sanjoy Das54c3ca62015-11-07 01:56:04 +00002323 const auto &Bundle = CS.getOperandBundleAt(i);
Sanjoy Dasb9ca6dc2015-11-10 20:13:15 +00002324 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002325
2326 for (auto &Input : Bundle.Inputs)
Teresa Johnson37687f32016-04-23 04:30:47 +00002327 pushValueAndType(Input, InstID, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002328
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002329 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002330 Record.clear();
2331 }
2332}
2333
Teresa Johnson37687f32016-04-23 04:30:47 +00002334/// pushValue - Like pushValueAndType, but where the type of the value is
Jan Wen Voungafaced02012-10-11 20:20:40 +00002335/// omitted (perhaps it was already encoded in an earlier operand).
Teresa Johnson37687f32016-04-23 04:30:47 +00002336void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2337 SmallVectorImpl<unsigned> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002338 unsigned ValID = VE.getValueID(V);
2339 Vals.push_back(InstID - ValID);
2340}
2341
Teresa Johnson37687f32016-04-23 04:30:47 +00002342void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2343 SmallVectorImpl<uint64_t> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002344 unsigned ValID = VE.getValueID(V);
2345 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2346 emitSignedInt64(Vals, diff);
2347}
2348
Chris Lattnere6e364c2007-04-26 05:53:54 +00002349/// WriteInstruction - Emit an instruction to the specified stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00002350void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2351 unsigned InstID,
2352 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnere6e364c2007-04-26 05:53:54 +00002353 unsigned Code = 0;
2354 unsigned AbbrevToUse = 0;
Devang Patelaf206b82009-09-18 19:26:43 +00002355 VE.setInstructionID(&I);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002356 switch (I.getOpcode()) {
2357 default:
2358 if (Instruction::isCast(I.getOpcode())) {
Chris Lattner0a603252007-05-01 02:13:26 +00002359 Code = bitc::FUNC_CODE_INST_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002360 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002361 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002362 Vals.push_back(VE.getTypeID(I.getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002363 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
Chris Lattnere6e364c2007-04-26 05:53:54 +00002364 } else {
2365 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
Chris Lattner9f35f912007-05-02 04:26:36 +00002366 Code = bitc::FUNC_CODE_INST_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002367 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002368 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
Teresa Johnson37687f32016-04-23 04:30:47 +00002369 pushValue(I.getOperand(1), InstID, Vals);
2370 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2371 uint64_t Flags = getOptimizationFlags(&I);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002372 if (Flags != 0) {
2373 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2374 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2375 Vals.push_back(Flags);
2376 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002377 }
2378 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002379
David Blaikieb5b5efd2015-02-25 01:08:52 +00002380 case Instruction::GetElementPtr: {
Chris Lattner0a603252007-05-01 02:13:26 +00002381 Code = bitc::FUNC_CODE_INST_GEP;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002382 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2383 auto &GEPInst = cast<GetElementPtrInst>(I);
2384 Vals.push_back(GEPInst.isInBounds());
2385 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002386 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002387 pushValueAndType(I.getOperand(i), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002388 break;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002389 }
Dan Gohmanca0256a2008-05-31 19:11:15 +00002390 case Instruction::ExtractValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002391 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002392 pushValueAndType(I.getOperand(0), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002393 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002394 Vals.append(EVI->idx_begin(), EVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002395 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002396 }
2397 case Instruction::InsertValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002398 Code = bitc::FUNC_CODE_INST_INSERTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002399 pushValueAndType(I.getOperand(0), InstID, Vals);
2400 pushValueAndType(I.getOperand(1), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002401 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002402 Vals.append(IVI->idx_begin(), IVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002403 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002404 }
Chris Lattner0a603252007-05-01 02:13:26 +00002405 case Instruction::Select:
Dan Gohmanc5d28922008-09-16 01:01:33 +00002406 Code = bitc::FUNC_CODE_INST_VSELECT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002407 pushValueAndType(I.getOperand(1), InstID, Vals);
2408 pushValue(I.getOperand(2), InstID, Vals);
2409 pushValueAndType(I.getOperand(0), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002410 break;
2411 case Instruction::ExtractElement:
2412 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002413 pushValueAndType(I.getOperand(0), InstID, Vals);
2414 pushValueAndType(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002415 break;
2416 case Instruction::InsertElement:
2417 Code = bitc::FUNC_CODE_INST_INSERTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002418 pushValueAndType(I.getOperand(0), InstID, Vals);
2419 pushValue(I.getOperand(1), InstID, Vals);
2420 pushValueAndType(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002421 break;
2422 case Instruction::ShuffleVector:
2423 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002424 pushValueAndType(I.getOperand(0), InstID, Vals);
2425 pushValue(I.getOperand(1), InstID, Vals);
2426 pushValue(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002427 break;
2428 case Instruction::ICmp:
James Molloy88eb5352015-07-10 12:52:00 +00002429 case Instruction::FCmp: {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002430 // compare returning Int1Ty or vector of Int1Ty
2431 Code = bitc::FUNC_CODE_INST_CMP2;
Teresa Johnson37687f32016-04-23 04:30:47 +00002432 pushValueAndType(I.getOperand(0), InstID, Vals);
2433 pushValue(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002434 Vals.push_back(cast<CmpInst>(I).getPredicate());
Teresa Johnson37687f32016-04-23 04:30:47 +00002435 uint64_t Flags = getOptimizationFlags(&I);
James Molloy88eb5352015-07-10 12:52:00 +00002436 if (Flags != 0)
2437 Vals.push_back(Flags);
Chris Lattner0a603252007-05-01 02:13:26 +00002438 break;
James Molloy88eb5352015-07-10 12:52:00 +00002439 }
Chris Lattner0a603252007-05-01 02:13:26 +00002440
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002441 case Instruction::Ret:
Devang Patelbbfd8742008-02-26 01:29:32 +00002442 {
2443 Code = bitc::FUNC_CODE_INST_RET;
2444 unsigned NumOperands = I.getNumOperands();
Devang Patelbbfd8742008-02-26 01:29:32 +00002445 if (NumOperands == 0)
2446 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2447 else if (NumOperands == 1) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002448 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Devang Patelbbfd8742008-02-26 01:29:32 +00002449 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2450 } else {
2451 for (unsigned i = 0, e = NumOperands; i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002452 pushValueAndType(I.getOperand(i), InstID, Vals);
Devang Patelbbfd8742008-02-26 01:29:32 +00002453 }
2454 }
Chris Lattner0a603252007-05-01 02:13:26 +00002455 break;
2456 case Instruction::Br:
Gabor Greif1933b002009-01-30 18:27:21 +00002457 {
2458 Code = bitc::FUNC_CODE_INST_BR;
David Blaikieb78e9e52013-02-11 01:16:51 +00002459 const BranchInst &II = cast<BranchInst>(I);
Gabor Greif1933b002009-01-30 18:27:21 +00002460 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2461 if (II.isConditional()) {
2462 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002463 pushValue(II.getCondition(), InstID, Vals);
Gabor Greif1933b002009-01-30 18:27:21 +00002464 }
Chris Lattner0a603252007-05-01 02:13:26 +00002465 }
2466 break;
2467 case Instruction::Switch:
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002468 {
2469 Code = bitc::FUNC_CODE_INST_SWITCH;
David Blaikieb78e9e52013-02-11 01:16:51 +00002470 const SwitchInst &SI = cast<SwitchInst>(I);
Bob Wilsone4077362013-09-09 19:14:35 +00002471 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002472 pushValue(SI.getCondition(), InstID, Vals);
Bob Wilsone4077362013-09-09 19:14:35 +00002473 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
Chandler Carruth927d8e62017-04-12 07:27:28 +00002474 for (auto Case : SI.cases()) {
Sanjay Patel225d65f2015-11-13 16:21:23 +00002475 Vals.push_back(VE.getValueID(Case.getCaseValue()));
2476 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002477 }
2478 }
Chris Lattner0a603252007-05-01 02:13:26 +00002479 break;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00002480 case Instruction::IndirectBr:
2481 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
Chris Lattner3ed871f2009-10-27 19:13:16 +00002482 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Jan Wen Voungafaced02012-10-11 20:20:40 +00002483 // Encode the address operand as relative, but not the basic blocks.
Teresa Johnson37687f32016-04-23 04:30:47 +00002484 pushValue(I.getOperand(0), InstID, Vals);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002485 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
Chris Lattner3ed871f2009-10-27 19:13:16 +00002486 Vals.push_back(VE.getValueID(I.getOperand(i)));
2487 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002488
Chris Lattnerb811e952007-05-01 07:03:37 +00002489 case Instruction::Invoke: {
Gabor Greif4b79e472009-01-16 18:40:27 +00002490 const InvokeInst *II = cast<InvokeInst>(&I);
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002491 const Value *Callee = II->getCalledValue();
2492 FunctionType *FTy = II->getFunctionType();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002493
2494 if (II->hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002495 writeOperandBundles(II, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002496
Chris Lattner0a603252007-05-01 02:13:26 +00002497 Code = bitc::FUNC_CODE_INST_INVOKE;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002498
Reid Klecknerb4a2d182017-04-24 20:38:30 +00002499 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002500 Vals.push_back(II->getCallingConv() | 1 << 13);
Gabor Greif6ecd6f42009-01-07 22:39:29 +00002501 Vals.push_back(VE.getValueID(II->getNormalDest()));
2502 Vals.push_back(VE.getValueID(II->getUnwindDest()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002503 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002504 pushValueAndType(Callee, InstID, Vals);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002505
Chris Lattner0a603252007-05-01 02:13:26 +00002506 // Emit value #'s for the fixed parameters.
Chris Lattner0a603252007-05-01 02:13:26 +00002507 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002508 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
Chris Lattner0a603252007-05-01 02:13:26 +00002509
2510 // Emit type/value pairs for varargs params.
2511 if (FTy->isVarArg()) {
Mehdi Amini7cf63822016-09-19 21:27:04 +00002512 for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002513 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002514 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
Chris Lattner0a603252007-05-01 02:13:26 +00002515 }
2516 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002517 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00002518 case Instruction::Resume:
2519 Code = bitc::FUNC_CODE_INST_RESUME;
Teresa Johnson37687f32016-04-23 04:30:47 +00002520 pushValueAndType(I.getOperand(0), InstID, Vals);
Bill Wendlingf891bf82011-07-31 06:30:59 +00002521 break;
David Majnemer654e1302015-07-31 17:58:14 +00002522 case Instruction::CleanupRet: {
2523 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2524 const auto &CRI = cast<CleanupReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002525 pushValue(CRI.getCleanupPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002526 if (CRI.hasUnwindDest())
2527 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2528 break;
2529 }
2530 case Instruction::CatchRet: {
2531 Code = bitc::FUNC_CODE_INST_CATCHRET;
2532 const auto &CRI = cast<CatchReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002533 pushValue(CRI.getCatchPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002534 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2535 break;
2536 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00002537 case Instruction::CleanupPad:
David Majnemer654e1302015-07-31 17:58:14 +00002538 case Instruction::CatchPad: {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002539 const auto &FuncletPad = cast<FuncletPadInst>(I);
2540 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2541 : bitc::FUNC_CODE_INST_CLEANUPPAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002542 pushValue(FuncletPad.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002543
2544 unsigned NumArgOperands = FuncletPad.getNumArgOperands();
David Majnemer654e1302015-07-31 17:58:14 +00002545 Vals.push_back(NumArgOperands);
2546 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
Teresa Johnson37687f32016-04-23 04:30:47 +00002547 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002548 break;
2549 }
2550 case Instruction::CatchSwitch: {
2551 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2552 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2553
Teresa Johnson37687f32016-04-23 04:30:47 +00002554 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002555
2556 unsigned NumHandlers = CatchSwitch.getNumHandlers();
2557 Vals.push_back(NumHandlers);
2558 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2559 Vals.push_back(VE.getValueID(CatchPadBB));
2560
2561 if (CatchSwitch.hasUnwindDest())
2562 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
David Majnemer654e1302015-07-31 17:58:14 +00002563 break;
2564 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002565 case Instruction::Unreachable:
2566 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
Chris Lattnercc6d4c92007-05-06 01:28:01 +00002567 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002568 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002569
Jay Foad372ad642011-06-20 14:18:48 +00002570 case Instruction::PHI: {
2571 const PHINode &PN = cast<PHINode>(I);
Chris Lattner0a603252007-05-01 02:13:26 +00002572 Code = bitc::FUNC_CODE_INST_PHI;
Jan Wen Voungafaced02012-10-11 20:20:40 +00002573 // With the newer instruction encoding, forward references could give
2574 // negative valued IDs. This is most common for PHIs, so we use
2575 // signed VBRs.
2576 SmallVector<uint64_t, 128> Vals64;
2577 Vals64.push_back(VE.getTypeID(PN.getType()));
Jay Foad372ad642011-06-20 14:18:48 +00002578 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002579 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002580 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
Jay Foad372ad642011-06-20 14:18:48 +00002581 }
Jan Wen Voungafaced02012-10-11 20:20:40 +00002582 // Emit a Vals64 vector and exit.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002583 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002584 Vals64.clear();
2585 return;
Jay Foad372ad642011-06-20 14:18:48 +00002586 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002587
Bill Wendlingfae14752011-08-12 20:24:12 +00002588 case Instruction::LandingPad: {
2589 const LandingPadInst &LP = cast<LandingPadInst>(I);
2590 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2591 Vals.push_back(VE.getTypeID(LP.getType()));
Bill Wendlingfae14752011-08-12 20:24:12 +00002592 Vals.push_back(LP.isCleanup());
2593 Vals.push_back(LP.getNumClauses());
2594 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2595 if (LP.isCatch(I))
2596 Vals.push_back(LandingPadInst::Catch);
2597 else
2598 Vals.push_back(LandingPadInst::Filter);
Teresa Johnson37687f32016-04-23 04:30:47 +00002599 pushValueAndType(LP.getClause(I), InstID, Vals);
Bill Wendlingfae14752011-08-12 20:24:12 +00002600 }
2601 break;
2602 }
2603
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002604 case Instruction::Alloca: {
Chris Lattner0a603252007-05-01 02:13:26 +00002605 Code = bitc::FUNC_CODE_INST_ALLOCA;
David Blaikiebdb49102015-04-28 16:51:01 +00002606 const AllocaInst &AI = cast<AllocaInst>(I);
2607 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
Dan Gohman9da5bb02010-05-28 01:38:28 +00002608 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002609 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002610 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2611 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2612 "not enough bits for maximum alignment");
2613 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2614 AlignRecord |= AI.isUsedWithInAlloca() << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00002615 AlignRecord |= 1 << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00002616 AlignRecord |= AI.isSwiftError() << 7;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002617 Vals.push_back(AlignRecord);
Chris Lattner0a603252007-05-01 02:13:26 +00002618 break;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002619 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002620
Chris Lattner0a603252007-05-01 02:13:26 +00002621 case Instruction::Load:
Eli Friedman59b66882011-08-09 23:02:53 +00002622 if (cast<LoadInst>(I).isAtomic()) {
2623 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002624 pushValueAndType(I.getOperand(0), InstID, Vals);
Eli Friedman59b66882011-08-09 23:02:53 +00002625 } else {
2626 Code = bitc::FUNC_CODE_INST_LOAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002627 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
Eli Friedman59b66882011-08-09 23:02:53 +00002628 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2629 }
David Blaikie85035652015-02-25 01:07:20 +00002630 Vals.push_back(VE.getTypeID(I.getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002631 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2632 Vals.push_back(cast<LoadInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002633 if (cast<LoadInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002634 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
2635 Vals.push_back(getEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
Eli Friedman59b66882011-08-09 23:02:53 +00002636 }
Chris Lattner0a603252007-05-01 02:13:26 +00002637 break;
2638 case Instruction::Store:
Eli Friedman59b66882011-08-09 23:02:53 +00002639 if (cast<StoreInst>(I).isAtomic())
2640 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2641 else
2642 Code = bitc::FUNC_CODE_INST_STORE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002643 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2644 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
Chris Lattner0a603252007-05-01 02:13:26 +00002645 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2646 Vals.push_back(cast<StoreInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002647 if (cast<StoreInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002648 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
2649 Vals.push_back(getEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
Eli Friedman59b66882011-08-09 23:02:53 +00002650 }
Chris Lattner0a603252007-05-01 02:13:26 +00002651 break;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002652 case Instruction::AtomicCmpXchg:
2653 Code = bitc::FUNC_CODE_INST_CMPXCHG;
Teresa Johnson37687f32016-04-23 04:30:47 +00002654 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2655 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2656 pushValue(I.getOperand(2), InstID, Vals); // newval.
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002657 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002658 Vals.push_back(
2659 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2660 Vals.push_back(
2661 getEncodedSynchScope(cast<AtomicCmpXchgInst>(I).getSynchScope()));
2662 Vals.push_back(
2663 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
Tim Northover420a2162014-06-13 14:24:07 +00002664 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002665 break;
2666 case Instruction::AtomicRMW:
2667 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
Teresa Johnson37687f32016-04-23 04:30:47 +00002668 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2669 pushValue(I.getOperand(1), InstID, Vals); // val.
2670 Vals.push_back(
2671 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002672 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002673 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2674 Vals.push_back(
2675 getEncodedSynchScope(cast<AtomicRMWInst>(I).getSynchScope()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002676 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002677 case Instruction::Fence:
2678 Code = bitc::FUNC_CODE_INST_FENCE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002679 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
2680 Vals.push_back(getEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
Eli Friedmanfee02c62011-07-25 23:16:38 +00002681 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002682 case Instruction::Call: {
Gabor Greife9afee22010-06-26 09:35:09 +00002683 const CallInst &CI = cast<CallInst>(I);
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002684 FunctionType *FTy = CI.getFunctionType();
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002685
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002686 if (CI.hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002687 writeOperandBundles(&CI, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002688
Chris Lattnerc44070802011-06-17 18:17:37 +00002689 Code = bitc::FUNC_CODE_INST_CALL;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002690
Reid Klecknerb4a2d182017-04-24 20:38:30 +00002691 Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002692
Teresa Johnson37687f32016-04-23 04:30:47 +00002693 unsigned Flags = getOptimizationFlags(&I);
Akira Hatanaka97cb3972015-11-07 02:48:49 +00002694 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2695 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2696 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2697 1 << bitc::CALL_EXPLICIT_TYPE |
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002698 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2699 unsigned(Flags != 0) << bitc::CALL_FMF);
2700 if (Flags != 0)
2701 Vals.push_back(Flags);
2702
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002703 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002704 pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002705
Chris Lattner0a603252007-05-01 02:13:26 +00002706 // Emit value #'s for the fixed parameters.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002707 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2708 // Check for labels (can happen with asm labels).
2709 if (FTy->getParamType(i)->isLabelTy())
2710 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2711 else
Teresa Johnson37687f32016-04-23 04:30:47 +00002712 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002713 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002714
Chris Lattnerb811e952007-05-01 07:03:37 +00002715 // Emit type/value pairs for varargs params.
2716 if (FTy->isVarArg()) {
Gabor Greife9afee22010-06-26 09:35:09 +00002717 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002718 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002719 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
Chris Lattner0a603252007-05-01 02:13:26 +00002720 }
2721 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002722 }
Chris Lattner0a603252007-05-01 02:13:26 +00002723 case Instruction::VAArg:
2724 Code = bitc::FUNC_CODE_INST_VAARG;
2725 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
Teresa Johnson37687f32016-04-23 04:30:47 +00002726 pushValue(I.getOperand(0), InstID, Vals); // valist.
Chris Lattner0a603252007-05-01 02:13:26 +00002727 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2728 break;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002729 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002730
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002731 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002732 Vals.clear();
2733}
2734
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002735/// Write a GlobalValue VST to the module. The purpose of this data structure is
2736/// to allow clients to efficiently find the function body.
2737void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
2738 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
2739 // Get the offset of the VST we are writing, and backpatch it into
2740 // the VST forward declaration record.
2741 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2742 // The BitcodeStartBit was the stream offset of the identification block.
2743 VSTOffset -= bitcodeStartBit();
2744 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2745 // Note that we add 1 here because the offset is relative to one word
2746 // before the start of the identification block, which was historically
2747 // always the start of the regular bitcode header.
2748 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002749
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002750 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
Chris Lattner2eae59f2007-05-04 20:34:50 +00002751
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002752 auto Abbv = std::make_shared<BitCodeAbbrev>();
2753 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2754 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2755 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2756 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnsonff642b92015-09-17 20:12:00 +00002757
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002758 for (const Function &F : M) {
2759 uint64_t Record[2];
Teresa Johnsonff642b92015-09-17 20:12:00 +00002760
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002761 if (F.isDeclaration())
2762 continue;
Teresa Johnsoncd21a642016-07-17 14:47:01 +00002763
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002764 Record[0] = VE.getValueID(&F);
2765
2766 // Save the word offset of the function (from the start of the
2767 // actual bitcode written to the stream).
2768 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
2769 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2770 // Note that we add 1 here because the offset is relative to one word
2771 // before the start of the identification block, which was historically
2772 // always the start of the regular bitcode header.
2773 Record[1] = BitcodeIndex / 32 + 1;
2774
2775 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002776 }
2777
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002778 Stream.ExitBlock();
2779}
2780
2781/// Emit names for arguments, instructions and basic blocks in a function.
2782void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
2783 const ValueSymbolTable &VST) {
2784 if (VST.empty())
2785 return;
2786
2787 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2788
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002789 // FIXME: Set up the abbrev, we know how many values there are!
2790 // FIXME: We know if the type names can use 7-bit ascii.
Teresa Johnsoncd21a642016-07-17 14:47:01 +00002791 SmallVector<uint64_t, 64> NameVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002792
Yaron Keren001e2e42015-08-10 07:04:29 +00002793 for (const ValueName &Name : VST) {
Chris Lattner4d925982007-05-04 20:52:02 +00002794 // Figure out the encoding to use for the name.
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002795 StringEncoding Bits =
2796 getStringEncoding(Name.getKeyData(), Name.getKeyLength());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002797
Chris Lattnera0987962007-05-04 21:31:13 +00002798 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
Teresa Johnsonff642b92015-09-17 20:12:00 +00002799 NameVals.push_back(VE.getValueID(Name.getValue()));
2800
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002801 // VST_CODE_ENTRY: [valueid, namechar x N]
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002802 // VST_CODE_BBENTRY: [bbid, namechar x N]
Chris Lattner6be58c62007-05-03 22:18:21 +00002803 unsigned Code;
Yaron Keren001e2e42015-08-10 07:04:29 +00002804 if (isa<BasicBlock>(Name.getValue())) {
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002805 Code = bitc::VST_CODE_BBENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002806 if (Bits == SE_Char6)
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002807 AbbrevToUse = VST_BBENTRY_6_ABBREV;
Chris Lattner6be58c62007-05-03 22:18:21 +00002808 } else {
2809 Code = bitc::VST_CODE_ENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002810 if (Bits == SE_Char6)
Chris Lattnere760d6f2007-05-05 01:26:50 +00002811 AbbrevToUse = VST_ENTRY_6_ABBREV;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002812 else if (Bits == SE_Fixed7)
Chris Lattnere760d6f2007-05-05 01:26:50 +00002813 AbbrevToUse = VST_ENTRY_7_ABBREV;
Chris Lattner6be58c62007-05-03 22:18:21 +00002814 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002815
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002816 for (const auto P : Name.getKey())
2817 NameVals.push_back((unsigned char)P);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002818
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002819 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002820 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002821 NameVals.clear();
2822 }
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002823
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002824 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00002825}
2826
Teresa Johnson37687f32016-04-23 04:30:47 +00002827void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002828 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
2829 unsigned Code;
2830 if (isa<BasicBlock>(Order.V))
2831 Code = bitc::USELIST_CODE_BB;
2832 else
2833 Code = bitc::USELIST_CODE_DEFAULT;
2834
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002835 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002836 Record.push_back(VE.getValueID(Order.V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002837 Stream.EmitRecord(Code, Record);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002838}
2839
Teresa Johnson37687f32016-04-23 04:30:47 +00002840void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00002841 assert(VE.shouldPreserveUseListOrder() &&
2842 "Expected to be preserving use-list order");
2843
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002844 auto hasMore = [&]() {
2845 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
2846 };
2847 if (!hasMore())
2848 // Nothing to do.
2849 return;
2850
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002851 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002852 while (hasMore()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002853 writeUseList(std::move(VE.UseListOrders.back()));
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002854 VE.UseListOrders.pop_back();
2855 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002856 Stream.ExitBlock();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002857}
2858
Teresa Johnson403a7872015-10-04 14:33:43 +00002859/// Emit a function body to the module stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00002860void ModuleBitcodeWriter::writeFunction(
2861 const Function &F,
2862 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00002863 // Save the bitcode index of the start of this function block for recording
2864 // in the VST.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002865 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00002866
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002867 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
Chad Rosier6a11b642011-06-03 17:02:19 +00002868 VE.incorporateFunction(F);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002869
2870 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002871
Chris Lattnere6e364c2007-04-26 05:53:54 +00002872 // Emit the number of basic blocks, so the reader can create them ahead of
2873 // time.
2874 Vals.push_back(VE.getBasicBlocks().size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002875 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002876 Vals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002877
Chris Lattnere6e364c2007-04-26 05:53:54 +00002878 // If there are function-local constants, emit them now.
2879 unsigned CstStart, CstEnd;
2880 VE.getFunctionConstantRange(CstStart, CstEnd);
Teresa Johnson37687f32016-04-23 04:30:47 +00002881 writeConstants(CstStart, CstEnd, false);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002882
Victor Hernandez6c730de2010-01-14 01:50:08 +00002883 // If there is function-local metadata, emit it now.
Teresa Johnson37687f32016-04-23 04:30:47 +00002884 writeFunctionMetadata(F);
Victor Hernandez6c730de2010-01-14 01:50:08 +00002885
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002886 // Keep a running idea of what the instruction ID is.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002887 unsigned InstID = CstEnd;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002888
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002889 bool NeedsMetadataAttachment = F.hasMetadata();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002890
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002891 DILocation *LastDL = nullptr;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002892 // Finally, emit all the instructions, in order.
Nick Lewycky4d43d3c2008-04-25 16:53:59 +00002893 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002894 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
2895 I != E; ++I) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002896 writeInstruction(*I, InstID, Vals);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002897
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002898 if (!I->getType()->isVoidTy())
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002899 ++InstID;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002900
Chris Lattner07d09ed2010-04-03 02:17:50 +00002901 // If the instruction has metadata, write a metadata attachment later.
2902 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002903
Chris Lattner07d09ed2010-04-03 02:17:50 +00002904 // If the instruction has a debug location, emit it.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002905 DILocation *DL = I->getDebugLoc();
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00002906 if (!DL)
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002907 continue;
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002908
2909 if (DL == LastDL) {
Chris Lattner07d09ed2010-04-03 02:17:50 +00002910 // Just repeat the same debug loc as last time.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002911 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002912 continue;
Chris Lattner07d09ed2010-04-03 02:17:50 +00002913 }
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002914
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00002915 Vals.push_back(DL->getLine());
2916 Vals.push_back(DL->getColumn());
2917 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
2918 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002919 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00002920 Vals.clear();
Duncan P. N. Exon Smith538ef562015-05-06 22:51:12 +00002921
2922 LastDL = DL;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002923 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002924
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002925 // Emit names for all the instructions etc.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00002926 if (auto *Symtab = F.getValueSymbolTable())
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002927 writeFunctionLevelValueSymbolTable(*Symtab);
Devang Patelaf206b82009-09-18 19:26:43 +00002928
Chris Lattner07d09ed2010-04-03 02:17:50 +00002929 if (NeedsMetadataAttachment)
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002930 writeFunctionMetadataAttachment(F);
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00002931 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00002932 writeUseListBlock(&F);
Chad Rosier6a11b642011-06-03 17:02:19 +00002933 VE.purgeFunction();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002934 Stream.ExitBlock();
Chris Lattner831d4202007-04-26 03:27:58 +00002935}
2936
Chris Lattner702658c2007-05-04 18:26:27 +00002937// Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00002938void ModuleBitcodeWriter::writeBlockInfo() {
Chris Lattner702658c2007-05-04 18:26:27 +00002939 // We only want to emit block info records for blocks that have multiple
Jan Wen Voungafaced02012-10-11 20:20:40 +00002940 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
Jan Wen Voung8c9e9412012-10-11 21:45:16 +00002941 // Other blocks can define their abbrevs inline.
Peter Collingbourned3a6c702016-11-01 01:18:57 +00002942 Stream.EnterBlockInfoBlock();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002943
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002944 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002945 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00002946 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
2947 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2948 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2949 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002950 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002951 VST_ENTRY_8_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002952 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00002953 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002954
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002955 { // 7-bit fixed width VST_CODE_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002956 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00002957 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2958 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2959 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2960 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002961 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002962 VST_ENTRY_7_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002963 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00002964 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002965 { // 6-bit char6 VST_CODE_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002966 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnere760d6f2007-05-05 01:26:50 +00002967 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
2968 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2969 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2970 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002971 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002972 VST_ENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002973 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnere760d6f2007-05-05 01:26:50 +00002974 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002975 { // 6-bit char6 VST_CODE_BBENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002976 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00002977 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
2978 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
2979 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chris Lattnere760d6f2007-05-05 01:26:50 +00002980 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002981 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002982 VST_BBENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002983 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00002984 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002985
2986
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002987
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002988 { // SETTYPE abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002989 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002990 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
2991 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
David Blaikie7b028102015-02-25 00:51:52 +00002992 VE.computeBitsRequiredForTypeIndicies()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002993 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00002994 CONSTANTS_SETTYPE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00002995 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002996 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002997
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002998 { // INTEGER abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002999 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003000 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3001 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003002 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003003 CONSTANTS_INTEGER_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003004 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003005 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003006
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003007 { // CE_CAST abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003008 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003009 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3010 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3011 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
David Blaikie7b028102015-02-25 00:51:52 +00003012 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003013 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3014
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003015 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003016 CONSTANTS_CE_CAST_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003017 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003018 }
3019 { // NULL abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003020 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003021 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003022 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003023 CONSTANTS_NULL_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003024 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003025 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003026
Chris Lattnerb80751d2007-05-05 07:44:49 +00003027 // FIXME: This should only use space for first class types!
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003028
Chris Lattnerb80751d2007-05-05 07:44:49 +00003029 { // INST_LOAD abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003030 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb80751d2007-05-05 07:44:49 +00003031 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
Chris Lattnerb80751d2007-05-05 07:44:49 +00003032 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
David Blaikie85035652015-02-25 01:07:20 +00003033 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3034 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerb80751d2007-05-05 07:44:49 +00003035 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3036 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003037 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003038 FUNCTION_INST_LOAD_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003039 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerb80751d2007-05-05 07:44:49 +00003040 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003041 { // INST_BINOP abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003042 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003043 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3044 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3045 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3046 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003047 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003048 FUNCTION_INST_BINOP_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003049 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003050 }
Dan Gohman0ebd6962009-07-20 21:19:07 +00003051 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003052 auto Abbv = std::make_shared<BitCodeAbbrev>();
Dan Gohman0ebd6962009-07-20 21:19:07 +00003053 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3054 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3055 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3056 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3057 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003058 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003059 FUNCTION_INST_BINOP_FLAGS_ABBREV)
Dan Gohman0ebd6962009-07-20 21:19:07 +00003060 llvm_unreachable("Unexpected abbrev ordering!");
3061 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003062 { // INST_CAST abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003063 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003064 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3065 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3066 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
David Blaikie7b028102015-02-25 00:51:52 +00003067 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003068 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003069 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003070 FUNCTION_INST_CAST_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003071 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003072 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003073
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003074 { // INST_RET abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003075 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003076 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003077 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003078 FUNCTION_INST_RET_VOID_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003079 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003080 }
3081 { // INST_RET abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003082 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003083 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3084 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003085 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003086 FUNCTION_INST_RET_VAL_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003087 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003088 }
3089 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003090 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003091 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003092 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003093 FUNCTION_INST_UNREACHABLE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003094 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003095 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00003096 {
David Blaikie7ad9dc12017-01-04 22:36:33 +00003097 auto Abbv = std::make_shared<BitCodeAbbrev>();
David Blaikieb5b5efd2015-02-25 01:08:52 +00003098 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3099 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3100 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3101 Log2_32_Ceil(VE.getTypes().size() + 1)));
3102 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3103 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003104 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
David Blaikieb5b5efd2015-02-25 01:08:52 +00003105 FUNCTION_INST_GEP_ABBREV)
3106 llvm_unreachable("Unexpected abbrev ordering!");
3107 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003108
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003109 Stream.ExitBlock();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003110}
3111
Teresa Johnson403a7872015-10-04 14:33:43 +00003112/// Write the module path strings, currently only used when generating
3113/// a combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003114void IndexBitcodeWriter::writeModStrings() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003115 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
Teresa Johnson403a7872015-10-04 14:33:43 +00003116
3117 // TODO: See which abbrev sizes we actually need to emit
3118
3119 // 8-bit fixed-width MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003120 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003121 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3122 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3123 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3124 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003125 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003126
3127 // 7-bit fixed width MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003128 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003129 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3130 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3131 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3132 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003133 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003134
3135 // 6-bit char6 MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003136 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003137 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3138 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3139 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3140 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003141 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003142
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003143 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003144 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003145 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3146 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3147 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3148 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3149 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3150 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003151 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003152
3153 SmallVector<unsigned, 64> Vals;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003154 for (const auto &MPSE : Index.modulePaths()) {
Teresa Johnson84174c32016-05-10 13:48:23 +00003155 if (!doIncludeModule(MPSE.getKey()))
3156 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00003157 StringEncoding Bits =
3158 getStringEncoding(MPSE.getKey().data(), MPSE.getKey().size());
3159 unsigned AbbrevToUse = Abbrev8Bit;
3160 if (Bits == SE_Char6)
3161 AbbrevToUse = Abbrev6Bit;
3162 else if (Bits == SE_Fixed7)
3163 AbbrevToUse = Abbrev7Bit;
3164
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003165 Vals.push_back(MPSE.getValue().first);
Teresa Johnson403a7872015-10-04 14:33:43 +00003166
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003167 for (const auto P : MPSE.getKey())
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003168 Vals.push_back((unsigned char)P);
Teresa Johnson403a7872015-10-04 14:33:43 +00003169
3170 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003171 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003172
3173 Vals.clear();
3174 // Emit an optional hash for the module now
3175 auto &Hash = MPSE.getValue().second;
3176 bool AllZero = true; // Detect if the hash is empty, and do not generate it
3177 for (auto Val : Hash) {
3178 if (Val)
3179 AllZero = false;
3180 Vals.push_back(Val);
3181 }
3182 if (!AllZero) {
3183 // Emit the hash record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003184 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003185 }
3186
3187 Vals.clear();
Teresa Johnson403a7872015-10-04 14:33:43 +00003188 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003189 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003190}
3191
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003192/// Write the function type metadata related records that need to appear before
3193/// a function summary entry (whether per-module or combined).
3194static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3195 FunctionSummary *FS) {
3196 if (!FS->type_tests().empty())
3197 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3198
3199 SmallVector<uint64_t, 64> Record;
3200
3201 auto WriteVFuncIdVec = [&](uint64_t Ty,
3202 ArrayRef<FunctionSummary::VFuncId> VFs) {
3203 if (VFs.empty())
3204 return;
3205 Record.clear();
3206 for (auto &VF : VFs) {
3207 Record.push_back(VF.GUID);
3208 Record.push_back(VF.Offset);
3209 }
3210 Stream.EmitRecord(Ty, Record);
3211 };
3212
3213 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3214 FS->type_test_assume_vcalls());
3215 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3216 FS->type_checked_load_vcalls());
3217
3218 auto WriteConstVCallVec = [&](uint64_t Ty,
3219 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3220 for (auto &VC : VCs) {
3221 Record.clear();
3222 Record.push_back(VC.VFunc.GUID);
3223 Record.push_back(VC.VFunc.Offset);
3224 Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
3225 Stream.EmitRecord(Ty, Record);
3226 }
3227 };
3228
3229 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3230 FS->type_test_assume_const_vcalls());
3231 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3232 FS->type_checked_load_const_vcalls());
3233}
3234
Teresa Johnson403a7872015-10-04 14:33:43 +00003235// Helper to emit a single function summary record.
Teresa Johnson37687f32016-04-23 04:30:47 +00003236void ModuleBitcodeWriter::writePerModuleFunctionSummaryRecord(
Teresa Johnson28e457b2016-04-24 14:57:11 +00003237 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
Teresa Johnson37687f32016-04-23 04:30:47 +00003238 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3239 const Function &F) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003240 NameVals.push_back(ValueID);
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003241
Teresa Johnson28e457b2016-04-24 14:57:11 +00003242 FunctionSummary *FS = cast<FunctionSummary>(Summary);
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003243 writeFunctionTypeMetadataRecords(Stream, FS);
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00003244
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003245 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
Teresa Johnson403a7872015-10-04 14:33:43 +00003246 NameVals.push_back(FS->instCount());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003247 NameVals.push_back(FS->refs().size());
3248
3249 for (auto &RI : FS->refs())
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003250 NameVals.push_back(VE.getValueID(RI.getValue()));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003251
3252 bool HasProfileData = F.getEntryCount().hasValue();
Peter Collingbourne0c30f082016-12-20 21:12:28 +00003253 for (auto &ECI : FS->calls()) {
Teresa Johnsoncd21a642016-07-17 14:47:01 +00003254 NameVals.push_back(getValueId(ECI.first));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003255 if (HasProfileData)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003256 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003257 }
3258
3259 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3260 unsigned Code =
3261 (HasProfileData ? bitc::FS_PERMODULE_PROFILE : bitc::FS_PERMODULE);
Teresa Johnson403a7872015-10-04 14:33:43 +00003262
3263 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003264 Stream.EmitRecord(Code, NameVals, FSAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003265 NameVals.clear();
3266}
3267
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003268// Collect the global value references in the given variable's initializer,
3269// and emit them in a summary record.
Teresa Johnson37687f32016-04-23 04:30:47 +00003270void ModuleBitcodeWriter::writeModuleLevelReferences(
3271 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3272 unsigned FSModRefsAbbrev) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00003273 auto VI = Index->getValueInfo(GlobalValue::getGUID(V.getName()));
3274 if (!VI || VI.getSummaryList().empty()) {
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003275 // Only declarations should not have a summary (a declaration might however
3276 // have a summary if the def was in module level asm).
3277 assert(V.isDeclaration());
Teresa Johnson13968092016-03-15 19:35:45 +00003278 return;
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003279 }
Peter Collingbourne9667b912017-05-04 18:03:25 +00003280 auto *Summary = VI.getSummaryList()[0].get();
Teresa Johnson13968092016-03-15 19:35:45 +00003281 NameVals.push_back(VE.getValueID(&V));
Teresa Johnson28e457b2016-04-24 14:57:11 +00003282 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
Teresa Johnson7c31cb12016-10-28 19:36:00 +00003283 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003284
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003285 unsigned SizeBeforeRefs = NameVals.size();
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003286 for (auto &RI : VS->refs())
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003287 NameVals.push_back(VE.getValueID(RI.getValue()));
3288 // Sort the refs for determinism output, the vector returned by FS->refs() has
3289 // been initialized from a DenseSet.
3290 std::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003291
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003292 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3293 FSModRefsAbbrev);
Teresa Johnson13968092016-03-15 19:35:45 +00003294 NameVals.clear();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003295}
Teresa Johnson403a7872015-10-04 14:33:43 +00003296
Mehdi Amini8fe69362016-04-24 03:18:11 +00003297// Current version for the summary.
3298// This is bumped whenever we introduce changes in the way some record are
3299// interpreted, like flags for instance.
Teresa Johnson519465b2017-01-05 14:32:16 +00003300static const uint64_t INDEX_VERSION = 3;
Mehdi Amini8fe69362016-04-24 03:18:11 +00003301
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003302/// Emit the per-module summary section alongside the rest of
3303/// the module's bitcode.
Teresa Johnson37687f32016-04-23 04:30:47 +00003304void ModuleBitcodeWriter::writePerModuleGlobalValueSummary() {
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003305 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 4);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003306
Mehdi Amini8fe69362016-04-24 03:18:11 +00003307 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3308
Teresa Johnson620c1402016-09-20 23:07:17 +00003309 if (Index->begin() == Index->end()) {
3310 Stream.ExitBlock();
3311 return;
3312 }
3313
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003314 for (const auto &GVI : valueIds()) {
3315 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3316 ArrayRef<uint64_t>{GVI.second, GVI.first});
3317 }
3318
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003319 // Abbrev for FS_PERMODULE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003320 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003321 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003322 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003323 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003324 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003325 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003326 // numrefs x valueid, n x (valueid)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003327 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3328 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003329 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003330
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003331 // Abbrev for FS_PERMODULE_PROFILE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003332 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003333 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3334 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003335 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003336 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3337 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003338 // numrefs x valueid, n x (valueid, hotness)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003339 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3340 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003341 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003342
3343 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003344 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003345 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3346 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003347 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003348 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3349 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003350 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003351
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003352 // Abbrev for FS_ALIAS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003353 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003354 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3355 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003356 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003357 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
David Blaikie7ad9dc12017-01-04 22:36:33 +00003358 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003359
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003360 SmallVector<uint64_t, 64> NameVals;
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003361 // Iterate over the list of functions instead of the Index to
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003362 // ensure the ordering is stable.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003363 for (const Function &F : M) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003364 // Summary emission does not support anonymous functions, they have to
3365 // renamed using the anonymous function renaming pass.
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003366 if (!F.hasName())
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003367 report_fatal_error("Unexpected anonymous function when writing summary");
Teresa Johnson403a7872015-10-04 14:33:43 +00003368
Peter Collingbourne9667b912017-05-04 18:03:25 +00003369 ValueInfo VI = Index->getValueInfo(GlobalValue::getGUID(F.getName()));
3370 if (!VI || VI.getSummaryList().empty()) {
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003371 // Only declarations should not have a summary (a declaration might
3372 // however have a summary if the def was in module level asm).
3373 assert(F.isDeclaration());
3374 continue;
3375 }
Peter Collingbourne9667b912017-05-04 18:03:25 +00003376 auto *Summary = VI.getSummaryList()[0].get();
Peter Collingbourne832e7fa2016-05-06 02:41:23 +00003377 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3378 FSCallsAbbrev, FSCallsProfileAbbrev, F);
Teresa Johnson403a7872015-10-04 14:33:43 +00003379 }
3380
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003381 // Capture references from GlobalVariable initializers, which are outside
3382 // of a function scope.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003383 for (const GlobalVariable &G : M.globals())
Teresa Johnson37687f32016-04-23 04:30:47 +00003384 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003385
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003386 for (const GlobalAlias &A : M.aliases()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003387 auto *Aliasee = A.getBaseObject();
3388 if (!Aliasee->hasName())
3389 // Nameless function don't have an entry in the summary, skip it.
3390 continue;
3391 auto AliasId = VE.getValueID(&A);
3392 auto AliaseeId = VE.getValueID(Aliasee);
3393 NameVals.push_back(AliasId);
Teresa Johnson02563cd2016-10-28 02:39:38 +00003394 auto *Summary = Index->getGlobalValueSummary(A);
3395 AliasSummary *AS = cast<AliasSummary>(Summary);
3396 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003397 NameVals.push_back(AliaseeId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003398 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003399 NameVals.clear();
3400 }
3401
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003402 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003403}
3404
Teresa Johnson26ab5772016-03-15 00:04:37 +00003405/// Emit the combined summary section into the combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003406void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003407 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
Mehdi Amini8fe69362016-04-24 03:18:11 +00003408 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
Teresa Johnson403a7872015-10-04 14:33:43 +00003409
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003410 // Create value IDs for undefined references.
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003411 forEachSummary([&](GVInfo I) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003412 if (auto *VS = dyn_cast<GlobalVarSummary>(I.second)) {
3413 for (auto &RI : VS->refs())
3414 assignValueId(RI.getGUID());
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003415 return;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003416 }
3417
3418 auto *FS = dyn_cast<FunctionSummary>(I.second);
3419 if (!FS)
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003420 return;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003421 for (auto &RI : FS->refs())
3422 assignValueId(RI.getGUID());
3423
3424 for (auto &EI : FS->calls()) {
3425 GlobalValue::GUID GUID = EI.first.getGUID();
3426 if (!hasValueId(GUID)) {
3427 // For SamplePGO, the indirect call targets for local functions will
3428 // have its original name annotated in profile. We try to find the
3429 // corresponding PGOFuncName as the GUID.
3430 GUID = Index.getGUIDFromOriginalID(GUID);
3431 if (GUID == 0 || !hasValueId(GUID))
3432 continue;
3433 }
3434 assignValueId(GUID);
3435 }
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003436 });
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003437
3438 for (const auto &GVI : valueIds()) {
3439 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3440 ArrayRef<uint64_t>{GVI.second, GVI.first});
3441 }
3442
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003443 // Abbrev for FS_COMBINED.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003444 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003445 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
Teresa Johnson02e98332016-04-27 13:28:35 +00003446 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003447 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003448 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003449 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3450 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003451 // numrefs x valueid, n x (valueid)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003452 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3453 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003454 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003455
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003456 // Abbrev for FS_COMBINED_PROFILE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003457 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003458 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
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, hotness)
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 FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003468
3469 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
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_GLOBALVAR_INIT_REFS));
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::Array)); // valueids
3476 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003477 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003478
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003479 // Abbrev for FS_COMBINED_ALIAS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003480 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003481 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003482 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003483 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003484 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson02e98332016-04-27 13:28:35 +00003485 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
David Blaikie7ad9dc12017-01-04 22:36:33 +00003486 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003487
Teresa Johnson02e98332016-04-27 13:28:35 +00003488 // The aliases are emitted as a post-pass, and will point to the value
3489 // id of the aliasee. Save them in a vector for post-processing.
Teresa Johnson28e457b2016-04-24 14:57:11 +00003490 SmallVector<AliasSummary *, 64> Aliases;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003491
Teresa Johnson02e98332016-04-27 13:28:35 +00003492 // Save the value id for each summary for alias emission.
3493 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3494
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003495 SmallVector<uint64_t, 64> NameVals;
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003496
3497 // For local linkage, we also emit the original name separately
3498 // immediately after the record.
3499 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3500 if (!GlobalValue::isLocalLinkage(S.linkage()))
3501 return;
3502 NameVals.push_back(S.getOriginalName());
3503 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3504 NameVals.clear();
3505 };
3506
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003507 forEachSummary([&](GVInfo I) {
Teresa Johnson84174c32016-05-10 13:48:23 +00003508 GlobalValueSummary *S = I.second;
3509 assert(S);
Teresa Johnson02e98332016-04-27 13:28:35 +00003510
Teresa Johnson84174c32016-05-10 13:48:23 +00003511 assert(hasValueId(I.first));
3512 unsigned ValueId = getValueId(I.first);
3513 SummaryToValueIdMap[S] = ValueId;
Teresa Johnson02e98332016-04-27 13:28:35 +00003514
Teresa Johnson84174c32016-05-10 13:48:23 +00003515 if (auto *AS = dyn_cast<AliasSummary>(S)) {
3516 // Will process aliases as a post-pass because the reader wants all
3517 // global to be loaded first.
3518 Aliases.push_back(AS);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003519 return;
Teresa Johnson84174c32016-05-10 13:48:23 +00003520 }
Teresa Johnson403a7872015-10-04 14:33:43 +00003521
Teresa Johnson84174c32016-05-10 13:48:23 +00003522 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
Teresa Johnson02e98332016-04-27 13:28:35 +00003523 NameVals.push_back(ValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003524 NameVals.push_back(Index.getModuleId(VS->modulePath()));
3525 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3526 for (auto &RI : VS->refs()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00003527 NameVals.push_back(getValueId(RI.getGUID()));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003528 }
3529
Teresa Johnson403a7872015-10-04 14:33:43 +00003530 // Emit the finished record.
Teresa Johnson84174c32016-05-10 13:48:23 +00003531 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3532 FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003533 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003534 MaybeEmitOriginalName(*S);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003535 return;
Teresa Johnson403a7872015-10-04 14:33:43 +00003536 }
Teresa Johnson84174c32016-05-10 13:48:23 +00003537
3538 auto *FS = cast<FunctionSummary>(S);
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003539 writeFunctionTypeMetadataRecords(Stream, FS);
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00003540
Teresa Johnson84174c32016-05-10 13:48:23 +00003541 NameVals.push_back(ValueId);
3542 NameVals.push_back(Index.getModuleId(FS->modulePath()));
3543 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3544 NameVals.push_back(FS->instCount());
3545 NameVals.push_back(FS->refs().size());
3546
3547 for (auto &RI : FS->refs()) {
3548 NameVals.push_back(getValueId(RI.getGUID()));
3549 }
3550
3551 bool HasProfileData = false;
3552 for (auto &EI : FS->calls()) {
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003553 HasProfileData |= EI.second.Hotness != CalleeInfo::HotnessType::Unknown;
Teresa Johnson84174c32016-05-10 13:48:23 +00003554 if (HasProfileData)
3555 break;
3556 }
3557
3558 for (auto &EI : FS->calls()) {
3559 // If this GUID doesn't have a value id, it doesn't have a function
3560 // summary and we don't need to record any calls to it.
Dehao Chen4a435e02017-03-14 17:33:01 +00003561 GlobalValue::GUID GUID = EI.first.getGUID();
3562 if (!hasValueId(GUID)) {
3563 // For SamplePGO, the indirect call targets for local functions will
3564 // have its original name annotated in profile. We try to find the
3565 // corresponding PGOFuncName as the GUID.
3566 GUID = Index.getGUIDFromOriginalID(GUID);
3567 if (GUID == 0 || !hasValueId(GUID))
3568 continue;
3569 }
3570 NameVals.push_back(getValueId(GUID));
Teresa Johnson84174c32016-05-10 13:48:23 +00003571 if (HasProfileData)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003572 NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
Teresa Johnson84174c32016-05-10 13:48:23 +00003573 }
3574
3575 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3576 unsigned Code =
3577 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3578
3579 // Emit the finished record.
3580 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3581 NameVals.clear();
3582 MaybeEmitOriginalName(*S);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003583 });
Teresa Johnson403a7872015-10-04 14:33:43 +00003584
Teresa Johnson28e457b2016-04-24 14:57:11 +00003585 for (auto *AS : Aliases) {
Teresa Johnson02e98332016-04-27 13:28:35 +00003586 auto AliasValueId = SummaryToValueIdMap[AS];
3587 assert(AliasValueId);
3588 NameVals.push_back(AliasValueId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003589 NameVals.push_back(Index.getModuleId(AS->modulePath()));
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003590 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
Teresa Johnson02e98332016-04-27 13:28:35 +00003591 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3592 assert(AliaseeValueId);
3593 NameVals.push_back(AliaseeValueId);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003594
3595 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003596 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003597 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003598 MaybeEmitOriginalName(*AS);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003599 }
3600
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003601 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003602}
3603
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003604/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3605/// current llvm version, and a record for the epoch number.
Benjamin Kramerefcf06f2017-02-11 11:06:55 +00003606static void writeIdentificationBlock(BitstreamWriter &Stream) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003607 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
Mehdi Amini5d303282015-10-26 18:37:00 +00003608
3609 // Write the "user readable" string identifying the bitcode producer
David Blaikie7ad9dc12017-01-04 22:36:33 +00003610 auto Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini5d303282015-10-26 18:37:00 +00003611 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3612 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3613 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003614 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003615 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
Teresa Johnson37687f32016-04-23 04:30:47 +00003616 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
Mehdi Amini5d303282015-10-26 18:37:00 +00003617
3618 // Write the epoch version
David Blaikie7ad9dc12017-01-04 22:36:33 +00003619 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini5d303282015-10-26 18:37:00 +00003620 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3621 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003622 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini5d303282015-10-26 18:37:00 +00003623 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003624 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3625 Stream.ExitBlock();
Mehdi Amini5d303282015-10-26 18:37:00 +00003626}
3627
Teresa Johnson37687f32016-04-23 04:30:47 +00003628void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003629 // Emit the module's hash.
3630 // MODULE_CODE_HASH: [5*i32]
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003631 if (GenerateHash) {
3632 SHA1 Hasher;
3633 uint32_t Vals[5];
3634 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
3635 Buffer.size() - BlockStartPos));
3636 StringRef Hash = Hasher.result();
3637 for (int Pos = 0; Pos < 20; Pos += 4) {
3638 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
3639 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003640
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003641 // Emit the finished record.
3642 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
3643
3644 if (ModHash)
3645 // Save the written hash value.
3646 std::copy(std::begin(Vals), std::end(Vals), std::begin(*ModHash));
3647 } else if (ModHash)
3648 Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003649}
3650
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003651void ModuleBitcodeWriter::write() {
3652 writeIdentificationBlock(Stream);
Teresa Johnson37687f32016-04-23 04:30:47 +00003653
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003654 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3655 size_t BlockStartPos = Buffer.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003656
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003657 writeModuleVersion();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003658
3659 // Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00003660 writeBlockInfo();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003661
Bill Wendlingdc095552013-02-10 23:09:32 +00003662 // Emit information about attribute groups.
Teresa Johnson37687f32016-04-23 04:30:47 +00003663 writeAttributeGroupTable();
Bill Wendlingdc095552013-02-10 23:09:32 +00003664
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003665 // Emit information about parameter attributes.
Teresa Johnson37687f32016-04-23 04:30:47 +00003666 writeAttributeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003667
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003668 // Emit information describing all of the types in the module.
Teresa Johnson37687f32016-04-23 04:30:47 +00003669 writeTypeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003670
Teresa Johnson37687f32016-04-23 04:30:47 +00003671 writeComdats();
David Majnemerdad0a642014-06-27 18:19:56 +00003672
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003673 // Emit top-level description of module, including target triple, inline asm,
3674 // descriptors for global variables, and function prototype info.
Teresa Johnson37687f32016-04-23 04:30:47 +00003675 writeModuleInfo();
Devang Patel7428d8a2009-07-22 17:43:22 +00003676
Devang Patele059ba6e2009-07-23 01:07:34 +00003677 // Emit constants.
Teresa Johnson37687f32016-04-23 04:30:47 +00003678 writeModuleConstants();
Devang Patele059ba6e2009-07-23 01:07:34 +00003679
Peter Collingbourne21521892016-06-21 23:42:48 +00003680 // Emit metadata kind names.
3681 writeModuleMetadataKinds();
Devang Patel8cca7b42009-08-04 05:01:35 +00003682
Devang Patelaf206b82009-09-18 19:26:43 +00003683 // Emit metadata.
Peter Collingbourne21521892016-06-21 23:42:48 +00003684 writeModuleMetadata();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003685
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003686 // Emit module-level use-lists.
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00003687 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00003688 writeUseListBlock(nullptr);
Chad Rosierca2567b2011-12-07 21:44:12 +00003689
Teresa Johnson37687f32016-04-23 04:30:47 +00003690 writeOperandBundleTags();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003691
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003692 // Emit function bodies.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003693 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003694 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003695 if (!F->isDeclaration())
Teresa Johnson37687f32016-04-23 04:30:47 +00003696 writeFunction(*F, FunctionToBitcodeIndex);
Teresa Johnson403a7872015-10-04 14:33:43 +00003697
3698 // Need to write after the above call to WriteFunction which populates
3699 // the summary information in the index.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003700 if (Index)
Teresa Johnson37687f32016-04-23 04:30:47 +00003701 writePerModuleGlobalValueSummary();
Teresa Johnsonff642b92015-09-17 20:12:00 +00003702
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003703 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003704
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003705 writeModuleHash(BlockStartPos);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003706
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003707 Stream.ExitBlock();
Chris Lattner702658c2007-05-04 18:26:27 +00003708}
3709
Teresa Johnson37687f32016-04-23 04:30:47 +00003710static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
3711 uint32_t &Position) {
3712 support::endian::write32le(&Buffer[Position], Value);
3713 Position += 4;
3714}
3715
3716/// If generating a bc file on darwin, we have to emit a
Chris Lattnera660f4b2008-07-09 05:14:23 +00003717/// header and trailer to make it compatible with the system archiver. To do
3718/// this we emit the following header, and then emit a trailer that pads the
3719/// file out to be a multiple of 16 bytes.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003720///
Chris Lattnera660f4b2008-07-09 05:14:23 +00003721/// struct bc_header {
3722/// uint32_t Magic; // 0x0B17C0DE
3723/// uint32_t Version; // Version, currently always 0.
3724/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
3725/// uint32_t BitcodeSize; // Size of traditional bitcode file.
3726/// uint32_t CPUType; // CPU specifier.
3727/// ... potentially more later ...
3728/// };
Teresa Johnson37687f32016-04-23 04:30:47 +00003729static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003730 const Triple &TT) {
Chris Lattnera660f4b2008-07-09 05:14:23 +00003731 unsigned CPUType = ~0U;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003732
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003733 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
Evan Cheng545d3602010-02-12 20:39:35 +00003734 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
3735 // number from /usr/include/mach/machine.h. It is ok to reproduce the
3736 // specific constants here because they are implicitly part of the Darwin ABI.
Chris Lattnera660f4b2008-07-09 05:14:23 +00003737 enum {
3738 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
3739 DARWIN_CPU_TYPE_X86 = 7,
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003740 DARWIN_CPU_TYPE_ARM = 12,
Chris Lattnera660f4b2008-07-09 05:14:23 +00003741 DARWIN_CPU_TYPE_POWERPC = 18
3742 };
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003743
Evan Chengcffdcae2011-06-14 01:51:33 +00003744 Triple::ArchType Arch = TT.getArch();
3745 if (Arch == Triple::x86_64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003746 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00003747 else if (Arch == Triple::x86)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003748 CPUType = DARWIN_CPU_TYPE_X86;
Evan Chengcffdcae2011-06-14 01:51:33 +00003749 else if (Arch == Triple::ppc)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003750 CPUType = DARWIN_CPU_TYPE_POWERPC;
Evan Chengcffdcae2011-06-14 01:51:33 +00003751 else if (Arch == Triple::ppc64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00003752 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00003753 else if (Arch == Triple::arm || Arch == Triple::thumb)
Evan Cheng9aa30fb2010-02-12 20:13:44 +00003754 CPUType = DARWIN_CPU_TYPE_ARM;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003755
Chris Lattnera660f4b2008-07-09 05:14:23 +00003756 // Traditional Bitcode starts after header.
Akira Hatanaka4f472a882016-01-29 05:55:09 +00003757 assert(Buffer.size() >= BWH_HeaderSize &&
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003758 "Expected header size to be reserved");
Akira Hatanaka4f472a882016-01-29 05:55:09 +00003759 unsigned BCOffset = BWH_HeaderSize;
3760 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003761
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003762 // Write the magic and version.
3763 unsigned Position = 0;
Teresa Johnson37687f32016-04-23 04:30:47 +00003764 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
3765 writeInt32ToBuffer(0, Buffer, Position); // Version.
3766 writeInt32ToBuffer(BCOffset, Buffer, Position);
3767 writeInt32ToBuffer(BCSize, Buffer, Position);
3768 writeInt32ToBuffer(CPUType, Buffer, Position);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003769
Chris Lattnera660f4b2008-07-09 05:14:23 +00003770 // If the file is not a multiple of 16 bytes, insert dummy padding.
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003771 while (Buffer.size() & 15)
3772 Buffer.push_back(0);
Chris Lattnera660f4b2008-07-09 05:14:23 +00003773}
3774
Teresa Johnson403a7872015-10-04 14:33:43 +00003775/// Helper to write the header common to all bitcode files.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003776static void writeBitcodeHeader(BitstreamWriter &Stream) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003777 // Emit the file header.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003778 Stream.Emit((unsigned)'B', 8);
3779 Stream.Emit((unsigned)'C', 8);
3780 Stream.Emit(0x0, 4);
3781 Stream.Emit(0xC, 4);
3782 Stream.Emit(0xE, 4);
3783 Stream.Emit(0xD, 4);
Teresa Johnson403a7872015-10-04 14:33:43 +00003784}
3785
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003786BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
3787 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
3788 writeBitcodeHeader(*Stream);
3789}
3790
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003791BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
3792
3793void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
3794 Stream->EnterSubblock(Block, 3);
3795
3796 auto Abbv = std::make_shared<BitCodeAbbrev>();
3797 Abbv->Add(BitCodeAbbrevOp(Record));
3798 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3799 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
3800
3801 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
3802
3803 Stream->ExitBlock();
3804}
3805
3806void BitcodeWriter::writeStrtab() {
3807 assert(!WroteStrtab);
3808
3809 std::vector<char> Strtab;
3810 StrtabBuilder.finalizeInOrder();
3811 Strtab.resize(StrtabBuilder.getSize());
3812 StrtabBuilder.write((uint8_t *)Strtab.data());
3813
3814 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
3815 {Strtab.data(), Strtab.size()});
3816
3817 WroteStrtab = true;
3818}
3819
3820void BitcodeWriter::copyStrtab(StringRef Strtab) {
3821 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
3822 WroteStrtab = true;
3823}
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003824
3825void BitcodeWriter::writeModule(const Module *M,
3826 bool ShouldPreserveUseListOrder,
3827 const ModuleSummaryIndex *Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003828 bool GenerateHash, ModuleHash *ModHash) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003829 ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003830 ShouldPreserveUseListOrder, Index,
3831 GenerateHash, ModHash);
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003832 ModuleWriter.write();
3833}
3834
Chris Lattnerc1d10d62007-04-22 06:24:45 +00003835/// WriteBitcodeToFile - Write the specified module to the specified output
3836/// stream.
Duncan P. N. Exon Smitha052ed62015-04-15 00:10:50 +00003837void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out,
Teresa Johnson403a7872015-10-04 14:33:43 +00003838 bool ShouldPreserveUseListOrder,
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003839 const ModuleSummaryIndex *Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003840 bool GenerateHash, ModuleHash *ModHash) {
Michael Ilsemane26658d2012-12-03 21:29:36 +00003841 SmallVector<char, 0> Buffer;
Chris Lattnerc1d10d62007-04-22 06:24:45 +00003842 Buffer.reserve(256*1024);
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00003843
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003844 // If this is darwin or another generic macho target, reserve space for the
3845 // header.
3846 Triple TT(M->getTargetTriple());
Akira Hatanaka1235d282016-01-23 16:02:10 +00003847 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Akira Hatanaka4f472a882016-01-29 05:55:09 +00003848 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003849
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003850 BitcodeWriter Writer(Buffer);
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003851 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
3852 ModHash);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003853 Writer.writeStrtab();
Daniel Dunbar6e45c022012-02-29 20:31:01 +00003854
Akira Hatanaka1235d282016-01-23 16:02:10 +00003855 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Teresa Johnson37687f32016-04-23 04:30:47 +00003856 emitDarwinBCHeaderAndTrailer(Buffer, TT);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003857
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00003858 // Write the generated bitstream to "Out".
3859 Out.write((char*)&Buffer.front(), Buffer.size());
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00003860}
Teresa Johnson403a7872015-10-04 14:33:43 +00003861
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003862void IndexBitcodeWriter::write() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003863 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
Teresa Johnson37687f32016-04-23 04:30:47 +00003864
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003865 writeModuleVersion();
Teresa Johnson37687f32016-04-23 04:30:47 +00003866
3867 // Write the module paths in the combined index.
3868 writeModStrings();
3869
3870 // Write the summary combined index records.
3871 writeCombinedGlobalValueSummary();
3872
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003873 Stream.ExitBlock();
Teresa Johnson37687f32016-04-23 04:30:47 +00003874}
3875
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003876// Write the specified module summary index to the given raw output stream,
Teresa Johnson403a7872015-10-04 14:33:43 +00003877// where it will be written in a new bitcode block. This is used when
Teresa Johnson84174c32016-05-10 13:48:23 +00003878// writing the combined index file for ThinLTO. When writing a subset of the
3879// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
3880void llvm::WriteIndexToFile(
3881 const ModuleSummaryIndex &Index, raw_ostream &Out,
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +00003882 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003883 SmallVector<char, 0> Buffer;
3884 Buffer.reserve(256 * 1024);
3885
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003886 BitstreamWriter Stream(Buffer);
3887 writeBitcodeHeader(Stream);
3888
3889 IndexBitcodeWriter IndexWriter(Stream, Index, ModuleToSummariesForIndex);
Teresa Johnson37687f32016-04-23 04:30:47 +00003890 IndexWriter.write();
Teresa Johnson403a7872015-10-04 14:33:43 +00003891
3892 Out.write((char *)&Buffer.front(), Buffer.size());
3893}