blob: d59da255be4bfca439d4094cc2426937496cbfbf [file] [log] [blame]
Eugene Zelenko975293f2017-09-07 23:28:24 +00001//===- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ------------------===//
Chris Lattnerc1d10d62007-04-22 06:24:45 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerc1d10d62007-04-22 06:24:45 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Bitcode writer implementation.
11//
12//===----------------------------------------------------------------------===//
13
Teresa Johnsonad176792016-11-11 05:34:58 +000014#include "llvm/Bitcode/BitcodeWriter.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "ValueEnumerator.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000016#include "llvm/ADT/APFloat.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/None.h"
21#include "llvm/ADT/Optional.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/StringMap.h"
26#include "llvm/ADT/StringRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/ADT/Triple.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000028#include "llvm/Bitcode/BitCodes.h"
Chris Lattnerc1d10d62007-04-22 06:24:45 +000029#include "llvm/Bitcode/BitstreamWriter.h"
Chris Lattner362b4a12007-04-23 01:01:37 +000030#include "llvm/Bitcode/LLVMBitCodes.h"
Nico Weber432a3882018-04-30 14:59:11 +000031#include "llvm/Config/llvm-config.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000032#include "llvm/IR/Attributes.h"
33#include "llvm/IR/BasicBlock.h"
Sanjoy Dasb513a9f2015-09-24 23:34:52 +000034#include "llvm/IR/CallSite.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000035#include "llvm/IR/Comdat.h"
36#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/Constants.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000038#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000039#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000041#include "llvm/IR/Function.h"
42#include "llvm/IR/GlobalAlias.h"
43#include "llvm/IR/GlobalIFunc.h"
44#include "llvm/IR/GlobalObject.h"
45#include "llvm/IR/GlobalValue.h"
46#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/InlineAsm.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000048#include "llvm/IR/InstrTypes.h"
49#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000050#include "llvm/IR/Instructions.h"
Teresa Johnson76a1c1d2016-03-11 18:52:24 +000051#include "llvm/IR/LLVMContext.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000052#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/Module.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000054#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/Operator.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000056#include "llvm/IR/Type.h"
Duncan P. N. Exon Smith6b6fdc92014-07-25 14:49:26 +000057#include "llvm/IR/UseListOrder.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000058#include "llvm/IR/Value.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000059#include "llvm/IR/ValueSymbolTable.h"
Peter Collingbournea0f371a2017-04-17 17:51:36 +000060#include "llvm/MC/StringTableBuilder.h"
Peter Collingbourne92648c22017-06-27 23:50:11 +000061#include "llvm/Object/IRSymtab.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000062#include "llvm/Support/AtomicOrdering.h"
63#include "llvm/Support/Casting.h"
64#include "llvm/Support/CommandLine.h"
65#include "llvm/Support/Endian.h"
66#include "llvm/Support/Error.h"
Torok Edwin56d06592009-07-11 20:10:48 +000067#include "llvm/Support/ErrorHandling.h"
Chris Lattnerc1d10d62007-04-22 06:24:45 +000068#include "llvm/Support/MathExtras.h"
Mehdi Aminid7ad2212016-04-01 05:33:11 +000069#include "llvm/Support/SHA1.h"
Peter Collingbourne92648c22017-06-27 23:50:11 +000070#include "llvm/Support/TargetRegistry.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000071#include "llvm/Support/raw_ostream.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000072#include <algorithm>
73#include <cassert>
74#include <cstddef>
75#include <cstdint>
76#include <iterator>
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000077#include <map>
Eugene Zelenko975293f2017-09-07 23:28:24 +000078#include <memory>
79#include <string>
80#include <utility>
81#include <vector>
82
Chris Lattnerc1d10d62007-04-22 06:24:45 +000083using namespace llvm;
84
Eugene Zelenko975293f2017-09-07 23:28:24 +000085static cl::opt<unsigned>
Mehdi Aminie98f9252016-12-28 22:30:28 +000086 IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
87 cl::desc("Number of metadatas above which we emit an index "
88 "to enable lazy-loading"));
Eugene Zelenko975293f2017-09-07 23:28:24 +000089
Easwaran Ramanc73cec82018-01-25 19:27:17 +000090cl::opt<bool> WriteRelBFToSummary(
91 "write-relbf-to-summary", cl::Hidden, cl::init(false),
92 cl::desc("Write relative block frequency to function summary "));
Teresa Johnsondb83ace2018-03-31 00:18:08 +000093
94extern FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold;
95
Eugene Zelenko975293f2017-09-07 23:28:24 +000096namespace {
97
Chris Lattner4d925982007-05-04 20:52:02 +000098/// These are manifest constants used by the bitcode writer. They do not need to
99/// be kept in sync with the reader, but need to be consistent within this file.
100enum {
Chris Lattner4d925982007-05-04 20:52:02 +0000101 // VALUE_SYMTAB_BLOCK abbrev id's.
102 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
Chris Lattnerfd1ad102007-05-04 20:58:35 +0000103 VST_ENTRY_7_ABBREV,
Chris Lattnere760d6f2007-05-05 01:26:50 +0000104 VST_ENTRY_6_ABBREV,
Chris Lattnerda5e5d22007-05-05 07:36:14 +0000105 VST_BBENTRY_6_ABBREV,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000106
Chris Lattnerda5e5d22007-05-05 07:36:14 +0000107 // CONSTANTS_BLOCK abbrev id's.
108 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
109 CONSTANTS_INTEGER_ABBREV,
110 CONSTANTS_CE_CAST_Abbrev,
Chris Lattnerb80751d2007-05-05 07:44:49 +0000111 CONSTANTS_NULL_Abbrev,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000112
Chris Lattnerb80751d2007-05-05 07:44:49 +0000113 // FUNCTION_BLOCK abbrev id's.
Chris Lattnercc6d4c92007-05-06 01:28:01 +0000114 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
Chris Lattnerc67e6d92007-05-06 02:38:57 +0000115 FUNCTION_INST_BINOP_ABBREV,
Dan Gohman0ebd6962009-07-20 21:19:07 +0000116 FUNCTION_INST_BINOP_FLAGS_ABBREV,
Chris Lattnerc67e6d92007-05-06 02:38:57 +0000117 FUNCTION_INST_CAST_ABBREV,
Chris Lattnercc6d4c92007-05-06 01:28:01 +0000118 FUNCTION_INST_RET_VOID_ABBREV,
119 FUNCTION_INST_RET_VAL_ABBREV,
David Blaikieb5b5efd2015-02-25 01:08:52 +0000120 FUNCTION_INST_UNREACHABLE_ABBREV,
121 FUNCTION_INST_GEP_ABBREV,
Chris Lattner4d925982007-05-04 20:52:02 +0000122};
123
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000124/// Abstract class to manage the bitcode writing, subclassed for each bitcode
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000125/// file type.
126class BitcodeWriterBase {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000127protected:
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000128 /// The stream created and owned by the client.
129 BitstreamWriter &Stream;
Teresa Johnson37687f32016-04-23 04:30:47 +0000130
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000131 StringTableBuilder &StrtabBuilder;
132
Teresa Johnson37687f32016-04-23 04:30:47 +0000133public:
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000134 /// Constructs a BitcodeWriterBase object that writes to the provided
135 /// \p Stream.
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000136 BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
137 : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
Teresa Johnson37687f32016-04-23 04:30:47 +0000138
139protected:
Teresa Johnson37687f32016-04-23 04:30:47 +0000140 void writeBitcodeHeader();
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000141 void writeModuleVersion();
Teresa Johnson37687f32016-04-23 04:30:47 +0000142};
143
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000144void BitcodeWriterBase::writeModuleVersion() {
145 // VERSION: [version#]
146 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
147}
148
Haojie Wang1dec57d2017-07-21 17:25:20 +0000149/// Base class to manage the module bitcode writing, currently subclassed for
150/// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
151class ModuleBitcodeWriterBase : public BitcodeWriterBase {
152protected:
Teresa Johnson37687f32016-04-23 04:30:47 +0000153 /// The Module to write to bitcode.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000154 const Module &M;
Teresa Johnson37687f32016-04-23 04:30:47 +0000155
156 /// Enumerates ids for all values in the module.
157 ValueEnumerator VE;
158
159 /// Optional per-module index to write for ThinLTO.
160 const ModuleSummaryIndex *Index;
161
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000162 /// Map that holds the correspondence between GUIDs in the summary index,
163 /// that came from indirect call profiles, and a value id generated by this
164 /// class to use in the VST and summary block records.
165 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
166
167 /// Tracks the last value id recorded in the GUIDToValueMap.
168 unsigned GlobalValueId;
169
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000170 /// Saves the offset of the VSTOffset record that must eventually be
171 /// backpatched with the offset of the actual VST.
172 uint64_t VSTOffsetPlaceholder = 0;
173
Teresa Johnson37687f32016-04-23 04:30:47 +0000174public:
Haojie Wang1dec57d2017-07-21 17:25:20 +0000175 /// Constructs a ModuleBitcodeWriterBase object for the given Module,
Teresa Johnson37687f32016-04-23 04:30:47 +0000176 /// writing to the provided \p Buffer.
Rafael Espindola6a86e252018-02-14 19:11:32 +0000177 ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
Haojie Wang1dec57d2017-07-21 17:25:20 +0000178 BitstreamWriter &Stream,
179 bool ShouldPreserveUseListOrder,
180 const ModuleSummaryIndex *Index)
Rafael Espindola6a86e252018-02-14 19:11:32 +0000181 : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
182 VE(M, ShouldPreserveUseListOrder), Index(Index) {
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000183 // Assign ValueIds to any callee values in the index that came from
184 // indirect call profiles and were recorded as a GUID not a Value*
185 // (which would have been assigned an ID by the ValueEnumerator).
186 // The starting ValueId is just after the number of values in the
187 // ValueEnumerator, so that they can be emitted in the VST.
188 GlobalValueId = VE.getValues().size();
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000189 if (!Index)
190 return;
191 for (const auto &GUIDSummaryLists : *Index)
192 // Examine all summaries for this GUID.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000193 for (auto &Summary : GUIDSummaryLists.second.SummaryList)
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000194 if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
195 // For each call in the function summary, see if the call
196 // is to a GUID (which means it is for an indirect call,
197 // otherwise we would have a Value for it). If so, synthesize
198 // a value id.
199 for (auto &CallEdge : FS->calls())
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000200 if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
Teresa Johnsonbb5c4042016-07-18 18:31:50 +0000201 assignValueId(CallEdge.first.getGUID());
Teresa Johnson37687f32016-04-23 04:30:47 +0000202 }
203
Haojie Wang1dec57d2017-07-21 17:25:20 +0000204protected:
205 void writePerModuleGlobalValueSummary();
206
207private:
208 void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
209 GlobalValueSummary *Summary,
210 unsigned ValueID,
211 unsigned FSCallsAbbrev,
212 unsigned FSCallsProfileAbbrev,
213 const Function &F);
214 void writeModuleLevelReferences(const GlobalVariable &V,
215 SmallVector<uint64_t, 64> &NameVals,
216 unsigned FSModRefsAbbrev);
217
218 void assignValueId(GlobalValue::GUID ValGUID) {
219 GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
220 }
Eugene Zelenko975293f2017-09-07 23:28:24 +0000221
Haojie Wang1dec57d2017-07-21 17:25:20 +0000222 unsigned getValueId(GlobalValue::GUID ValGUID) {
223 const auto &VMI = GUIDToValueIdMap.find(ValGUID);
224 // Expect that any GUID value had a value Id assigned by an
225 // earlier call to assignValueId.
226 assert(VMI != GUIDToValueIdMap.end() &&
227 "GUID does not have assigned value Id");
228 return VMI->second;
229 }
Eugene Zelenko975293f2017-09-07 23:28:24 +0000230
Haojie Wang1dec57d2017-07-21 17:25:20 +0000231 // Helper to get the valueId for the type of value recorded in VI.
232 unsigned getValueId(ValueInfo VI) {
Teresa Johnson63ee0e72018-06-26 13:56:49 +0000233 if (!VI.haveGVs() || !VI.getValue())
Haojie Wang1dec57d2017-07-21 17:25:20 +0000234 return getValueId(VI.getGUID());
235 return VE.getValueID(VI.getValue());
236 }
Eugene Zelenko975293f2017-09-07 23:28:24 +0000237
Haojie Wang1dec57d2017-07-21 17:25:20 +0000238 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
239};
240
241/// Class to manage the bitcode writing for a module.
242class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
243 /// Pointer to the buffer allocated by caller for bitcode writing.
244 const SmallVectorImpl<char> &Buffer;
245
246 /// True if a module hash record should be written.
247 bool GenerateHash;
248
249 /// If non-null, when GenerateHash is true, the resulting hash is written
250 /// into ModHash.
251 ModuleHash *ModHash;
252
253 SHA1 Hasher;
254
255 /// The start bit of the identification block.
256 uint64_t BitcodeStartBit;
257
258public:
259 /// Constructs a ModuleBitcodeWriter object for the given Module,
260 /// writing to the provided \p Buffer.
Rafael Espindola6a86e252018-02-14 19:11:32 +0000261 ModuleBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer,
Haojie Wang1dec57d2017-07-21 17:25:20 +0000262 StringTableBuilder &StrtabBuilder,
263 BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
264 const ModuleSummaryIndex *Index, bool GenerateHash,
265 ModuleHash *ModHash = nullptr)
266 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
267 ShouldPreserveUseListOrder, Index),
268 Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash),
269 BitcodeStartBit(Stream.GetCurrentBitNo()) {}
270
Teresa Johnson37687f32016-04-23 04:30:47 +0000271 /// Emit the current module to the bitstream.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000272 void write();
Teresa Johnson37687f32016-04-23 04:30:47 +0000273
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000274private:
Teresa Johnson37687f32016-04-23 04:30:47 +0000275 uint64_t bitcodeStartBit() { return BitcodeStartBit; }
276
Peter Collingbournec8556152017-07-06 17:56:01 +0000277 size_t addToStrtab(StringRef Str);
278
Teresa Johnson37687f32016-04-23 04:30:47 +0000279 void writeAttributeGroupTable();
280 void writeAttributeTable();
281 void writeTypeTable();
282 void writeComdats();
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000283 void writeValueSymbolTableForwardDecl();
Teresa Johnson37687f32016-04-23 04:30:47 +0000284 void writeModuleInfo();
285 void writeValueAsMetadata(const ValueAsMetadata *MD,
286 SmallVectorImpl<uint64_t> &Record);
287 void writeMDTuple(const MDTuple *N, SmallVectorImpl<uint64_t> &Record,
288 unsigned Abbrev);
289 unsigned createDILocationAbbrev();
290 void writeDILocation(const DILocation *N, SmallVectorImpl<uint64_t> &Record,
291 unsigned &Abbrev);
292 unsigned createGenericDINodeAbbrev();
293 void writeGenericDINode(const GenericDINode *N,
294 SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
295 void writeDISubrange(const DISubrange *N, SmallVectorImpl<uint64_t> &Record,
296 unsigned Abbrev);
297 void writeDIEnumerator(const DIEnumerator *N,
298 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
299 void writeDIBasicType(const DIBasicType *N, SmallVectorImpl<uint64_t> &Record,
300 unsigned Abbrev);
301 void writeDIDerivedType(const DIDerivedType *N,
302 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
303 void writeDICompositeType(const DICompositeType *N,
304 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
305 void writeDISubroutineType(const DISubroutineType *N,
306 SmallVectorImpl<uint64_t> &Record,
307 unsigned Abbrev);
308 void writeDIFile(const DIFile *N, SmallVectorImpl<uint64_t> &Record,
309 unsigned Abbrev);
310 void writeDICompileUnit(const DICompileUnit *N,
311 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
312 void writeDISubprogram(const DISubprogram *N,
313 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
314 void writeDILexicalBlock(const DILexicalBlock *N,
315 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
316 void writeDILexicalBlockFile(const DILexicalBlockFile *N,
317 SmallVectorImpl<uint64_t> &Record,
318 unsigned Abbrev);
319 void writeDINamespace(const DINamespace *N, SmallVectorImpl<uint64_t> &Record,
320 unsigned Abbrev);
321 void writeDIMacro(const DIMacro *N, SmallVectorImpl<uint64_t> &Record,
322 unsigned Abbrev);
323 void writeDIMacroFile(const DIMacroFile *N, SmallVectorImpl<uint64_t> &Record,
324 unsigned Abbrev);
325 void writeDIModule(const DIModule *N, SmallVectorImpl<uint64_t> &Record,
326 unsigned Abbrev);
327 void writeDITemplateTypeParameter(const DITemplateTypeParameter *N,
328 SmallVectorImpl<uint64_t> &Record,
329 unsigned Abbrev);
330 void writeDITemplateValueParameter(const DITemplateValueParameter *N,
331 SmallVectorImpl<uint64_t> &Record,
332 unsigned Abbrev);
333 void writeDIGlobalVariable(const DIGlobalVariable *N,
334 SmallVectorImpl<uint64_t> &Record,
335 unsigned Abbrev);
336 void writeDILocalVariable(const DILocalVariable *N,
337 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
Shiva Chen2c864552018-05-09 02:40:45 +0000338 void writeDILabel(const DILabel *N,
339 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
Teresa Johnson37687f32016-04-23 04:30:47 +0000340 void writeDIExpression(const DIExpression *N,
341 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000342 void writeDIGlobalVariableExpression(const DIGlobalVariableExpression *N,
343 SmallVectorImpl<uint64_t> &Record,
344 unsigned Abbrev);
Teresa Johnson37687f32016-04-23 04:30:47 +0000345 void writeDIObjCProperty(const DIObjCProperty *N,
346 SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
347 void writeDIImportedEntity(const DIImportedEntity *N,
348 SmallVectorImpl<uint64_t> &Record,
349 unsigned Abbrev);
350 unsigned createNamedMetadataAbbrev();
351 void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
352 unsigned createMetadataStringsAbbrev();
353 void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
354 SmallVectorImpl<uint64_t> &Record);
355 void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
Mehdi Aminie98f9252016-12-28 22:30:28 +0000356 SmallVectorImpl<uint64_t> &Record,
357 std::vector<unsigned> *MDAbbrevs = nullptr,
358 std::vector<uint64_t> *IndexPos = nullptr);
Teresa Johnson37687f32016-04-23 04:30:47 +0000359 void writeModuleMetadata();
360 void writeFunctionMetadata(const Function &F);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000361 void writeFunctionMetadataAttachment(const Function &F);
362 void writeGlobalVariableMetadataAttachment(const GlobalVariable &GV);
363 void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
364 const GlobalObject &GO);
Peter Collingbourne21521892016-06-21 23:42:48 +0000365 void writeModuleMetadataKinds();
Teresa Johnson37687f32016-04-23 04:30:47 +0000366 void writeOperandBundleTags();
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000367 void writeSyncScopeNames();
Teresa Johnson37687f32016-04-23 04:30:47 +0000368 void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
369 void writeModuleConstants();
370 bool pushValueAndType(const Value *V, unsigned InstID,
371 SmallVectorImpl<unsigned> &Vals);
372 void writeOperandBundles(ImmutableCallSite CS, unsigned InstID);
373 void pushValue(const Value *V, unsigned InstID,
374 SmallVectorImpl<unsigned> &Vals);
375 void pushValueSigned(const Value *V, unsigned InstID,
376 SmallVectorImpl<uint64_t> &Vals);
377 void writeInstruction(const Instruction &I, unsigned InstID,
378 SmallVectorImpl<unsigned> &Vals);
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000379 void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
380 void writeGlobalValueSymbolTable(
381 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
Teresa Johnson37687f32016-04-23 04:30:47 +0000382 void writeUseList(UseListOrder &&Order);
383 void writeUseListBlock(const Function *F);
384 void
385 writeFunction(const Function &F,
386 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
387 void writeBlockInfo();
Teresa Johnson37687f32016-04-23 04:30:47 +0000388 void writeModuleHash(size_t BlockStartPos);
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000389
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000390 unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
391 return unsigned(SSID);
392 }
Teresa Johnson37687f32016-04-23 04:30:47 +0000393};
394
395/// Class to manage the bitcode writing for a combined index.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000396class IndexBitcodeWriter : public BitcodeWriterBase {
Teresa Johnson37687f32016-04-23 04:30:47 +0000397 /// The combined index to write to bitcode.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000398 const ModuleSummaryIndex &Index;
Teresa Johnson37687f32016-04-23 04:30:47 +0000399
Teresa Johnson84174c32016-05-10 13:48:23 +0000400 /// When writing a subset of the index for distributed backends, client
401 /// provides a map of modules to the corresponding GUIDs/summaries to write.
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +0000402 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
Teresa Johnson84174c32016-05-10 13:48:23 +0000403
Teresa Johnson37687f32016-04-23 04:30:47 +0000404 /// Map that holds the correspondence between the GUID used in the combined
405 /// index and a value id generated by this class to use in references.
406 std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
407
408 /// Tracks the last value id recorded in the GUIDToValueMap.
409 unsigned GlobalValueId = 0;
410
411public:
412 /// Constructs a IndexBitcodeWriter object for the given combined index,
Teresa Johnson84174c32016-05-10 13:48:23 +0000413 /// writing to the provided \p Buffer. When writing a subset of the index
414 /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000415 IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
416 const ModuleSummaryIndex &Index,
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +0000417 const std::map<std::string, GVSummaryMapTy>
Teresa Johnson84174c32016-05-10 13:48:23 +0000418 *ModuleToSummariesForIndex = nullptr)
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000419 : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
Teresa Johnson84174c32016-05-10 13:48:23 +0000420 ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
421 // Assign unique value ids to all summaries to be written, for use
Teresa Johnson37687f32016-04-23 04:30:47 +0000422 // in writing out the call graph edges. Save the mapping from GUID
423 // to the new global value id to use when writing those edges, which
424 // are currently saved in the index in terms of GUID.
Teresa Johnson81bbf742017-12-16 00:18:12 +0000425 forEachSummary([&](GVInfo I, bool) {
Teresa Johnson84174c32016-05-10 13:48:23 +0000426 GUIDToValueIdMap[I.first] = ++GlobalValueId;
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000427 });
Teresa Johnson37687f32016-04-23 04:30:47 +0000428 }
429
Teresa Johnson84174c32016-05-10 13:48:23 +0000430 /// The below iterator returns the GUID and associated summary.
Eugene Zelenko975293f2017-09-07 23:28:24 +0000431 using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
Teresa Johnson84174c32016-05-10 13:48:23 +0000432
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000433 /// Calls the callback for each value GUID and summary to be written to
434 /// bitcode. This hides the details of whether they are being pulled from the
435 /// entire index or just those in a provided ModuleToSummariesForIndex map.
David Blaikie358c0122017-06-02 18:25:29 +0000436 template<typename Functor>
437 void forEachSummary(Functor Callback) {
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000438 if (ModuleToSummariesForIndex) {
439 for (auto &M : *ModuleToSummariesForIndex)
Teresa Johnson81bbf742017-12-16 00:18:12 +0000440 for (auto &Summary : M.second) {
441 Callback(Summary, false);
442 // Ensure aliasee is handled, e.g. for assigning a valueId,
443 // even if we are not importing the aliasee directly (the
444 // imported alias will contain a copy of aliasee).
445 if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
446 Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
447 }
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000448 } else {
449 for (auto &Summaries : Index)
Peter Collingbourne9667b912017-05-04 18:03:25 +0000450 for (auto &Summary : Summaries.second.SummaryList)
Teresa Johnson81bbf742017-12-16 00:18:12 +0000451 Callback({Summaries.first, Summary.get()}, false);
Teresa Johnson84174c32016-05-10 13:48:23 +0000452 }
Peter Collingbourne7c2c4092017-05-02 17:48:39 +0000453 }
Teresa Johnson84174c32016-05-10 13:48:23 +0000454
Teresa Johnson7a27b132017-06-02 01:56:02 +0000455 /// Calls the callback for each entry in the modulePaths StringMap that
456 /// should be written to the module path string table. This hides the details
457 /// of whether they are being pulled from the entire index or just those in a
458 /// provided ModuleToSummariesForIndex map.
David Blaikieb6b42e02017-06-02 17:24:26 +0000459 template <typename Functor> void forEachModule(Functor Callback) {
Teresa Johnson7a27b132017-06-02 01:56:02 +0000460 if (ModuleToSummariesForIndex) {
461 for (const auto &M : *ModuleToSummariesForIndex) {
462 const auto &MPI = Index.modulePaths().find(M.first);
463 if (MPI == Index.modulePaths().end()) {
464 // This should only happen if the bitcode file was empty, in which
465 // case we shouldn't be importing (the ModuleToSummariesForIndex
466 // would only include the module we are writing and index for).
467 assert(ModuleToSummariesForIndex->size() == 1);
468 continue;
469 }
470 Callback(*MPI);
471 }
472 } else {
473 for (const auto &MPSE : Index.modulePaths())
474 Callback(MPSE);
475 }
476 }
477
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000478 /// Main entry point for writing a combined index to bitcode.
479 void write();
Teresa Johnson37687f32016-04-23 04:30:47 +0000480
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000481private:
Teresa Johnson37687f32016-04-23 04:30:47 +0000482 void writeModStrings();
Teresa Johnson37687f32016-04-23 04:30:47 +0000483 void writeCombinedGlobalValueSummary();
484
Teresa Johnsona6a3fb52017-05-31 18:58:11 +0000485 Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000486 auto VMI = GUIDToValueIdMap.find(ValGUID);
Teresa Johnsona6a3fb52017-05-31 18:58:11 +0000487 if (VMI == GUIDToValueIdMap.end())
488 return None;
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000489 return VMI->second;
Teresa Johnson37687f32016-04-23 04:30:47 +0000490 }
Eugene Zelenko975293f2017-09-07 23:28:24 +0000491
Teresa Johnson37687f32016-04-23 04:30:47 +0000492 std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
493};
Eugene Zelenko975293f2017-09-07 23:28:24 +0000494
Benjamin Kramera65b6102016-05-15 15:18:11 +0000495} // end anonymous namespace
Teresa Johnson37687f32016-04-23 04:30:47 +0000496
497static unsigned getEncodedCastOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000498 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000499 default: llvm_unreachable("Unknown cast instruction!");
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000500 case Instruction::Trunc : return bitc::CAST_TRUNC;
501 case Instruction::ZExt : return bitc::CAST_ZEXT;
502 case Instruction::SExt : return bitc::CAST_SEXT;
503 case Instruction::FPToUI : return bitc::CAST_FPTOUI;
504 case Instruction::FPToSI : return bitc::CAST_FPTOSI;
505 case Instruction::UIToFP : return bitc::CAST_UITOFP;
506 case Instruction::SIToFP : return bitc::CAST_SITOFP;
507 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
508 case Instruction::FPExt : return bitc::CAST_FPEXT;
509 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
510 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
511 case Instruction::BitCast : return bitc::CAST_BITCAST;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000512 case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000513 }
514}
515
Teresa Johnson37687f32016-04-23 04:30:47 +0000516static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000517 switch (Opcode) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000518 default: llvm_unreachable("Unknown binary instruction!");
Dan Gohmana5b96452009-06-04 22:49:04 +0000519 case Instruction::Add:
520 case Instruction::FAdd: return bitc::BINOP_ADD;
521 case Instruction::Sub:
522 case Instruction::FSub: return bitc::BINOP_SUB;
523 case Instruction::Mul:
524 case Instruction::FMul: return bitc::BINOP_MUL;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000525 case Instruction::UDiv: return bitc::BINOP_UDIV;
526 case Instruction::FDiv:
527 case Instruction::SDiv: return bitc::BINOP_SDIV;
528 case Instruction::URem: return bitc::BINOP_UREM;
529 case Instruction::FRem:
530 case Instruction::SRem: return bitc::BINOP_SREM;
531 case Instruction::Shl: return bitc::BINOP_SHL;
532 case Instruction::LShr: return bitc::BINOP_LSHR;
533 case Instruction::AShr: return bitc::BINOP_ASHR;
534 case Instruction::And: return bitc::BINOP_AND;
535 case Instruction::Or: return bitc::BINOP_OR;
536 case Instruction::Xor: return bitc::BINOP_XOR;
537 }
538}
539
Teresa Johnson37687f32016-04-23 04:30:47 +0000540static unsigned getEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000541 switch (Op) {
542 default: llvm_unreachable("Unknown RMW operation!");
543 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
544 case AtomicRMWInst::Add: return bitc::RMW_ADD;
545 case AtomicRMWInst::Sub: return bitc::RMW_SUB;
546 case AtomicRMWInst::And: return bitc::RMW_AND;
547 case AtomicRMWInst::Nand: return bitc::RMW_NAND;
548 case AtomicRMWInst::Or: return bitc::RMW_OR;
549 case AtomicRMWInst::Xor: return bitc::RMW_XOR;
550 case AtomicRMWInst::Max: return bitc::RMW_MAX;
551 case AtomicRMWInst::Min: return bitc::RMW_MIN;
552 case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
553 case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
554 }
555}
556
Teresa Johnson37687f32016-04-23 04:30:47 +0000557static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000558 switch (Ordering) {
JF Bastien800f87a2016-04-06 21:19:33 +0000559 case AtomicOrdering::NotAtomic: return bitc::ORDERING_NOTATOMIC;
560 case AtomicOrdering::Unordered: return bitc::ORDERING_UNORDERED;
561 case AtomicOrdering::Monotonic: return bitc::ORDERING_MONOTONIC;
562 case AtomicOrdering::Acquire: return bitc::ORDERING_ACQUIRE;
563 case AtomicOrdering::Release: return bitc::ORDERING_RELEASE;
564 case AtomicOrdering::AcquireRelease: return bitc::ORDERING_ACQREL;
565 case AtomicOrdering::SequentiallyConsistent: return bitc::ORDERING_SEQCST;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000566 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000567 llvm_unreachable("Invalid ordering");
Eli Friedmanfee02c62011-07-25 23:16:38 +0000568}
569
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000570static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
571 StringRef Str, unsigned AbbrevToUse) {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000572 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000573
Chris Lattnere14cb882007-05-04 19:11:41 +0000574 // Code: [strchar x N]
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000575 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
576 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
577 AbbrevToUse = 0;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000578 Vals.push_back(Str[i]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000579 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000580
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000581 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000582 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000583}
584
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000585static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
586 switch (Kind) {
587 case Attribute::Alignment:
588 return bitc::ATTR_KIND_ALIGNMENT;
George Burgess IV278199f2016-04-12 01:05:35 +0000589 case Attribute::AllocSize:
590 return bitc::ATTR_KIND_ALLOC_SIZE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000591 case Attribute::AlwaysInline:
592 return bitc::ATTR_KIND_ALWAYS_INLINE;
Igor Laevsky39d662f2015-07-11 10:30:36 +0000593 case Attribute::ArgMemOnly:
594 return bitc::ATTR_KIND_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000595 case Attribute::Builtin:
596 return bitc::ATTR_KIND_BUILTIN;
597 case Attribute::ByVal:
598 return bitc::ATTR_KIND_BY_VAL;
Owen Anderson85fa7d52015-05-26 23:48:40 +0000599 case Attribute::Convergent:
600 return bitc::ATTR_KIND_CONVERGENT;
Reid Klecknera534a382013-12-19 02:14:12 +0000601 case Attribute::InAlloca:
602 return bitc::ATTR_KIND_IN_ALLOCA;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000603 case Attribute::Cold:
604 return bitc::ATTR_KIND_COLD;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +0000605 case Attribute::InaccessibleMemOnly:
606 return bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY;
607 case Attribute::InaccessibleMemOrArgMemOnly:
608 return bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000609 case Attribute::InlineHint:
610 return bitc::ATTR_KIND_INLINE_HINT;
611 case Attribute::InReg:
612 return bitc::ATTR_KIND_IN_REG;
Tom Roeder44cb65f2014-06-05 19:29:43 +0000613 case Attribute::JumpTable:
614 return bitc::ATTR_KIND_JUMP_TABLE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000615 case Attribute::MinSize:
616 return bitc::ATTR_KIND_MIN_SIZE;
617 case Attribute::Naked:
618 return bitc::ATTR_KIND_NAKED;
619 case Attribute::Nest:
620 return bitc::ATTR_KIND_NEST;
621 case Attribute::NoAlias:
622 return bitc::ATTR_KIND_NO_ALIAS;
623 case Attribute::NoBuiltin:
624 return bitc::ATTR_KIND_NO_BUILTIN;
625 case Attribute::NoCapture:
626 return bitc::ATTR_KIND_NO_CAPTURE;
627 case Attribute::NoDuplicate:
628 return bitc::ATTR_KIND_NO_DUPLICATE;
629 case Attribute::NoImplicitFloat:
630 return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
631 case Attribute::NoInline:
632 return bitc::ATTR_KIND_NO_INLINE;
James Molloye6f87ca2015-11-06 10:32:53 +0000633 case Attribute::NoRecurse:
634 return bitc::ATTR_KIND_NO_RECURSE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000635 case Attribute::NonLazyBind:
636 return bitc::ATTR_KIND_NON_LAZY_BIND;
Nick Lewyckyd52b1522014-05-20 01:23:40 +0000637 case Attribute::NonNull:
638 return bitc::ATTR_KIND_NON_NULL;
Hal Finkelb0407ba2014-07-18 15:51:28 +0000639 case Attribute::Dereferenceable:
640 return bitc::ATTR_KIND_DEREFERENCEABLE;
Sanjoy Das31ea6d12015-04-16 20:29:50 +0000641 case Attribute::DereferenceableOrNull:
642 return bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000643 case Attribute::NoRedZone:
644 return bitc::ATTR_KIND_NO_RED_ZONE;
645 case Attribute::NoReturn:
646 return bitc::ATTR_KIND_NO_RETURN;
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +0000647 case Attribute::NoCfCheck:
648 return bitc::ATTR_KIND_NOCF_CHECK;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000649 case Attribute::NoUnwind:
650 return bitc::ATTR_KIND_NO_UNWIND;
Matt Morehouse236cdaf2018-03-22 17:07:51 +0000651 case Attribute::OptForFuzzing:
652 return bitc::ATTR_KIND_OPT_FOR_FUZZING;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000653 case Attribute::OptimizeForSize:
654 return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
Andrea Di Biagio377496b2013-08-23 11:53:55 +0000655 case Attribute::OptimizeNone:
656 return bitc::ATTR_KIND_OPTIMIZE_NONE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000657 case Attribute::ReadNone:
658 return bitc::ATTR_KIND_READ_NONE;
659 case Attribute::ReadOnly:
660 return bitc::ATTR_KIND_READ_ONLY;
661 case Attribute::Returned:
662 return bitc::ATTR_KIND_RETURNED;
663 case Attribute::ReturnsTwice:
664 return bitc::ATTR_KIND_RETURNS_TWICE;
665 case Attribute::SExt:
666 return bitc::ATTR_KIND_S_EXT;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +0000667 case Attribute::Speculatable:
668 return bitc::ATTR_KIND_SPECULATABLE;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000669 case Attribute::StackAlignment:
670 return bitc::ATTR_KIND_STACK_ALIGNMENT;
671 case Attribute::StackProtect:
672 return bitc::ATTR_KIND_STACK_PROTECT;
673 case Attribute::StackProtectReq:
674 return bitc::ATTR_KIND_STACK_PROTECT_REQ;
675 case Attribute::StackProtectStrong:
676 return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
Peter Collingbourne82437bf2015-06-15 21:07:11 +0000677 case Attribute::SafeStack:
678 return bitc::ATTR_KIND_SAFESTACK;
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +0000679 case Attribute::ShadowCallStack:
680 return bitc::ATTR_KIND_SHADOWCALLSTACK;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +0000681 case Attribute::StrictFP:
682 return bitc::ATTR_KIND_STRICT_FP;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000683 case Attribute::StructRet:
684 return bitc::ATTR_KIND_STRUCT_RET;
685 case Attribute::SanitizeAddress:
686 return bitc::ATTR_KIND_SANITIZE_ADDRESS;
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +0000687 case Attribute::SanitizeHWAddress:
688 return bitc::ATTR_KIND_SANITIZE_HWADDRESS;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000689 case Attribute::SanitizeThread:
690 return bitc::ATTR_KIND_SANITIZE_THREAD;
691 case Attribute::SanitizeMemory:
692 return bitc::ATTR_KIND_SANITIZE_MEMORY;
Chandler Carruth664aa862018-09-04 12:38:00 +0000693 case Attribute::SpeculativeLoadHardening:
694 return bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING;
Manman Ren9bfd0d02016-04-01 21:41:15 +0000695 case Attribute::SwiftError:
696 return bitc::ATTR_KIND_SWIFT_ERROR;
Manman Renf46262e2016-03-29 17:37:21 +0000697 case Attribute::SwiftSelf:
698 return bitc::ATTR_KIND_SWIFT_SELF;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000699 case Attribute::UWTable:
700 return bitc::ATTR_KIND_UW_TABLE;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +0000701 case Attribute::WriteOnly:
702 return bitc::ATTR_KIND_WRITEONLY;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +0000703 case Attribute::ZExt:
704 return bitc::ATTR_KIND_Z_EXT;
705 case Attribute::EndAttrKinds:
706 llvm_unreachable("Can not encode end-attribute kinds marker.");
707 case Attribute::None:
708 llvm_unreachable("Can not encode none-attribute.");
709 }
710
711 llvm_unreachable("Trying to encode unknown attribute");
712}
713
Teresa Johnson37687f32016-04-23 04:30:47 +0000714void ModuleBitcodeWriter::writeAttributeGroupTable() {
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000715 const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
716 VE.getAttributeGroups();
Bill Wendling92ed7002013-02-11 22:33:26 +0000717 if (AttrGrps.empty()) return;
Bill Wendlingdc095552013-02-10 23:09:32 +0000718
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000719 Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
Bill Wendlingdc095552013-02-10 23:09:32 +0000720
721 SmallVector<uint64_t, 64> Record;
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000722 for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
723 unsigned AttrListIndex = Pair.first;
724 AttributeSet AS = Pair.second;
725 Record.push_back(VE.getAttributeGroupID(Pair));
726 Record.push_back(AttrListIndex);
Bill Wendlingdc095552013-02-10 23:09:32 +0000727
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000728 for (Attribute Attr : AS) {
729 if (Attr.isEnumAttribute()) {
730 Record.push_back(0);
731 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
732 } else if (Attr.isIntAttribute()) {
733 Record.push_back(1);
734 Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
735 Record.push_back(Attr.getValueAsInt());
736 } else {
737 StringRef Kind = Attr.getKindAsString();
738 StringRef Val = Attr.getValueAsString();
Bill Wendlingdc095552013-02-10 23:09:32 +0000739
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000740 Record.push_back(Val.empty() ? 3 : 4);
741 Record.append(Kind.begin(), Kind.end());
742 Record.push_back(0);
743 if (!Val.empty()) {
744 Record.append(Val.begin(), Val.end());
Bill Wendlingdc095552013-02-10 23:09:32 +0000745 Record.push_back(0);
Bill Wendlingdc095552013-02-10 23:09:32 +0000746 }
747 }
Bill Wendlingdc095552013-02-10 23:09:32 +0000748 }
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000749
750 Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
751 Record.clear();
Bill Wendlingdc095552013-02-10 23:09:32 +0000752 }
753
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000754 Stream.ExitBlock();
Bill Wendlingdc095552013-02-10 23:09:32 +0000755}
756
Teresa Johnson37687f32016-04-23 04:30:47 +0000757void ModuleBitcodeWriter::writeAttributeTable() {
Reid Klecknerb4a2d182017-04-24 20:38:30 +0000758 const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000759 if (Attrs.empty()) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000760
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000761 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000762
763 SmallVector<uint64_t, 64> Record;
764 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
Reid Kleckner8bf67fe2017-05-23 17:01:48 +0000765 AttributeList AL = Attrs[i];
766 for (unsigned i = AL.index_begin(), e = AL.index_end(); i != e; ++i) {
767 AttributeSet AS = AL.getAttributes(i);
768 if (AS.hasAttributes())
769 Record.push_back(VE.getAttributeGroupID({i, AS}));
770 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000771
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000772 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
Chris Lattnere72bf9f2007-05-04 02:59:04 +0000773 Record.clear();
774 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000775
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000776 Stream.ExitBlock();
Chris Lattnere2f98ef2007-05-04 00:44:52 +0000777}
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000778
779/// WriteTypeTable - Write out the type table for a module.
Teresa Johnson37687f32016-04-23 04:30:47 +0000780void ModuleBitcodeWriter::writeTypeTable() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000781 const ValueEnumerator::TypeList &TypeList = VE.getTypes();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000782
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000783 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000784 SmallVector<uint64_t, 64> TypeVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000785
David Blaikie7b028102015-02-25 00:51:52 +0000786 uint64_t NumBits = VE.computeBitsRequiredForTypeIndicies();
Chad Rosier9646c0d2011-12-08 00:38:45 +0000787
Chris Lattnerccee7062007-05-05 06:30:12 +0000788 // Abbrev for TYPE_CODE_POINTER.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000789 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000790 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000791 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
Christopher Lamb25f50762007-12-12 08:44:39 +0000792 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
David Blaikie7ad9dc12017-01-04 22:36:33 +0000793 unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000794
Chris Lattnerccee7062007-05-05 06:30:12 +0000795 // Abbrev for TYPE_CODE_FUNCTION.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000796 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000797 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
798 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
Chris Lattnerccee7062007-05-05 06:30:12 +0000799 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000800 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000801 unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000802
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000803 // Abbrev for TYPE_CODE_STRUCT_ANON.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000804 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000805 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
Chris Lattnerccee7062007-05-05 06:30:12 +0000806 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
807 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000808 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000809 unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000810
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000811 // Abbrev for TYPE_CODE_STRUCT_NAME.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000812 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000813 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
814 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
815 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000816 unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000817
818 // Abbrev for TYPE_CODE_STRUCT_NAMED.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000819 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000820 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
821 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
822 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chad Rosier9646c0d2011-12-08 00:38:45 +0000823 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000824 unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000825
Chris Lattnerccee7062007-05-05 06:30:12 +0000826 // Abbrev for TYPE_CODE_ARRAY.
David Blaikie7ad9dc12017-01-04 22:36:33 +0000827 Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerccee7062007-05-05 06:30:12 +0000828 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
829 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
Chad Rosier9646c0d2011-12-08 00:38:45 +0000830 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
David Blaikie7ad9dc12017-01-04 22:36:33 +0000831 unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000832
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000833 // Emit an entry count so the reader can reserve space.
834 TypeVals.push_back(TypeList.size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000835 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000836 TypeVals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000837
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000838 // Loop over all of the types, emitting each in turn.
839 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
Chris Lattner229907c2011-07-18 04:54:35 +0000840 Type *T = TypeList[i];
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000841 int AbbrevToUse = 0;
842 unsigned Code = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000843
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000844 switch (T->getTypeID()) {
Joe Abbey2ad8df22012-11-25 15:23:39 +0000845 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
846 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break;
847 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
848 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
849 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
850 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +0000851 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
Joe Abbey2ad8df22012-11-25 15:23:39 +0000852 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
853 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
854 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break;
David Majnemerb611e3f2015-08-14 05:09:07 +0000855 case Type::TokenTyID: Code = bitc::TYPE_CODE_TOKEN; break;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000856 case Type::IntegerTyID:
857 // INTEGER: [width]
858 Code = bitc::TYPE_CODE_INTEGER;
859 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
860 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000861 case Type::PointerTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000862 PointerType *PTy = cast<PointerType>(T);
Christopher Lamb25f50762007-12-12 08:44:39 +0000863 // POINTER: [pointee type, address space]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000864 Code = bitc::TYPE_CODE_POINTER;
Christopher Lamb54dd24c2007-12-11 08:59:05 +0000865 TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
Christopher Lamb25f50762007-12-12 08:44:39 +0000866 unsigned AddressSpace = PTy->getAddressSpace();
867 TypeVals.push_back(AddressSpace);
868 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000869 break;
Duncan Sandsf41217d2007-12-11 12:20:47 +0000870 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000871 case Type::FunctionTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000872 FunctionType *FT = cast<FunctionType>(T);
Chad Rosier95898722011-11-03 00:14:01 +0000873 // FUNCTION: [isvararg, retty, paramty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000874 Code = bitc::TYPE_CODE_FUNCTION;
875 TypeVals.push_back(FT->isVarArg());
876 TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000877 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
878 TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
Chris Lattnerccee7062007-05-05 06:30:12 +0000879 AbbrevToUse = FunctionAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000880 break;
881 }
882 case Type::StructTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000883 StructType *ST = cast<StructType>(T);
Chris Lattnerccee7062007-05-05 06:30:12 +0000884 // STRUCT: [ispacked, eltty x N]
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000885 TypeVals.push_back(ST->isPacked());
Chris Lattnere14cb882007-05-04 19:11:41 +0000886 // Output all of the element types.
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000887 for (StructType::element_iterator I = ST->element_begin(),
888 E = ST->element_end(); I != E; ++I)
889 TypeVals.push_back(VE.getTypeID(*I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +0000890
Chris Lattner335d3992011-08-12 18:06:37 +0000891 if (ST->isLiteral()) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000892 Code = bitc::TYPE_CODE_STRUCT_ANON;
893 AbbrevToUse = StructAnonAbbrev;
894 } else {
895 if (ST->isOpaque()) {
896 Code = bitc::TYPE_CODE_OPAQUE;
897 } else {
898 Code = bitc::TYPE_CODE_STRUCT_NAMED;
899 AbbrevToUse = StructNamedAbbrev;
900 }
901
902 // Emit the name if it is present.
903 if (!ST->getName().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +0000904 writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
Teresa Johnson37687f32016-04-23 04:30:47 +0000905 StructNameAbbrev);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000906 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000907 break;
908 }
909 case Type::ArrayTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000910 ArrayType *AT = cast<ArrayType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000911 // ARRAY: [numelts, eltty]
912 Code = bitc::TYPE_CODE_ARRAY;
913 TypeVals.push_back(AT->getNumElements());
914 TypeVals.push_back(VE.getTypeID(AT->getElementType()));
Chris Lattnerccee7062007-05-05 06:30:12 +0000915 AbbrevToUse = ArrayAbbrev;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000916 break;
917 }
918 case Type::VectorTyID: {
Chris Lattner229907c2011-07-18 04:54:35 +0000919 VectorType *VT = cast<VectorType>(T);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000920 // VECTOR [numelts, eltty]
921 Code = bitc::TYPE_CODE_VECTOR;
922 TypeVals.push_back(VT->getNumElements());
923 TypeVals.push_back(VE.getTypeID(VT->getElementType()));
924 break;
925 }
926 }
927
928 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000929 Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000930 TypeVals.clear();
931 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000932
Teresa Johnsonc814e0c2016-04-23 04:31:20 +0000933 Stream.ExitBlock();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000934}
935
Teresa Johnson5e22e442016-02-06 16:07:35 +0000936static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
937 switch (Linkage) {
Rafael Espindola261d25b2015-01-08 16:25:01 +0000938 case GlobalValue::ExternalLinkage:
939 return 0;
940 case GlobalValue::WeakAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000941 return 16;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000942 case GlobalValue::AppendingLinkage:
943 return 2;
944 case GlobalValue::InternalLinkage:
945 return 3;
946 case GlobalValue::LinkOnceAnyLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000947 return 18;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000948 case GlobalValue::ExternalWeakLinkage:
949 return 7;
950 case GlobalValue::CommonLinkage:
951 return 8;
952 case GlobalValue::PrivateLinkage:
953 return 9;
954 case GlobalValue::WeakODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000955 return 17;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000956 case GlobalValue::LinkOnceODRLinkage:
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000957 return 19;
Rafael Espindola261d25b2015-01-08 16:25:01 +0000958 case GlobalValue::AvailableExternallyLinkage:
959 return 12;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000960 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000961 llvm_unreachable("Invalid linkage");
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000962}
963
Teresa Johnson5e22e442016-02-06 16:07:35 +0000964static unsigned getEncodedLinkage(const GlobalValue &GV) {
965 return getEncodedLinkage(GV.getLinkage());
966}
967
Charles Saternos75da10d2017-08-04 16:00:58 +0000968static uint64_t getEncodedFFlags(FunctionSummary::FFlags Flags) {
969 uint64_t RawFlags = 0;
970 RawFlags |= Flags.ReadNone;
971 RawFlags |= (Flags.ReadOnly << 1);
972 RawFlags |= (Flags.NoRecurse << 2);
973 RawFlags |= (Flags.ReturnDoesNotAlias << 3);
974 return RawFlags;
975}
976
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000977// Decode the flags for GlobalValue in the summary
978static uint64_t getEncodedGVSummaryFlags(GlobalValueSummary::GVFlags Flags) {
979 uint64_t RawFlags = 0;
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000980
Mehdi Amini1380edf2017-02-03 07:41:43 +0000981 RawFlags |= Flags.NotEligibleToImport; // bool
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000982 RawFlags |= (Flags.Live << 1);
Sean Fertile4595a912017-11-04 17:04:39 +0000983 RawFlags |= (Flags.DSOLocal << 2);
984
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000985 // Linkage don't need to be remapped at that time for the summary. Any future
986 // change to the getEncodedLinkage() function will need to be taken into
987 // account here as well.
Mehdi Amini1380edf2017-02-03 07:41:43 +0000988 RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
989
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000990 return RawFlags;
991}
992
Rafael Espindolaacef6c72014-05-26 13:38:51 +0000993static unsigned getEncodedVisibility(const GlobalValue &GV) {
994 switch (GV.getVisibility()) {
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000995 case GlobalValue::DefaultVisibility: return 0;
996 case GlobalValue::HiddenVisibility: return 1;
997 case GlobalValue::ProtectedVisibility: return 2;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000998 }
Chandler Carruthf3e85022012-01-10 18:08:01 +0000999 llvm_unreachable("Invalid visibility");
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001000}
1001
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001002static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1003 switch (GV.getDLLStorageClass()) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001004 case GlobalValue::DefaultStorageClass: return 0;
1005 case GlobalValue::DLLImportStorageClass: return 1;
1006 case GlobalValue::DLLExportStorageClass: return 2;
1007 }
1008 llvm_unreachable("Invalid DLL storage class");
1009}
1010
Rafael Espindola59f7eba2014-05-28 18:15:43 +00001011static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001012 switch (GV.getThreadLocalMode()) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001013 case GlobalVariable::NotThreadLocal: return 0;
1014 case GlobalVariable::GeneralDynamicTLSModel: return 1;
1015 case GlobalVariable::LocalDynamicTLSModel: return 2;
1016 case GlobalVariable::InitialExecTLSModel: return 3;
1017 case GlobalVariable::LocalExecTLSModel: return 4;
1018 }
1019 llvm_unreachable("Invalid TLS model");
1020}
1021
David Majnemerdad0a642014-06-27 18:19:56 +00001022static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1023 switch (C.getSelectionKind()) {
1024 case Comdat::Any:
1025 return bitc::COMDAT_SELECTION_KIND_ANY;
1026 case Comdat::ExactMatch:
1027 return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
1028 case Comdat::Largest:
1029 return bitc::COMDAT_SELECTION_KIND_LARGEST;
1030 case Comdat::NoDuplicates:
1031 return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
1032 case Comdat::SameSize:
1033 return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
1034 }
1035 llvm_unreachable("Invalid selection kind");
1036}
1037
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001038static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1039 switch (GV.getUnnamedAddr()) {
1040 case GlobalValue::UnnamedAddr::None: return 0;
1041 case GlobalValue::UnnamedAddr::Local: return 2;
1042 case GlobalValue::UnnamedAddr::Global: return 1;
1043 }
1044 llvm_unreachable("Invalid unnamed_addr");
1045}
1046
Peter Collingbournec8556152017-07-06 17:56:01 +00001047size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1048 if (GenerateHash)
1049 Hasher.update(Str);
1050 return StrtabBuilder.add(Str);
1051}
1052
Teresa Johnson37687f32016-04-23 04:30:47 +00001053void ModuleBitcodeWriter::writeComdats() {
David Majnemer90a021f2016-03-13 08:01:03 +00001054 SmallVector<unsigned, 64> Vals;
David Majnemerdad0a642014-06-27 18:19:56 +00001055 for (const Comdat *C : VE.getComdats()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001056 // COMDAT: [strtab offset, strtab size, selection_kind]
Peter Collingbournec8556152017-07-06 17:56:01 +00001057 Vals.push_back(addToStrtab(C->getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001058 Vals.push_back(C->getName().size());
David Majnemerdad0a642014-06-27 18:19:56 +00001059 Vals.push_back(getEncodedComdatSelectionKind(*C));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001060 Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
David Majnemerdad0a642014-06-27 18:19:56 +00001061 Vals.clear();
1062 }
1063}
1064
Teresa Johnsonff642b92015-09-17 20:12:00 +00001065/// Write a record that will eventually hold the word offset of the
1066/// module-level VST. For now the offset is 0, which will be backpatched
Teresa Johnson37687f32016-04-23 04:30:47 +00001067/// after the real VST is written. Saves the bit offset to backpatch.
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001068void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001069 // Write a placeholder value in for the offset of the real VST,
1070 // which is written after the function blocks so that it can include
1071 // the offset of each function. The placeholder offset will be
1072 // updated when the real VST is written.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001073 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnsonff642b92015-09-17 20:12:00 +00001074 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_VSTOFFSET));
1075 // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1076 // hold the real VST offset. Must use fixed instead of VBR as we don't
1077 // know how many VBR chunks to reserve ahead of time.
1078 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001079 unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnsonff642b92015-09-17 20:12:00 +00001080
1081 // Emit the placeholder
1082 uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001083 Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001084
Teresa Johnson37687f32016-04-23 04:30:47 +00001085 // Compute and save the bit offset to the placeholder, which will be
Teresa Johnsonff642b92015-09-17 20:12:00 +00001086 // patched when the real VST is written. We can simply subtract the 32-bit
1087 // fixed size from the current bit number to get the location to backpatch.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001088 VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
Teresa Johnsonff642b92015-09-17 20:12:00 +00001089}
1090
Teresa Johnsone1164de2016-02-10 21:55:02 +00001091enum StringEncoding { SE_Char6, SE_Fixed7, SE_Fixed8 };
1092
1093/// Determine the encoding to use for the given string name and length.
David Blaikieb6b42e02017-06-02 17:24:26 +00001094static StringEncoding getStringEncoding(StringRef Str) {
Teresa Johnsone1164de2016-02-10 21:55:02 +00001095 bool isChar6 = true;
David Blaikieb6b42e02017-06-02 17:24:26 +00001096 for (char C : Str) {
Teresa Johnsone1164de2016-02-10 21:55:02 +00001097 if (isChar6)
David Blaikieb6b42e02017-06-02 17:24:26 +00001098 isChar6 = BitCodeAbbrevOp::isChar6(C);
1099 if ((unsigned char)C & 128)
Teresa Johnsone1164de2016-02-10 21:55:02 +00001100 // don't bother scanning the rest.
1101 return SE_Fixed8;
1102 }
1103 if (isChar6)
1104 return SE_Char6;
David Blaikieb6b42e02017-06-02 17:24:26 +00001105 return SE_Fixed7;
Teresa Johnsone1164de2016-02-10 21:55:02 +00001106}
1107
Teresa Johnsonff642b92015-09-17 20:12:00 +00001108/// Emit top-level description of module, including target triple, inline asm,
1109/// descriptors for global variables, and function prototype info.
1110/// Returns the bit offset to backpatch with the location of the real VST.
Teresa Johnson37687f32016-04-23 04:30:47 +00001111void ModuleBitcodeWriter::writeModuleInfo() {
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001112 // Emit various pieces of data attached to a module.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001113 if (!M.getTargetTriple().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001114 writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001115 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001116 const std::string &DL = M.getDataLayoutStr();
Rafael Espindolaf863ee22014-02-25 20:01:08 +00001117 if (!DL.empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001118 writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001119 if (!M.getModuleInlineAsm().empty())
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001120 writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001121 0 /*TODO*/);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001122
Gordon Henriksend930f912008-08-17 18:44:35 +00001123 // Emit information about sections and GC, computing how many there are. Also
1124 // compute the maximum alignment value.
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001125 std::map<std::string, unsigned> SectionMap;
Gordon Henriksend930f912008-08-17 18:44:35 +00001126 std::map<std::string, unsigned> GCMap;
Chris Lattner4b00d922007-04-23 16:04:05 +00001127 unsigned MaxAlignment = 0;
Chris Lattnerb5491372007-04-23 18:58:34 +00001128 unsigned MaxGlobalType = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001129 for (const GlobalValue &GV : M.globals()) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001130 MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
David Blaikie1a848da2015-04-27 19:58:56 +00001131 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001132 if (GV.hasSection()) {
Chad Rosier75ec09c2011-08-12 16:45:18 +00001133 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001134 unsigned &Entry = SectionMap[GV.getSection()];
Chad Rosier75ec09c2011-08-12 16:45:18 +00001135 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001136 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001137 0 /*TODO*/);
Chad Rosier75ec09c2011-08-12 16:45:18 +00001138 Entry = SectionMap.size();
1139 }
1140 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001141 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001142 for (const Function &F : M) {
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001143 MaxAlignment = std::max(MaxAlignment, F.getAlignment());
1144 if (F.hasSection()) {
Gordon Henriksen71183b62007-12-10 03:18:06 +00001145 // Give section names unique ID's.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001146 unsigned &Entry = SectionMap[F.getSection()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001147 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001148 writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
Teresa Johnson37687f32016-04-23 04:30:47 +00001149 0 /*TODO*/);
Gordon Henriksen71183b62007-12-10 03:18:06 +00001150 Entry = SectionMap.size();
1151 }
1152 }
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001153 if (F.hasGC()) {
Gordon Henriksend930f912008-08-17 18:44:35 +00001154 // Same for GC names.
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001155 unsigned &Entry = GCMap[F.getGC()];
Gordon Henriksen71183b62007-12-10 03:18:06 +00001156 if (!Entry) {
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00001157 writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1158 0 /*TODO*/);
Gordon Henriksend930f912008-08-17 18:44:35 +00001159 Entry = GCMap.size();
Gordon Henriksen71183b62007-12-10 03:18:06 +00001160 }
1161 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001162 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001163
Chris Lattner4b00d922007-04-23 16:04:05 +00001164 // Emit abbrev for globals, now that we know # sections and max alignment.
1165 unsigned SimpleGVarAbbrev = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001166 if (!M.global_empty()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001167 // Add an abbrev for common globals with no visibility or thread localness.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001168 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner4b00d922007-04-23 16:04:05 +00001169 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1171 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Chris Lattner2eae59f2007-05-04 20:34:50 +00001172 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001173 Log2_32_Ceil(MaxGlobalType+1)));
David Blaikie1a848da2015-04-27 19:58:56 +00001174 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1175 //| explicitType << 1
1176 //| constant
1177 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1178 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1179 if (MaxAlignment == 0) // Alignment.
Chris Lattner4b00d922007-04-23 16:04:05 +00001180 Abbv->Add(BitCodeAbbrevOp(0));
1181 else {
1182 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
Chris Lattner2eae59f2007-05-04 20:34:50 +00001183 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattnerb5491372007-04-23 18:58:34 +00001184 Log2_32_Ceil(MaxEncAlignment+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001185 }
1186 if (SectionMap.empty()) // Section.
1187 Abbv->Add(BitCodeAbbrevOp(0));
1188 else
Chris Lattner2eae59f2007-05-04 20:34:50 +00001189 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
Chris Lattner1e50c292007-04-24 03:29:47 +00001190 Log2_32_Ceil(SectionMap.size()+1)));
Chris Lattner4b00d922007-04-23 16:04:05 +00001191 // Don't bother emitting vis + thread local.
David Blaikie7ad9dc12017-01-04 22:36:33 +00001192 SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Chris Lattner4b00d922007-04-23 16:04:05 +00001193 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001194
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001195 SmallVector<unsigned, 64> Vals;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001196 // Emit the module's source file name.
1197 {
David Blaikieb6b42e02017-06-02 17:24:26 +00001198 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001199 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
1200 if (Bits == SE_Char6)
1201 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1202 else if (Bits == SE_Fixed7)
1203 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1204
1205 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1206 auto Abbv = std::make_shared<BitCodeAbbrev>();
1207 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
1208 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1209 Abbv->Add(AbbrevOpToUse);
1210 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1211
1212 for (const auto P : M.getSourceFileName())
1213 Vals.push_back((unsigned char)P);
1214
1215 // Emit the finished record.
1216 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1217 Vals.clear();
1218 }
1219
1220 // Emit the global variable information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001221 for (const GlobalVariable &GV : M.globals()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001222 unsigned AbbrevToUse = 0;
1223
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001224 // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00001225 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00001226 // unnamed_addr, externally_initialized, dllstorageclass,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001227 // comdat, attributes, DSO_Local]
Peter Collingbournec8556152017-07-06 17:56:01 +00001228 Vals.push_back(addToStrtab(GV.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001229 Vals.push_back(GV.getName().size());
David Blaikie1a848da2015-04-27 19:58:56 +00001230 Vals.push_back(VE.getTypeID(GV.getValueType()));
1231 Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001232 Vals.push_back(GV.isDeclaration() ? 0 :
1233 (VE.getValueID(GV.getInitializer()) + 1));
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001234 Vals.push_back(getEncodedLinkage(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001235 Vals.push_back(Log2_32(GV.getAlignment())+1);
1236 Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
1237 if (GV.isThreadLocal() ||
1238 GV.getVisibility() != GlobalValue::DefaultVisibility ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001239 GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1240 GV.isExternallyInitialized() ||
David Majnemerdad0a642014-06-27 18:19:56 +00001241 GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
Javed Absarf3d79042017-05-11 12:28:08 +00001242 GV.hasComdat() ||
Sean Fertilec70d28b2017-10-26 15:00:26 +00001243 GV.hasAttributes() ||
1244 GV.isDSOLocal()) {
Chris Lattner4b00d922007-04-23 16:04:05 +00001245 Vals.push_back(getEncodedVisibility(GV));
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001246 Vals.push_back(getEncodedThreadLocalMode(GV));
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001247 Vals.push_back(getEncodedUnnamedAddr(GV));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001248 Vals.push_back(GV.isExternallyInitialized());
Nico Rieck7157bb72014-01-14 15:22:47 +00001249 Vals.push_back(getEncodedDLLStorageClass(GV));
David Majnemerdad0a642014-06-27 18:19:56 +00001250 Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
Javed Absarf3d79042017-05-11 12:28:08 +00001251
1252 auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1253 Vals.push_back(VE.getAttributeListID(AL));
Sean Fertilec70d28b2017-10-26 15:00:26 +00001254
1255 Vals.push_back(GV.isDSOLocal());
Chris Lattner4b00d922007-04-23 16:04:05 +00001256 } else {
1257 AbbrevToUse = SimpleGVarAbbrev;
1258 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001259
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001260 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001261 Vals.clear();
1262 }
1263
1264 // Emit the function proto information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001265 for (const Function &F : M) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001266 // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1267 // linkage, paramattrs, alignment, section, visibility, gc,
1268 // unnamed_addr, prologuedata, dllstorageclass, comdat,
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001269 // prefixdata, personalityfn, DSO_Local, addrspace]
Peter Collingbournec8556152017-07-06 17:56:01 +00001270 Vals.push_back(addToStrtab(F.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001271 Vals.push_back(F.getName().size());
David Blaikie561a1572015-04-17 16:28:26 +00001272 Vals.push_back(VE.getTypeID(F.getFunctionType()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001273 Vals.push_back(F.getCallingConv());
1274 Vals.push_back(F.isDeclaration());
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001275 Vals.push_back(getEncodedLinkage(F));
Reid Klecknerb4a2d182017-04-24 20:38:30 +00001276 Vals.push_back(VE.getAttributeListID(F.getAttributes()));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001277 Vals.push_back(Log2_32(F.getAlignment())+1);
1278 Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001279 Vals.push_back(getEncodedVisibility(F));
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001280 Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001281 Vals.push_back(getEncodedUnnamedAddr(F));
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001282 Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1283 : 0);
Nico Rieck7157bb72014-01-14 15:22:47 +00001284 Vals.push_back(getEncodedDLLStorageClass(F));
David Majnemerdad0a642014-06-27 18:19:56 +00001285 Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00001286 Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1287 : 0);
David Majnemer7fddecc2015-06-17 20:52:32 +00001288 Vals.push_back(
1289 F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001290
Sean Fertilec70d28b2017-10-26 15:00:26 +00001291 Vals.push_back(F.isDSOLocal());
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00001292 Vals.push_back(F.getAddressSpace());
1293
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001294 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001295 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001296 Vals.clear();
1297 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001298
Chris Lattner44c17072007-04-26 02:46:40 +00001299 // Emit the alias information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001300 for (const GlobalAlias &A : M.aliases()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001301 // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
Sean Fertilec70d28b2017-10-26 15:00:26 +00001302 // visibility, dllstorageclass, threadlocal, unnamed_addr,
1303 // DSO_Local]
Peter Collingbournec8556152017-07-06 17:56:01 +00001304 Vals.push_back(addToStrtab(A.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001305 Vals.push_back(A.getName().size());
David Blaikie6a51dbd2015-09-17 22:18:59 +00001306 Vals.push_back(VE.getTypeID(A.getValueType()));
1307 Vals.push_back(A.getType()->getAddressSpace());
Rafael Espindolaacef6c72014-05-26 13:38:51 +00001308 Vals.push_back(VE.getValueID(A.getAliasee()));
1309 Vals.push_back(getEncodedLinkage(A));
1310 Vals.push_back(getEncodedVisibility(A));
1311 Vals.push_back(getEncodedDLLStorageClass(A));
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00001312 Vals.push_back(getEncodedThreadLocalMode(A));
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001313 Vals.push_back(getEncodedUnnamedAddr(A));
Sean Fertilec70d28b2017-10-26 15:00:26 +00001314 Vals.push_back(A.isDSOLocal());
1315
Chris Lattner44c17072007-04-26 02:46:40 +00001316 unsigned AbbrevToUse = 0;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001317 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
Chris Lattner44c17072007-04-26 02:46:40 +00001318 Vals.clear();
1319 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001320
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001321 // Emit the ifunc information.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001322 for (const GlobalIFunc &I : M.ifuncs()) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001323 // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
Rafael Espindola3b9843f2018-01-12 17:03:43 +00001324 // val#, linkage, visibility, DSO_Local]
Peter Collingbournec8556152017-07-06 17:56:01 +00001325 Vals.push_back(addToStrtab(I.getName()));
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001326 Vals.push_back(I.getName().size());
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001327 Vals.push_back(VE.getTypeID(I.getValueType()));
1328 Vals.push_back(I.getType()->getAddressSpace());
1329 Vals.push_back(VE.getValueID(I.getResolver()));
1330 Vals.push_back(getEncodedLinkage(I));
1331 Vals.push_back(getEncodedVisibility(I));
Rafael Espindola3b9843f2018-01-12 17:03:43 +00001332 Vals.push_back(I.isDSOLocal());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001333 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
Dmitry Polukhina1feff72016-04-07 12:32:19 +00001334 Vals.clear();
1335 }
1336
Teresa Johnson37687f32016-04-23 04:30:47 +00001337 writeValueSymbolTableForwardDecl();
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001338}
1339
Teresa Johnson37687f32016-04-23 04:30:47 +00001340static uint64_t getOptimizationFlags(const Value *V) {
Dan Gohman0ebd6962009-07-20 21:19:07 +00001341 uint64_t Flags = 0;
1342
Sanjay Patelc00017d2014-10-15 17:45:13 +00001343 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
Dan Gohman16f54152009-08-20 17:11:38 +00001344 if (OBO->hasNoSignedWrap())
1345 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1346 if (OBO->hasNoUnsignedWrap())
1347 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001348 } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
Chris Lattner35315d02011-02-06 21:44:57 +00001349 if (PEO->isExact())
1350 Flags |= 1 << bitc::PEO_EXACT;
Sanjay Patelc00017d2014-10-15 17:45:13 +00001351 } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
Sanjay Patel629c4112017-11-06 16:27:15 +00001352 if (FPMO->hasAllowReassoc())
Steven Wu545d34a2018-02-19 19:22:28 +00001353 Flags |= bitc::AllowReassoc;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001354 if (FPMO->hasNoNaNs())
Steven Wu545d34a2018-02-19 19:22:28 +00001355 Flags |= bitc::NoNaNs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001356 if (FPMO->hasNoInfs())
Steven Wu545d34a2018-02-19 19:22:28 +00001357 Flags |= bitc::NoInfs;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001358 if (FPMO->hasNoSignedZeros())
Steven Wu545d34a2018-02-19 19:22:28 +00001359 Flags |= bitc::NoSignedZeros;
Michael Ilseman9978d7e2012-11-27 00:43:38 +00001360 if (FPMO->hasAllowReciprocal())
Steven Wu545d34a2018-02-19 19:22:28 +00001361 Flags |= bitc::AllowReciprocal;
Adam Nemetcd847a82017-03-28 20:11:52 +00001362 if (FPMO->hasAllowContract())
Steven Wu545d34a2018-02-19 19:22:28 +00001363 Flags |= bitc::AllowContract;
Sanjay Patel629c4112017-11-06 16:27:15 +00001364 if (FPMO->hasApproxFunc())
Steven Wu545d34a2018-02-19 19:22:28 +00001365 Flags |= bitc::ApproxFunc;
Dan Gohman0ebd6962009-07-20 21:19:07 +00001366 }
1367
1368 return Flags;
1369}
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001370
Teresa Johnson37687f32016-04-23 04:30:47 +00001371void ModuleBitcodeWriter::writeValueAsMetadata(
1372 const ValueAsMetadata *MD, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001373 // Mimic an MDNode with a value as one operand.
1374 Value *V = MD->getValue();
1375 Record.push_back(VE.getTypeID(V->getType()));
1376 Record.push_back(VE.getValueID(V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001377 Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001378 Record.clear();
1379}
1380
Teresa Johnson37687f32016-04-23 04:30:47 +00001381void ModuleBitcodeWriter::writeMDTuple(const MDTuple *N,
1382 SmallVectorImpl<uint64_t> &Record,
1383 unsigned Abbrev) {
Chris Lattner9b493022009-12-31 01:22:29 +00001384 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001385 Metadata *MD = N->getOperand(i);
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001386 assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1387 "Unexpected function-local metadata");
1388 Record.push_back(VE.getMetadataOrNullID(MD));
Devang Patel8cca7b42009-08-04 05:01:35 +00001389 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001390 Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1391 : bitc::METADATA_NODE,
1392 Record, Abbrev);
Devang Patel8cca7b42009-08-04 05:01:35 +00001393 Record.clear();
1394}
Devang Patele059ba6e2009-07-23 01:07:34 +00001395
Teresa Johnson37687f32016-04-23 04:30:47 +00001396unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001397 // Assume the column is usually under 128, and always output the inlined-at
1398 // location (it's never more expensive than building an array size 1).
David Blaikie7ad9dc12017-01-04 22:36:33 +00001399 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001400 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_LOCATION));
1401 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1402 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1403 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1404 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1405 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
Calixte Denizeteb7f6022018-09-20 08:53:06 +00001406 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001407 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001408}
1409
Teresa Johnson37687f32016-04-23 04:30:47 +00001410void ModuleBitcodeWriter::writeDILocation(const DILocation *N,
1411 SmallVectorImpl<uint64_t> &Record,
1412 unsigned &Abbrev) {
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001413 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001414 Abbrev = createDILocationAbbrev();
Duncan P. N. Exon Smith625fda22016-03-24 16:25:51 +00001415
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001416 Record.push_back(N->isDistinct());
1417 Record.push_back(N->getLine());
1418 Record.push_back(N->getColumn());
1419 Record.push_back(VE.getMetadataID(N->getScope()));
Duncan P. N. Exon Smith9a6f64e2015-01-20 01:00:23 +00001420 Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
Calixte Denizeteb7f6022018-09-20 08:53:06 +00001421 Record.push_back(N->isImplicitCode());
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001422
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001423 Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001424 Record.clear();
1425}
1426
Teresa Johnson37687f32016-04-23 04:30:47 +00001427unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001428 // Assume the column is usually under 128, and always output the inlined-at
1429 // location (it's never more expensive than building an array size 1).
David Blaikie7ad9dc12017-01-04 22:36:33 +00001430 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001431 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_GENERIC_DEBUG));
1432 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1433 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1434 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1435 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1436 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1437 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001438 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001439}
1440
Teresa Johnson37687f32016-04-23 04:30:47 +00001441void ModuleBitcodeWriter::writeGenericDINode(const GenericDINode *N,
1442 SmallVectorImpl<uint64_t> &Record,
1443 unsigned &Abbrev) {
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001444 if (!Abbrev)
Teresa Johnson37687f32016-04-23 04:30:47 +00001445 Abbrev = createGenericDINodeAbbrev();
Duncan P. N. Exon Smitha5e25a52016-03-24 16:30:18 +00001446
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001447 Record.push_back(N->isDistinct());
1448 Record.push_back(N->getTag());
1449 Record.push_back(0); // Per-tag version field; unused for now.
1450
1451 for (auto &I : N->operands())
1452 Record.push_back(VE.getMetadataOrNullID(I));
1453
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001454 Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001455 Record.clear();
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001456}
1457
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001458static uint64_t rotateSign(int64_t I) {
1459 uint64_t U = I;
1460 return I < 0 ? ~(U << 1) : U << 1;
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001461}
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001462
Teresa Johnson37687f32016-04-23 04:30:47 +00001463void ModuleBitcodeWriter::writeDISubrange(const DISubrange *N,
1464 SmallVectorImpl<uint64_t> &Record,
1465 unsigned Abbrev) {
Sander de Smalenfdf40912018-01-24 09:56:07 +00001466 const uint64_t Version = 1 << 1;
1467 Record.push_back((uint64_t)N->isDistinct() | Version);
1468 Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
Duncan P. N. Exon Smith5dcf6212015-04-07 00:39:59 +00001469 Record.push_back(rotateSign(N->getLowerBound()));
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001470
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001471 Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001472 Record.clear();
1473}
1474
Teresa Johnson37687f32016-04-23 04:30:47 +00001475void ModuleBitcodeWriter::writeDIEnumerator(const DIEnumerator *N,
1476 SmallVectorImpl<uint64_t> &Record,
1477 unsigned Abbrev) {
Momchil Velikov08dc66e2018-02-12 16:10:09 +00001478 Record.push_back((N->isUnsigned() << 1) | N->isDistinct());
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001479 Record.push_back(rotateSign(N->getValue()));
1480 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1481
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001482 Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001483 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001484}
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001485
Teresa Johnson37687f32016-04-23 04:30:47 +00001486void ModuleBitcodeWriter::writeDIBasicType(const DIBasicType *N,
1487 SmallVectorImpl<uint64_t> &Record,
1488 unsigned Abbrev) {
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001489 Record.push_back(N->isDistinct());
1490 Record.push_back(N->getTag());
1491 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1492 Record.push_back(N->getSizeInBits());
1493 Record.push_back(N->getAlignInBits());
1494 Record.push_back(N->getEncoding());
Adrian Prantl55f42622018-08-14 19:35:34 +00001495 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001496
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001497 Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001498 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001499}
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001500
Teresa Johnson37687f32016-04-23 04:30:47 +00001501void ModuleBitcodeWriter::writeDIDerivedType(const DIDerivedType *N,
1502 SmallVectorImpl<uint64_t> &Record,
1503 unsigned Abbrev) {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001504 Record.push_back(N->isDistinct());
1505 Record.push_back(N->getTag());
1506 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1507 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1508 Record.push_back(N->getLine());
1509 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001510 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001511 Record.push_back(N->getSizeInBits());
1512 Record.push_back(N->getAlignInBits());
1513 Record.push_back(N->getOffsetInBits());
1514 Record.push_back(N->getFlags());
1515 Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1516
Konstantin Zhuravlyovd5561e02017-03-08 23:55:44 +00001517 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1518 // that there is no DWARF address space associated with DIDerivedType.
1519 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1520 Record.push_back(*DWARFAddressSpace + 1);
1521 else
1522 Record.push_back(0);
1523
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001524 Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001525 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001526}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001527
Teresa Johnson37687f32016-04-23 04:30:47 +00001528void ModuleBitcodeWriter::writeDICompositeType(
1529 const DICompositeType *N, SmallVectorImpl<uint64_t> &Record,
1530 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001531 const unsigned IsNotUsedInOldTypeRef = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001532 Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001533 Record.push_back(N->getTag());
1534 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1535 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1536 Record.push_back(N->getLine());
1537 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1538 Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1539 Record.push_back(N->getSizeInBits());
1540 Record.push_back(N->getAlignInBits());
1541 Record.push_back(N->getOffsetInBits());
1542 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001543 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001544 Record.push_back(N->getRuntimeLang());
1545 Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001546 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001547 Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
Adrian Prantl8c599212018-02-06 23:45:59 +00001548 Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001549
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001550 Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001551 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001552}
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001553
Teresa Johnson37687f32016-04-23 04:30:47 +00001554void ModuleBitcodeWriter::writeDISubroutineType(
1555 const DISubroutineType *N, SmallVectorImpl<uint64_t> &Record,
1556 unsigned Abbrev) {
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001557 const unsigned HasNoOldTypeRefs = 0x2;
Aaron Ballmanc79c2be2016-04-24 13:03:20 +00001558 Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001559 Record.push_back(N->getFlags());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001560 Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001561 Record.push_back(N->getCC());
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001562
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001563 Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001564 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001565}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001566
Teresa Johnson37687f32016-04-23 04:30:47 +00001567void ModuleBitcodeWriter::writeDIFile(const DIFile *N,
1568 SmallVectorImpl<uint64_t> &Record,
1569 unsigned Abbrev) {
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001570 Record.push_back(N->isDistinct());
1571 Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1572 Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
Scott Linder71603842018-02-12 19:45:54 +00001573 if (N->getRawChecksum()) {
1574 Record.push_back(N->getRawChecksum()->Kind);
1575 Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1576 } else {
1577 // Maintain backwards compatibility with the old internal representation of
1578 // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1579 Record.push_back(0);
1580 Record.push_back(VE.getMetadataOrNullID(nullptr));
1581 }
Scott Linder16c7bda2018-02-23 23:01:06 +00001582 auto Source = N->getRawSource();
1583 if (Source)
1584 Record.push_back(VE.getMetadataOrNullID(*Source));
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001585
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001586 Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001587 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001588}
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001589
Teresa Johnson37687f32016-04-23 04:30:47 +00001590void ModuleBitcodeWriter::writeDICompileUnit(const DICompileUnit *N,
1591 SmallVectorImpl<uint64_t> &Record,
1592 unsigned Abbrev) {
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00001593 assert(N->isDistinct() && "Expected distinct compile units");
1594 Record.push_back(/* IsDistinct */ true);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001595 Record.push_back(N->getSourceLanguage());
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001596 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001597 Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1598 Record.push_back(N->isOptimized());
1599 Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1600 Record.push_back(N->getRuntimeVersion());
1601 Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1602 Record.push_back(N->getEmissionKind());
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001603 Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1604 Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
Adrian Prantl75819ae2016-04-15 15:57:41 +00001605 Record.push_back(/* subprograms */ 0);
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001606 Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1607 Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
Adrian Prantl1f599f92015-05-21 20:37:30 +00001608 Record.push_back(N->getDWOId());
Amjad Abouda9bcf162015-12-10 12:56:35 +00001609 Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
David Blaikiea01f2952016-08-24 18:29:49 +00001610 Record.push_back(N->getSplitDebugInlining());
Dehao Chen0944a8c2017-02-01 22:45:09 +00001611 Record.push_back(N->getDebugInfoForProfiling());
David Blaikie66cf14d2018-08-16 21:29:55 +00001612 Record.push_back((unsigned)N->getNameTableKind());
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001613
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001614 Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001615 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001616}
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001617
Teresa Johnson37687f32016-04-23 04:30:47 +00001618void ModuleBitcodeWriter::writeDISubprogram(const DISubprogram *N,
1619 SmallVectorImpl<uint64_t> &Record,
1620 unsigned Abbrev) {
Adrian Prantl85338cb2016-05-06 22:53:06 +00001621 uint64_t HasUnitFlag = 1 << 1;
1622 Record.push_back(N->isDistinct() | HasUnitFlag);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001623 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1624 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1625 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1626 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1627 Record.push_back(N->getLine());
1628 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1629 Record.push_back(N->isLocalToUnit());
1630 Record.push_back(N->isDefinition());
1631 Record.push_back(N->getScopeLine());
1632 Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1633 Record.push_back(N->getVirtuality());
1634 Record.push_back(N->getVirtualIndex());
1635 Record.push_back(N->getFlags());
1636 Record.push_back(N->isOptimized());
Adrian Prantl75819ae2016-04-15 15:57:41 +00001637 Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
Duncan P. N. Exon Smith11344732015-04-07 16:50:39 +00001638 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001639 Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
Shiva Chen2c864552018-05-09 02:40:45 +00001640 Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
Reid Klecknerb5af11d2016-07-01 02:41:21 +00001641 Record.push_back(N->getThisAdjustment());
Adrian Prantl1d12b882017-04-26 22:56:44 +00001642 Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001643
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001644 Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001645 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001646}
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001647
Teresa Johnson37687f32016-04-23 04:30:47 +00001648void ModuleBitcodeWriter::writeDILexicalBlock(const DILexicalBlock *N,
1649 SmallVectorImpl<uint64_t> &Record,
1650 unsigned Abbrev) {
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001651 Record.push_back(N->isDistinct());
1652 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1653 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1654 Record.push_back(N->getLine());
1655 Record.push_back(N->getColumn());
1656
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001657 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001658 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001659}
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001660
Teresa Johnson37687f32016-04-23 04:30:47 +00001661void ModuleBitcodeWriter::writeDILexicalBlockFile(
1662 const DILexicalBlockFile *N, SmallVectorImpl<uint64_t> &Record,
1663 unsigned Abbrev) {
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001664 Record.push_back(N->isDistinct());
1665 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1666 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1667 Record.push_back(N->getDiscriminator());
1668
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001669 Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001670 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001671}
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001672
Teresa Johnson37687f32016-04-23 04:30:47 +00001673void ModuleBitcodeWriter::writeDINamespace(const DINamespace *N,
1674 SmallVectorImpl<uint64_t> &Record,
1675 unsigned Abbrev) {
Adrian Prantldbfda632016-11-03 19:42:02 +00001676 Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001677 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001678 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001679
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001680 Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001681 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001682}
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001683
Teresa Johnson37687f32016-04-23 04:30:47 +00001684void ModuleBitcodeWriter::writeDIMacro(const DIMacro *N,
1685 SmallVectorImpl<uint64_t> &Record,
1686 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001687 Record.push_back(N->isDistinct());
1688 Record.push_back(N->getMacinfoType());
1689 Record.push_back(N->getLine());
1690 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1691 Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1692
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001693 Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001694 Record.clear();
1695}
1696
Teresa Johnson37687f32016-04-23 04:30:47 +00001697void ModuleBitcodeWriter::writeDIMacroFile(const DIMacroFile *N,
1698 SmallVectorImpl<uint64_t> &Record,
1699 unsigned Abbrev) {
Amjad Abouda9bcf162015-12-10 12:56:35 +00001700 Record.push_back(N->isDistinct());
1701 Record.push_back(N->getMacinfoType());
1702 Record.push_back(N->getLine());
1703 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1704 Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1705
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001706 Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
Amjad Abouda9bcf162015-12-10 12:56:35 +00001707 Record.clear();
1708}
1709
Teresa Johnson37687f32016-04-23 04:30:47 +00001710void ModuleBitcodeWriter::writeDIModule(const DIModule *N,
1711 SmallVectorImpl<uint64_t> &Record,
1712 unsigned Abbrev) {
Adrian Prantlab1243f2015-06-29 23:03:47 +00001713 Record.push_back(N->isDistinct());
1714 for (auto &I : N->operands())
1715 Record.push_back(VE.getMetadataOrNullID(I));
1716
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001717 Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
Adrian Prantlab1243f2015-06-29 23:03:47 +00001718 Record.clear();
1719}
1720
Teresa Johnson37687f32016-04-23 04:30:47 +00001721void ModuleBitcodeWriter::writeDITemplateTypeParameter(
1722 const DITemplateTypeParameter *N, SmallVectorImpl<uint64_t> &Record,
1723 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001724 Record.push_back(N->isDistinct());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001725 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1726 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1727
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001728 Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001729 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001730}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001731
Teresa Johnson37687f32016-04-23 04:30:47 +00001732void ModuleBitcodeWriter::writeDITemplateValueParameter(
1733 const DITemplateValueParameter *N, SmallVectorImpl<uint64_t> &Record,
1734 unsigned Abbrev) {
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001735 Record.push_back(N->isDistinct());
1736 Record.push_back(N->getTag());
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001737 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1738 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1739 Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1740
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001741 Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001742 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001743}
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001744
Teresa Johnson37687f32016-04-23 04:30:47 +00001745void ModuleBitcodeWriter::writeDIGlobalVariable(
1746 const DIGlobalVariable *N, SmallVectorImpl<uint64_t> &Record,
1747 unsigned Abbrev) {
Matthew Vossf8ab35a2018-10-03 18:44:53 +00001748 const uint64_t Version = 2 << 1;
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001749 Record.push_back((uint64_t)N->isDistinct() | Version);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001750 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1751 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1752 Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1753 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1754 Record.push_back(N->getLine());
1755 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1756 Record.push_back(N->isLocalToUnit());
1757 Record.push_back(N->isDefinition());
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001758 Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
Matthew Vossf8ab35a2018-10-03 18:44:53 +00001759 Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
Victor Leschuk2ede1262016-10-20 00:13:12 +00001760 Record.push_back(N->getAlignInBits());
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001761
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001762 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001763 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001764}
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001765
Teresa Johnson37687f32016-04-23 04:30:47 +00001766void ModuleBitcodeWriter::writeDILocalVariable(
1767 const DILocalVariable *N, SmallVectorImpl<uint64_t> &Record,
1768 unsigned Abbrev) {
Victor Leschuk2ede1262016-10-20 00:13:12 +00001769 // In order to support all possible bitcode formats in BitcodeReader we need
Simon Pilgrim25059362016-10-20 10:42:14 +00001770 // to distinguish the following cases:
Victor Leschuk2ede1262016-10-20 00:13:12 +00001771 // 1) Record has no artificial tag (Record[1]),
1772 // has no obsolete inlinedAt field (Record[9]).
1773 // In this case Record size will be 8, HasAlignment flag is false.
1774 // 2) Record has artificial tag (Record[1]),
1775 // has no obsolete inlignedAt field (Record[9]).
1776 // In this case Record size will be 9, HasAlignment flag is false.
1777 // 3) Record has both artificial tag (Record[1]) and
1778 // obsolete inlignedAt field (Record[9]).
1779 // In this case Record size will be 10, HasAlignment flag is false.
1780 // 4) Record has neither artificial tag, nor inlignedAt field, but
1781 // HasAlignment flag is true and Record[8] contains alignment value.
1782 const uint64_t HasAlignmentFlag = 1 << 1;
Simon Pilgrim071da462016-10-20 10:37:58 +00001783 Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001784 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1785 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1786 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1787 Record.push_back(N->getLine());
1788 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1789 Record.push_back(N->getArg());
1790 Record.push_back(N->getFlags());
Victor Leschuk2ede1262016-10-20 00:13:12 +00001791 Record.push_back(N->getAlignInBits());
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001792
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001793 Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001794 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001795}
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001796
Shiva Chen2c864552018-05-09 02:40:45 +00001797void ModuleBitcodeWriter::writeDILabel(
1798 const DILabel *N, SmallVectorImpl<uint64_t> &Record,
1799 unsigned Abbrev) {
1800 Record.push_back((uint64_t)N->isDistinct());
1801 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1802 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1803 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1804 Record.push_back(N->getLine());
1805
1806 Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
1807 Record.clear();
1808}
1809
Teresa Johnson37687f32016-04-23 04:30:47 +00001810void ModuleBitcodeWriter::writeDIExpression(const DIExpression *N,
1811 SmallVectorImpl<uint64_t> &Record,
1812 unsigned Abbrev) {
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001813 Record.reserve(N->getElements().size() + 1);
Florian Hahnffc498d2017-06-14 13:14:38 +00001814 const uint64_t Version = 3 << 1;
Adrian Prantl6825fb62017-04-18 01:21:53 +00001815 Record.push_back((uint64_t)N->isDistinct() | Version);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001816 Record.append(N->elements_begin(), N->elements_end());
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001817
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001818 Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001819 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001820}
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001821
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001822void ModuleBitcodeWriter::writeDIGlobalVariableExpression(
1823 const DIGlobalVariableExpression *N, SmallVectorImpl<uint64_t> &Record,
1824 unsigned Abbrev) {
1825 Record.push_back(N->isDistinct());
1826 Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
1827 Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
Charles Saternos75da10d2017-08-04 16:00:58 +00001828
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001829 Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
1830 Record.clear();
1831}
1832
Teresa Johnson37687f32016-04-23 04:30:47 +00001833void ModuleBitcodeWriter::writeDIObjCProperty(const DIObjCProperty *N,
1834 SmallVectorImpl<uint64_t> &Record,
1835 unsigned Abbrev) {
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001836 Record.push_back(N->isDistinct());
1837 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1838 Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1839 Record.push_back(N->getLine());
1840 Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
1841 Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
1842 Record.push_back(N->getAttributes());
1843 Record.push_back(VE.getMetadataOrNullID(N->getType()));
1844
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001845 Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001846 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001847}
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001848
Teresa Johnson37687f32016-04-23 04:30:47 +00001849void ModuleBitcodeWriter::writeDIImportedEntity(
1850 const DIImportedEntity *N, SmallVectorImpl<uint64_t> &Record,
1851 unsigned Abbrev) {
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001852 Record.push_back(N->isDistinct());
1853 Record.push_back(N->getTag());
1854 Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1855 Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
1856 Record.push_back(N->getLine());
1857 Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
Adrian Prantld63bfd22017-07-19 00:09:54 +00001858 Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001859
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001860 Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001861 Record.clear();
Duncan P. N. Exon Smith01fc1762015-02-10 00:52:32 +00001862}
1863
Teresa Johnson37687f32016-04-23 04:30:47 +00001864unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
David Blaikie7ad9dc12017-01-04 22:36:33 +00001865 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001866 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_NAME));
1867 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
1868 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001869 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001870}
1871
Teresa Johnson37687f32016-04-23 04:30:47 +00001872void ModuleBitcodeWriter::writeNamedMetadata(
1873 SmallVectorImpl<uint64_t> &Record) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001874 if (M.named_metadata_empty())
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001875 return;
1876
Teresa Johnson37687f32016-04-23 04:30:47 +00001877 unsigned Abbrev = createNamedMetadataAbbrev();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001878 for (const NamedMDNode &NMD : M.named_metadata()) {
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001879 // Write name.
1880 StringRef Str = NMD.getName();
1881 Record.append(Str.bytes_begin(), Str.bytes_end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001882 Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001883 Record.clear();
1884
1885 // Write named metadata operands.
1886 for (const MDNode *N : NMD.operands())
1887 Record.push_back(VE.getMetadataID(N));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001888 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
Duncan P. N. Exon Smithf8ecdf52016-03-24 16:16:08 +00001889 Record.clear();
1890 }
1891}
1892
Teresa Johnson37687f32016-04-23 04:30:47 +00001893unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
David Blaikie7ad9dc12017-01-04 22:36:33 +00001894 auto Abbv = std::make_shared<BitCodeAbbrev>();
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001895 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRINGS));
1896 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
1897 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
1898 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001899 return Stream.EmitAbbrev(std::move(Abbv));
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001900}
1901
1902/// Write out a record for MDString.
1903///
1904/// All the metadata strings in a metadata block are emitted in a single
1905/// record. The sizes and strings themselves are shoved into a blob.
Teresa Johnson37687f32016-04-23 04:30:47 +00001906void ModuleBitcodeWriter::writeMetadataStrings(
1907 ArrayRef<const Metadata *> Strings, SmallVectorImpl<uint64_t> &Record) {
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001908 if (Strings.empty())
1909 return;
1910
1911 // Start the record with the number of strings.
1912 Record.push_back(bitc::METADATA_STRINGS);
1913 Record.push_back(Strings.size());
1914
1915 // Emit the sizes of the strings in the blob.
1916 SmallString<256> Blob;
1917 {
1918 BitstreamWriter W(Blob);
1919 for (const Metadata *MD : Strings)
1920 W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
1921 W.FlushToWord();
1922 }
1923
1924 // Add the offset to the strings to the record.
1925 Record.push_back(Blob.size());
1926
1927 // Add the strings to the blob.
1928 for (const Metadata *MD : Strings)
1929 Blob.append(cast<MDString>(MD)->getString());
1930
1931 // Emit the final record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001932 Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001933 Record.clear();
1934}
1935
Mehdi Aminie98f9252016-12-28 22:30:28 +00001936// Generates an enum to use as an index in the Abbrev array of Metadata record.
1937enum MetadataAbbrev : unsigned {
1938#define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
1939#include "llvm/IR/Metadata.def"
1940 LastPlusOne
1941};
1942
Teresa Johnson37687f32016-04-23 04:30:47 +00001943void ModuleBitcodeWriter::writeMetadataRecords(
Mehdi Aminie98f9252016-12-28 22:30:28 +00001944 ArrayRef<const Metadata *> MDs, SmallVectorImpl<uint64_t> &Record,
1945 std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001946 if (MDs.empty())
Duncan P. N. Exon Smith2fcf60e2015-01-12 22:30:34 +00001947 return;
1948
Duncan P. N. Exon Smith6b7b6802015-02-04 21:54:12 +00001949 // Initialize MDNode abbreviations.
1950#define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
1951#include "llvm/IR/Metadata.def"
1952
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001953 for (const Metadata *MD : MDs) {
Mehdi Aminie98f9252016-12-28 22:30:28 +00001954 if (IndexPos)
1955 IndexPos->push_back(Stream.GetCurrentBitNo());
Duncan P. N. Exon Smith73d5aae2015-01-12 22:31:35 +00001956 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
Duncan P. N. Exon Smith79f8d112015-03-17 00:16:35 +00001957 assert(N->isResolved() && "Expected forward references to be resolved");
1958
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001959 switch (N->getMetadataID()) {
1960 default:
1961 llvm_unreachable("Invalid MDNode subclass");
1962#define HANDLE_MDNODE_LEAF(CLASS) \
1963 case Metadata::CLASS##Kind: \
Mehdi Aminie98f9252016-12-28 22:30:28 +00001964 if (MDAbbrevs) \
1965 write##CLASS(cast<CLASS>(N), Record, \
1966 (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
1967 else \
1968 write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
Duncan P. N. Exon Smithdb6bc8b2015-01-20 01:03:09 +00001969 continue;
1970#include "llvm/IR/Metadata.def"
1971 }
Devang Patel8cca7b42009-08-04 05:01:35 +00001972 }
Teresa Johnson37687f32016-04-23 04:30:47 +00001973 writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
Devang Patel8cca7b42009-08-04 05:01:35 +00001974 }
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001975}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001976
Teresa Johnson37687f32016-04-23 04:30:47 +00001977void ModuleBitcodeWriter::writeModuleMetadata() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00001978 if (!VE.hasMDs() && M.named_metadata_empty())
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001979 return;
1980
Mehdi Aminie98f9252016-12-28 22:30:28 +00001981 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
Duncan P. N. Exon Smith80d153f2016-03-27 23:53:30 +00001982 SmallVector<uint64_t, 64> Record;
Mehdi Aminie98f9252016-12-28 22:30:28 +00001983
1984 // Emit all abbrevs upfront, so that the reader can jump in the middle of the
1985 // block and load any metadata.
1986 std::vector<unsigned> MDAbbrevs;
1987
1988 MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
1989 MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
1990 MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
1991 createGenericDINodeAbbrev();
1992
David Blaikie7ad9dc12017-01-04 22:36:33 +00001993 auto Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminie98f9252016-12-28 22:30:28 +00001994 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX_OFFSET));
Mehdi Amini5022bb72016-12-28 23:45:54 +00001995 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1996 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00001997 unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminie98f9252016-12-28 22:30:28 +00001998
David Blaikie7ad9dc12017-01-04 22:36:33 +00001999 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminie98f9252016-12-28 22:30:28 +00002000 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_INDEX));
2001 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2002 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002003 unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminie98f9252016-12-28 22:30:28 +00002004
2005 // Emit MDStrings together upfront.
Teresa Johnson37687f32016-04-23 04:30:47 +00002006 writeMetadataStrings(VE.getMDStrings(), Record);
Mehdi Aminie98f9252016-12-28 22:30:28 +00002007
2008 // We only emit an index for the metadata record if we have more than a given
2009 // (naive) threshold of metadatas, otherwise it is not worth it.
2010 if (VE.getNonMDStrings().size() > IndexThreshold) {
2011 // Write a placeholder value in for the offset of the metadata index,
2012 // which is written after the records, so that it can include
2013 // the offset of each entry. The placeholder offset will be
2014 // updated after all records are emitted.
Mehdi Amini5022bb72016-12-28 23:45:54 +00002015 uint64_t Vals[] = {0, 0};
Mehdi Aminie98f9252016-12-28 22:30:28 +00002016 Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2017 }
2018
2019 // Compute and save the bit offset to the current position, which will be
2020 // patched when we emit the index later. We can simply subtract the 64-bit
2021 // fixed size from the current bit number to get the location to backpatch.
2022 uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2023
2024 // This index will contain the bitpos for each individual record.
2025 std::vector<uint64_t> IndexPos;
2026 IndexPos.reserve(VE.getNonMDStrings().size());
2027
2028 // Write all the records
2029 writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2030
2031 if (VE.getNonMDStrings().size() > IndexThreshold) {
2032 // Now that we have emitted all the records we will emit the index. But
2033 // first
2034 // backpatch the forward reference so that the reader can skip the records
2035 // efficiently.
2036 Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2037 Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2038
2039 // Delta encode the index.
2040 uint64_t PreviousValue = IndexOffsetRecordBitPos;
2041 for (auto &Elt : IndexPos) {
2042 auto EltDelta = Elt - PreviousValue;
2043 PreviousValue = Elt;
2044 Elt = EltDelta;
2045 }
2046 // Emit the index record.
2047 Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2048 IndexPos.clear();
2049 }
2050
2051 // Write the named metadata now.
Teresa Johnson37687f32016-04-23 04:30:47 +00002052 writeNamedMetadata(Record);
Peter Collingbourne21521892016-06-21 23:42:48 +00002053
2054 auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2055 SmallVector<uint64_t, 4> Record;
2056 Record.push_back(VE.getValueID(&GO));
2057 pushGlobalMetadataAttachment(Record, GO);
2058 Stream.EmitRecord(bitc::METADATA_GLOBAL_DECL_ATTACHMENT, Record);
2059 };
2060 for (const Function &F : M)
2061 if (F.isDeclaration() && F.hasMetadata())
2062 AddDeclAttachedMetadata(F);
2063 // FIXME: Only store metadata for declarations here, and move data for global
2064 // variable definitions to a separate block (PR28134).
2065 for (const GlobalVariable &GV : M.globals())
2066 if (GV.hasMetadata())
2067 AddDeclAttachedMetadata(GV);
2068
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002069 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00002070}
2071
Teresa Johnson37687f32016-04-23 04:30:47 +00002072void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
Duncan P. N. Exon Smith93429112016-04-02 15:09:42 +00002073 if (!VE.hasMDs())
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00002074 return;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002075
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002076 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
Duncan P. N. Exon Smith5465f0a2016-03-27 23:38:36 +00002077 SmallVector<uint64_t, 64> Record;
Teresa Johnson37687f32016-04-23 04:30:47 +00002078 writeMetadataStrings(VE.getMDStrings(), Record);
2079 writeMetadataRecords(VE.getNonMDStrings(), Record);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002080 Stream.ExitBlock();
Victor Hernandezb00a6be2010-01-13 19:37:33 +00002081}
2082
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002083void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2084 SmallVectorImpl<uint64_t> &Record, const GlobalObject &GO) {
2085 // [n x [id, mdnode]]
2086 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2087 GO.getAllMetadata(MDs);
2088 for (const auto &I : MDs) {
2089 Record.push_back(I.first);
2090 Record.push_back(VE.getMetadataID(I.second));
2091 }
2092}
2093
2094void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002095 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
Chris Lattner07d09ed2010-04-03 02:17:50 +00002096
Devang Patelaf206b82009-09-18 19:26:43 +00002097 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002098
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002099 if (F.hasMetadata()) {
2100 pushGlobalMetadataAttachment(Record, F);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002101 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00002102 Record.clear();
2103 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002104
Peter Collingbournecceae7f2016-05-31 23:01:54 +00002105 // Write metadata attachments
2106 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2107 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00002108 for (const BasicBlock &BB : F)
2109 for (const Instruction &I : BB) {
Devang Patel6da5dbf2009-10-22 18:55:16 +00002110 MDs.clear();
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00002111 I.getAllMetadataOtherThanDebugLoc(MDs);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002112
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002113 // If no metadata, ignore instruction.
2114 if (MDs.empty()) continue;
2115
Duncan P. N. Exon Smith584af872015-10-13 03:26:19 +00002116 Record.push_back(VE.getInstructionID(&I));
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002117
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002118 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2119 Record.push_back(MDs[i].first);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002120 Record.push_back(VE.getMetadataID(MDs[i].second));
Devang Patelaf206b82009-09-18 19:26:43 +00002121 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002122 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00002123 Record.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00002124 }
2125
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002126 Stream.ExitBlock();
Devang Patelaf206b82009-09-18 19:26:43 +00002127}
2128
Peter Collingbourne21521892016-06-21 23:42:48 +00002129void ModuleBitcodeWriter::writeModuleMetadataKinds() {
Devang Patelaf206b82009-09-18 19:26:43 +00002130 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002131
Devang Patelaf206b82009-09-18 19:26:43 +00002132 // Write metadata kinds
2133 // METADATA_KIND - [n x [id, name]]
Michael Ilseman979dfbb2012-12-03 22:57:47 +00002134 SmallVector<StringRef, 8> Names;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002135 M.getMDKindNames(Names);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002136
Dan Gohman43aa8f02010-07-20 21:42:28 +00002137 if (Names.empty()) return;
Chris Lattnerc9558df2009-12-28 20:10:43 +00002138
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002139 Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002140
Dan Gohman43aa8f02010-07-20 21:42:28 +00002141 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
Chris Lattnerc9558df2009-12-28 20:10:43 +00002142 Record.push_back(MDKindID);
2143 StringRef KName = Names[MDKindID];
2144 Record.append(KName.begin(), KName.end());
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002145
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002146 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
Devang Patelaf206b82009-09-18 19:26:43 +00002147 Record.clear();
2148 }
2149
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002150 Stream.ExitBlock();
Devang Patel8cca7b42009-08-04 05:01:35 +00002151}
2152
Teresa Johnson37687f32016-04-23 04:30:47 +00002153void ModuleBitcodeWriter::writeOperandBundleTags() {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002154 // Write metadata kinds
2155 //
2156 // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2157 //
2158 // OPERAND_BUNDLE_TAG - [strchr x N]
2159
2160 SmallVector<StringRef, 8> Tags;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002161 M.getOperandBundleTags(Tags);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002162
2163 if (Tags.empty())
2164 return;
2165
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002166 Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002167
2168 SmallVector<uint64_t, 64> Record;
2169
2170 for (auto Tag : Tags) {
2171 Record.append(Tag.begin(), Tag.end());
2172
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002173 Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002174 Record.clear();
2175 }
2176
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002177 Stream.ExitBlock();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002178}
2179
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002180void ModuleBitcodeWriter::writeSyncScopeNames() {
2181 SmallVector<StringRef, 8> SSNs;
2182 M.getContext().getSyncScopeNames(SSNs);
2183 if (SSNs.empty())
2184 return;
2185
2186 Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
2187
2188 SmallVector<uint64_t, 64> Record;
2189 for (auto SSN : SSNs) {
2190 Record.append(SSN.begin(), SSN.end());
2191 Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2192 Record.clear();
2193 }
2194
2195 Stream.ExitBlock();
2196}
2197
Jan Wen Voungafaced02012-10-11 20:20:40 +00002198static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
2199 if ((int64_t)V >= 0)
2200 Vals.push_back(V << 1);
2201 else
2202 Vals.push_back((-V << 1) | 1);
2203}
2204
Teresa Johnson37687f32016-04-23 04:30:47 +00002205void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2206 bool isGlobal) {
Devang Patel8cca7b42009-08-04 05:01:35 +00002207 if (FirstVal == LastVal) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002208
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002209 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
Devang Patel8cca7b42009-08-04 05:01:35 +00002210
2211 unsigned AggregateAbbrev = 0;
2212 unsigned String8Abbrev = 0;
2213 unsigned CString7Abbrev = 0;
2214 unsigned CString6Abbrev = 0;
2215 // If this is a constant pool for the module, emit module-specific abbrevs.
2216 if (isGlobal) {
2217 // Abbrev for CST_CODE_AGGREGATE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002218 auto Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002219 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
2220 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2221 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002222 AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002223
2224 // Abbrev for CST_CODE_STRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002225 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002226 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
2227 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2228 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002229 String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002230 // Abbrev for CST_CODE_CSTRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002231 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002232 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002235 CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Devang Patel8cca7b42009-08-04 05:01:35 +00002236 // Abbrev for CST_CODE_CSTRING.
David Blaikie7ad9dc12017-01-04 22:36:33 +00002237 Abbv = std::make_shared<BitCodeAbbrev>();
Devang Patel8cca7b42009-08-04 05:01:35 +00002238 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
2239 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
2240 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00002241 CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002242 }
2243
Devang Patel8cca7b42009-08-04 05:01:35 +00002244 SmallVector<uint64_t, 64> Record;
2245
2246 const ValueEnumerator::ValueList &Vals = VE.getValues();
Craig Topper2617dcc2014-04-15 06:32:26 +00002247 Type *LastTy = nullptr;
Devang Patel8cca7b42009-08-04 05:01:35 +00002248 for (unsigned i = FirstVal; i != LastVal; ++i) {
2249 const Value *V = Vals[i].first;
Chris Lattner52523562007-04-24 00:16:04 +00002250 // If we need to switch types, do so now.
2251 if (V->getType() != LastTy) {
2252 LastTy = V->getType();
2253 Record.push_back(VE.getTypeID(LastTy));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002254 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2255 CONSTANTS_SETTYPE_ABBREV);
Chris Lattner52523562007-04-24 00:16:04 +00002256 Record.clear();
2257 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002258
Chris Lattner52523562007-04-24 00:16:04 +00002259 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
Dale Johannesenfd04c742009-10-13 20:46:56 +00002260 Record.push_back(unsigned(IA->hasSideEffects()) |
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002261 unsigned(IA->isAlignStack()) << 1 |
2262 unsigned(IA->getDialect()&1) << 2);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002263
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002264 // Add the asm string.
2265 const std::string &AsmStr = IA->getAsmString();
2266 Record.push_back(AsmStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002267 Record.append(AsmStr.begin(), AsmStr.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002268
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002269 // Add the constraint string.
2270 const std::string &ConstraintStr = IA->getConstraintString();
2271 Record.push_back(ConstraintStr.size());
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002272 Record.append(ConstraintStr.begin(), ConstraintStr.end());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002273 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002274 Record.clear();
Chris Lattner52523562007-04-24 00:16:04 +00002275 continue;
2276 }
2277 const Constant *C = cast<Constant>(V);
2278 unsigned Code = -1U;
2279 unsigned AbbrevToUse = 0;
2280 if (C->isNullValue()) {
2281 Code = bitc::CST_CODE_NULL;
2282 } else if (isa<UndefValue>(C)) {
2283 Code = bitc::CST_CODE_UNDEF;
2284 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
Bob Wilsone4077362013-09-09 19:14:35 +00002285 if (IV->getBitWidth() <= 64) {
2286 uint64_t V = IV->getSExtValue();
2287 emitSignedInt64(Record, V);
2288 Code = bitc::CST_CODE_INTEGER;
2289 AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2290 } else { // Wide integers, > 64 bits in size.
2291 // We have an arbitrary precision integer value to write whose
2292 // bit width is > 64. However, in canonical unsigned integer
2293 // format it is likely that the high bits are going to be zero.
2294 // So, we only write the number of active words.
2295 unsigned NWords = IV->getValue().getActiveWords();
2296 const uint64_t *RawWords = IV->getValue().getRawData();
2297 for (unsigned i = 0; i != NWords; ++i) {
2298 emitSignedInt64(Record, RawWords[i]);
2299 }
2300 Code = bitc::CST_CODE_WIDE_INTEGER;
2301 }
Chris Lattner52523562007-04-24 00:16:04 +00002302 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2303 Code = bitc::CST_CODE_FLOAT;
Chris Lattner229907c2011-07-18 04:54:35 +00002304 Type *Ty = CFP->getType();
Dan Gohman518cda42011-12-17 00:04:22 +00002305 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002306 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
Chris Lattnerfdd87902009-10-05 05:54:46 +00002307 } else if (Ty->isX86_FP80Ty()) {
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002308 // api needed to prevent premature destruction
Dale Johannesen93eefa02009-03-23 21:16:53 +00002309 // bits are not in the same order as a normal i80 APInt, compensate.
Dale Johannesen54306fe2008-10-09 18:53:47 +00002310 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002311 const uint64_t *p = api.getRawData();
Dale Johannesen93eefa02009-03-23 21:16:53 +00002312 Record.push_back((p[1] << 48) | (p[0] >> 16));
2313 Record.push_back(p[0] & 0xffffLL);
Chris Lattnerfdd87902009-10-05 05:54:46 +00002314 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00002315 APInt api = CFP->getValueAPF().bitcastToAPInt();
Dale Johannesen34aa41c2007-09-26 23:20:33 +00002316 const uint64_t *p = api.getRawData();
Dale Johannesen245dceb2007-09-11 18:32:33 +00002317 Record.push_back(p[0]);
2318 Record.push_back(p[1]);
Dale Johannesenbdad8092007-08-09 22:51:36 +00002319 } else {
Eugene Zelenko975293f2017-09-07 23:28:24 +00002320 assert(0 && "Unknown FP type!");
Chris Lattner52523562007-04-24 00:16:04 +00002321 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002322 } else if (isa<ConstantDataSequential>(C) &&
2323 cast<ConstantDataSequential>(C)->isString()) {
2324 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2325 // Emit constant strings specially.
2326 unsigned NumElts = Str->getNumElements();
2327 // If this is a null-terminated string, use the denser CSTRING encoding.
2328 if (Str->isCString()) {
2329 Code = bitc::CST_CODE_CSTRING;
2330 --NumElts; // Don't encode the null, which isn't allowed by char6.
2331 } else {
2332 Code = bitc::CST_CODE_STRING;
2333 AbbrevToUse = String8Abbrev;
2334 }
2335 bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2336 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2337 for (unsigned i = 0; i != NumElts; ++i) {
2338 unsigned char V = Str->getElementAsInteger(i);
2339 Record.push_back(V);
2340 isCStr7 &= (V & 128) == 0;
2341 if (isCStrChar6)
2342 isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2343 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002344
Chris Lattner372dd1e2012-01-30 00:51:16 +00002345 if (isCStrChar6)
2346 AbbrevToUse = CString6Abbrev;
2347 else if (isCStr7)
2348 AbbrevToUse = CString7Abbrev;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002349 } else if (const ConstantDataSequential *CDS =
Chris Lattner372dd1e2012-01-30 00:51:16 +00002350 dyn_cast<ConstantDataSequential>(C)) {
Chris Lattner5d917072012-01-30 07:36:01 +00002351 Code = bitc::CST_CODE_DATA;
Chris Lattner372dd1e2012-01-30 00:51:16 +00002352 Type *EltTy = CDS->getType()->getElementType();
2353 if (isa<IntegerType>(EltTy)) {
2354 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2355 Record.push_back(CDS->getElementAsInteger(i));
Chris Lattner372dd1e2012-01-30 00:51:16 +00002356 } else {
Justin Bognera43eacb2016-01-06 22:31:32 +00002357 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2358 Record.push_back(
2359 CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002360 }
Duncan P. N. Exon Smith1de3c7e2016-04-05 21:10:45 +00002361 } else if (isa<ConstantAggregate>(C)) {
Chris Lattner52523562007-04-24 00:16:04 +00002362 Code = bitc::CST_CODE_AGGREGATE;
Pete Cooper125ad172015-06-25 20:51:38 +00002363 for (const Value *Op : C->operands())
2364 Record.push_back(VE.getValueID(Op));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002365 AbbrevToUse = AggregateAbbrev;
Chris Lattner52523562007-04-24 00:16:04 +00002366 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002367 switch (CE->getOpcode()) {
2368 default:
2369 if (Instruction::isCast(CE->getOpcode())) {
2370 Code = bitc::CST_CODE_CE_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002371 Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002372 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2373 Record.push_back(VE.getValueID(C->getOperand(0)));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00002374 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002375 } else {
2376 assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2377 Code = bitc::CST_CODE_CE_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002378 Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002379 Record.push_back(VE.getValueID(C->getOperand(0)));
2380 Record.push_back(VE.getValueID(C->getOperand(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002381 uint64_t Flags = getOptimizationFlags(CE);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002382 if (Flags != 0)
2383 Record.push_back(Flags);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002384 }
2385 break;
David Blaikieb9263572015-03-13 21:03:36 +00002386 case Instruction::GetElementPtr: {
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002387 Code = bitc::CST_CODE_CE_GEP;
David Blaikieb9263572015-03-13 21:03:36 +00002388 const auto *GO = cast<GEPOperator>(C);
David Blaikieb9263572015-03-13 21:03:36 +00002389 Record.push_back(VE.getTypeID(GO->getSourceElementType()));
Peter Collingbourned93620b2016-11-10 22:34:55 +00002390 if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2391 Code = bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX;
2392 Record.push_back((*Idx << 1) | GO->isInBounds());
2393 } else if (GO->isInBounds())
2394 Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002395 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2396 Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2397 Record.push_back(VE.getValueID(C->getOperand(i)));
2398 }
2399 break;
David Blaikieb9263572015-03-13 21:03:36 +00002400 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002401 case Instruction::Select:
2402 Code = bitc::CST_CODE_CE_SELECT;
2403 Record.push_back(VE.getValueID(C->getOperand(0)));
2404 Record.push_back(VE.getValueID(C->getOperand(1)));
2405 Record.push_back(VE.getValueID(C->getOperand(2)));
2406 break;
2407 case Instruction::ExtractElement:
2408 Code = bitc::CST_CODE_CE_EXTRACTELT;
2409 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2410 Record.push_back(VE.getValueID(C->getOperand(0)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002411 Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002412 Record.push_back(VE.getValueID(C->getOperand(1)));
2413 break;
2414 case Instruction::InsertElement:
2415 Code = bitc::CST_CODE_CE_INSERTELT;
2416 Record.push_back(VE.getValueID(C->getOperand(0)));
2417 Record.push_back(VE.getValueID(C->getOperand(1)));
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002418 Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002419 Record.push_back(VE.getValueID(C->getOperand(2)));
2420 break;
2421 case Instruction::ShuffleVector:
Nate Begeman94aa38d2009-02-12 21:28:33 +00002422 // If the return type and argument types are the same, this is a
2423 // standard shufflevector instruction. If the types are different,
2424 // then the shuffle is widening or truncating the input vectors, and
2425 // the argument type must also be encoded.
2426 if (C->getType() == C->getOperand(0)->getType()) {
2427 Code = bitc::CST_CODE_CE_SHUFFLEVEC;
2428 } else {
2429 Code = bitc::CST_CODE_CE_SHUFVEC_EX;
2430 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2431 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002432 Record.push_back(VE.getValueID(C->getOperand(0)));
2433 Record.push_back(VE.getValueID(C->getOperand(1)));
2434 Record.push_back(VE.getValueID(C->getOperand(2)));
2435 break;
2436 case Instruction::ICmp:
2437 case Instruction::FCmp:
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002438 Code = bitc::CST_CODE_CE_CMP;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002439 Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2440 Record.push_back(VE.getValueID(C->getOperand(0)));
2441 Record.push_back(VE.getValueID(C->getOperand(1)));
2442 Record.push_back(CE->getPredicate());
2443 break;
2444 }
Chris Lattnerf540d742009-10-28 05:24:40 +00002445 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
Chris Lattnerf540d742009-10-28 05:24:40 +00002446 Code = bitc::CST_CODE_BLOCKADDRESS;
2447 Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2448 Record.push_back(VE.getValueID(BA->getFunction()));
2449 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
Chris Lattner52523562007-04-24 00:16:04 +00002450 } else {
Dan Gohman47dc8fd2010-07-21 21:18:37 +00002451#ifndef NDEBUG
2452 C->dump();
2453#endif
Torok Edwinfbcc6632009-07-14 16:55:14 +00002454 llvm_unreachable("Unknown constant!");
Chris Lattner52523562007-04-24 00:16:04 +00002455 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002456 Stream.EmitRecord(Code, Record, AbbrevToUse);
Chris Lattner52523562007-04-24 00:16:04 +00002457 Record.clear();
2458 }
2459
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002460 Stream.ExitBlock();
Chris Lattner52523562007-04-24 00:16:04 +00002461}
2462
Teresa Johnson37687f32016-04-23 04:30:47 +00002463void ModuleBitcodeWriter::writeModuleConstants() {
Chris Lattner52523562007-04-24 00:16:04 +00002464 const ValueEnumerator::ValueList &Vals = VE.getValues();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002465
Chris Lattner52523562007-04-24 00:16:04 +00002466 // Find the first constant to emit, which is the first non-globalvalue value.
2467 // We know globalvalues have been emitted by WriteModuleInfo.
2468 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2469 if (!isa<GlobalValue>(Vals[i].first)) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002470 writeConstants(i, Vals.size(), true);
Chris Lattner52523562007-04-24 00:16:04 +00002471 return;
2472 }
2473 }
2474}
Chris Lattner215e9cd2007-04-23 20:35:01 +00002475
Teresa Johnson37687f32016-04-23 04:30:47 +00002476/// pushValueAndType - The file has to encode both the value and type id for
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002477/// many values, because we need to know what type to create for forward
2478/// references. However, most operands are not forward references, so this type
2479/// field is not needed.
2480///
2481/// This function adds V's value ID to Vals. If the value ID is higher than the
2482/// instruction ID, then it is a forward reference, and it also includes the
Jan Wen Voungafaced02012-10-11 20:20:40 +00002483/// type ID. The value ID that is written is encoded relative to the InstID.
Teresa Johnson37687f32016-04-23 04:30:47 +00002484bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2485 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002486 unsigned ValID = VE.getValueID(V);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002487 // Make encoding relative to the InstID.
2488 Vals.push_back(InstID - ValID);
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002489 if (ValID >= InstID) {
2490 Vals.push_back(VE.getTypeID(V->getType()));
2491 return true;
2492 }
2493 return false;
2494}
2495
Teresa Johnson37687f32016-04-23 04:30:47 +00002496void ModuleBitcodeWriter::writeOperandBundles(ImmutableCallSite CS,
2497 unsigned InstID) {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002498 SmallVector<unsigned, 64> Record;
2499 LLVMContext &C = CS.getInstruction()->getContext();
2500
2501 for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
Sanjoy Das54c3ca62015-11-07 01:56:04 +00002502 const auto &Bundle = CS.getOperandBundleAt(i);
Sanjoy Dasb9ca6dc2015-11-10 20:13:15 +00002503 Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002504
2505 for (auto &Input : Bundle.Inputs)
Teresa Johnson37687f32016-04-23 04:30:47 +00002506 pushValueAndType(Input, InstID, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002507
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002508 Stream.EmitRecord(bitc::FUNC_CODE_OPERAND_BUNDLE, Record);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002509 Record.clear();
2510 }
2511}
2512
Teresa Johnson37687f32016-04-23 04:30:47 +00002513/// pushValue - Like pushValueAndType, but where the type of the value is
Jan Wen Voungafaced02012-10-11 20:20:40 +00002514/// omitted (perhaps it was already encoded in an earlier operand).
Teresa Johnson37687f32016-04-23 04:30:47 +00002515void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2516 SmallVectorImpl<unsigned> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002517 unsigned ValID = VE.getValueID(V);
2518 Vals.push_back(InstID - ValID);
2519}
2520
Teresa Johnson37687f32016-04-23 04:30:47 +00002521void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2522 SmallVectorImpl<uint64_t> &Vals) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00002523 unsigned ValID = VE.getValueID(V);
2524 int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2525 emitSignedInt64(Vals, diff);
2526}
2527
Chris Lattnere6e364c2007-04-26 05:53:54 +00002528/// WriteInstruction - Emit an instruction to the specified stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00002529void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2530 unsigned InstID,
2531 SmallVectorImpl<unsigned> &Vals) {
Chris Lattnere6e364c2007-04-26 05:53:54 +00002532 unsigned Code = 0;
2533 unsigned AbbrevToUse = 0;
Devang Patelaf206b82009-09-18 19:26:43 +00002534 VE.setInstructionID(&I);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002535 switch (I.getOpcode()) {
2536 default:
2537 if (Instruction::isCast(I.getOpcode())) {
Chris Lattner0a603252007-05-01 02:13:26 +00002538 Code = bitc::FUNC_CODE_INST_CAST;
Teresa Johnson37687f32016-04-23 04:30:47 +00002539 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002540 AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002541 Vals.push_back(VE.getTypeID(I.getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002542 Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
Chris Lattnere6e364c2007-04-26 05:53:54 +00002543 } else {
2544 assert(isa<BinaryOperator>(I) && "Unknown instruction!");
Chris Lattner9f35f912007-05-02 04:26:36 +00002545 Code = bitc::FUNC_CODE_INST_BINOP;
Teresa Johnson37687f32016-04-23 04:30:47 +00002546 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Chris Lattnerc67e6d92007-05-06 02:38:57 +00002547 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
Teresa Johnson37687f32016-04-23 04:30:47 +00002548 pushValue(I.getOperand(1), InstID, Vals);
2549 Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2550 uint64_t Flags = getOptimizationFlags(&I);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002551 if (Flags != 0) {
2552 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2553 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2554 Vals.push_back(Flags);
2555 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002556 }
2557 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002558
David Blaikieb5b5efd2015-02-25 01:08:52 +00002559 case Instruction::GetElementPtr: {
Chris Lattner0a603252007-05-01 02:13:26 +00002560 Code = bitc::FUNC_CODE_INST_GEP;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002561 AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2562 auto &GEPInst = cast<GetElementPtrInst>(I);
2563 Vals.push_back(GEPInst.isInBounds());
2564 Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002565 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002566 pushValueAndType(I.getOperand(i), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002567 break;
David Blaikieb5b5efd2015-02-25 01:08:52 +00002568 }
Dan Gohmanca0256a2008-05-31 19:11:15 +00002569 case Instruction::ExtractValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002570 Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002571 pushValueAndType(I.getOperand(0), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002572 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002573 Vals.append(EVI->idx_begin(), EVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002574 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002575 }
2576 case Instruction::InsertValue: {
Dan Gohman30499842008-05-23 01:55:30 +00002577 Code = bitc::FUNC_CODE_INST_INSERTVAL;
Teresa Johnson37687f32016-04-23 04:30:47 +00002578 pushValueAndType(I.getOperand(0), InstID, Vals);
2579 pushValueAndType(I.getOperand(1), InstID, Vals);
Dan Gohmanca0256a2008-05-31 19:11:15 +00002580 const InsertValueInst *IVI = cast<InsertValueInst>(&I);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002581 Vals.append(IVI->idx_begin(), IVI->idx_end());
Dan Gohman30499842008-05-23 01:55:30 +00002582 break;
Dan Gohmanca0256a2008-05-31 19:11:15 +00002583 }
Chris Lattner0a603252007-05-01 02:13:26 +00002584 case Instruction::Select:
Dan Gohmanc5d28922008-09-16 01:01:33 +00002585 Code = bitc::FUNC_CODE_INST_VSELECT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002586 pushValueAndType(I.getOperand(1), InstID, Vals);
2587 pushValue(I.getOperand(2), InstID, Vals);
2588 pushValueAndType(I.getOperand(0), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002589 break;
2590 case Instruction::ExtractElement:
2591 Code = bitc::FUNC_CODE_INST_EXTRACTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002592 pushValueAndType(I.getOperand(0), InstID, Vals);
2593 pushValueAndType(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002594 break;
2595 case Instruction::InsertElement:
2596 Code = bitc::FUNC_CODE_INST_INSERTELT;
Teresa Johnson37687f32016-04-23 04:30:47 +00002597 pushValueAndType(I.getOperand(0), InstID, Vals);
2598 pushValue(I.getOperand(1), InstID, Vals);
2599 pushValueAndType(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002600 break;
2601 case Instruction::ShuffleVector:
2602 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002603 pushValueAndType(I.getOperand(0), InstID, Vals);
2604 pushValue(I.getOperand(1), InstID, Vals);
2605 pushValue(I.getOperand(2), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002606 break;
2607 case Instruction::ICmp:
James Molloy88eb5352015-07-10 12:52:00 +00002608 case Instruction::FCmp: {
Nick Lewyckya21d3da2009-07-08 03:04:38 +00002609 // compare returning Int1Ty or vector of Int1Ty
2610 Code = bitc::FUNC_CODE_INST_CMP2;
Teresa Johnson37687f32016-04-23 04:30:47 +00002611 pushValueAndType(I.getOperand(0), InstID, Vals);
2612 pushValue(I.getOperand(1), InstID, Vals);
Chris Lattner0a603252007-05-01 02:13:26 +00002613 Vals.push_back(cast<CmpInst>(I).getPredicate());
Teresa Johnson37687f32016-04-23 04:30:47 +00002614 uint64_t Flags = getOptimizationFlags(&I);
James Molloy88eb5352015-07-10 12:52:00 +00002615 if (Flags != 0)
2616 Vals.push_back(Flags);
Chris Lattner0a603252007-05-01 02:13:26 +00002617 break;
James Molloy88eb5352015-07-10 12:52:00 +00002618 }
Chris Lattner0a603252007-05-01 02:13:26 +00002619
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002620 case Instruction::Ret:
Devang Patelbbfd8742008-02-26 01:29:32 +00002621 {
2622 Code = bitc::FUNC_CODE_INST_RET;
2623 unsigned NumOperands = I.getNumOperands();
Devang Patelbbfd8742008-02-26 01:29:32 +00002624 if (NumOperands == 0)
2625 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2626 else if (NumOperands == 1) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002627 if (!pushValueAndType(I.getOperand(0), InstID, Vals))
Devang Patelbbfd8742008-02-26 01:29:32 +00002628 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2629 } else {
2630 for (unsigned i = 0, e = NumOperands; i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002631 pushValueAndType(I.getOperand(i), InstID, Vals);
Devang Patelbbfd8742008-02-26 01:29:32 +00002632 }
2633 }
Chris Lattner0a603252007-05-01 02:13:26 +00002634 break;
2635 case Instruction::Br:
Gabor Greif1933b002009-01-30 18:27:21 +00002636 {
2637 Code = bitc::FUNC_CODE_INST_BR;
David Blaikieb78e9e52013-02-11 01:16:51 +00002638 const BranchInst &II = cast<BranchInst>(I);
Gabor Greif1933b002009-01-30 18:27:21 +00002639 Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2640 if (II.isConditional()) {
2641 Vals.push_back(VE.getValueID(II.getSuccessor(1)));
Teresa Johnson37687f32016-04-23 04:30:47 +00002642 pushValue(II.getCondition(), InstID, Vals);
Gabor Greif1933b002009-01-30 18:27:21 +00002643 }
Chris Lattner0a603252007-05-01 02:13:26 +00002644 }
2645 break;
2646 case Instruction::Switch:
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002647 {
2648 Code = bitc::FUNC_CODE_INST_SWITCH;
David Blaikieb78e9e52013-02-11 01:16:51 +00002649 const SwitchInst &SI = cast<SwitchInst>(I);
Bob Wilsone4077362013-09-09 19:14:35 +00002650 Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002651 pushValue(SI.getCondition(), InstID, Vals);
Bob Wilsone4077362013-09-09 19:14:35 +00002652 Vals.push_back(VE.getValueID(SI.getDefaultDest()));
Chandler Carruth927d8e62017-04-12 07:27:28 +00002653 for (auto Case : SI.cases()) {
Sanjay Patel225d65f2015-11-13 16:21:23 +00002654 Vals.push_back(VE.getValueID(Case.getCaseValue()));
2655 Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00002656 }
2657 }
Chris Lattner0a603252007-05-01 02:13:26 +00002658 break;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00002659 case Instruction::IndirectBr:
2660 Code = bitc::FUNC_CODE_INST_INDIRECTBR;
Chris Lattner3ed871f2009-10-27 19:13:16 +00002661 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Jan Wen Voungafaced02012-10-11 20:20:40 +00002662 // Encode the address operand as relative, but not the basic blocks.
Teresa Johnson37687f32016-04-23 04:30:47 +00002663 pushValue(I.getOperand(0), InstID, Vals);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002664 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
Chris Lattner3ed871f2009-10-27 19:13:16 +00002665 Vals.push_back(VE.getValueID(I.getOperand(i)));
2666 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002667
Chris Lattnerb811e952007-05-01 07:03:37 +00002668 case Instruction::Invoke: {
Gabor Greif4b79e472009-01-16 18:40:27 +00002669 const InvokeInst *II = cast<InvokeInst>(&I);
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002670 const Value *Callee = II->getCalledValue();
2671 FunctionType *FTy = II->getFunctionType();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002672
2673 if (II->hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002674 writeOperandBundles(II, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002675
Chris Lattner0a603252007-05-01 02:13:26 +00002676 Code = bitc::FUNC_CODE_INST_INVOKE;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002677
Reid Klecknerb4a2d182017-04-24 20:38:30 +00002678 Vals.push_back(VE.getAttributeListID(II->getAttributes()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002679 Vals.push_back(II->getCallingConv() | 1 << 13);
Gabor Greif6ecd6f42009-01-07 22:39:29 +00002680 Vals.push_back(VE.getValueID(II->getNormalDest()));
2681 Vals.push_back(VE.getValueID(II->getUnwindDest()));
David Blaikie5ea1f7b2015-04-24 18:06:06 +00002682 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002683 pushValueAndType(Callee, InstID, Vals);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002684
Chris Lattner0a603252007-05-01 02:13:26 +00002685 // Emit value #'s for the fixed parameters.
Chris Lattner0a603252007-05-01 02:13:26 +00002686 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002687 pushValue(I.getOperand(i), InstID, Vals); // fixed param.
Chris Lattner0a603252007-05-01 02:13:26 +00002688
2689 // Emit type/value pairs for varargs params.
2690 if (FTy->isVarArg()) {
Mehdi Amini7cf63822016-09-19 21:27:04 +00002691 for (unsigned i = FTy->getNumParams(), e = II->getNumArgOperands();
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002692 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002693 pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
Chris Lattner0a603252007-05-01 02:13:26 +00002694 }
2695 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002696 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00002697 case Instruction::Resume:
2698 Code = bitc::FUNC_CODE_INST_RESUME;
Teresa Johnson37687f32016-04-23 04:30:47 +00002699 pushValueAndType(I.getOperand(0), InstID, Vals);
Bill Wendlingf891bf82011-07-31 06:30:59 +00002700 break;
David Majnemer654e1302015-07-31 17:58:14 +00002701 case Instruction::CleanupRet: {
2702 Code = bitc::FUNC_CODE_INST_CLEANUPRET;
2703 const auto &CRI = cast<CleanupReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002704 pushValue(CRI.getCleanupPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002705 if (CRI.hasUnwindDest())
2706 Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2707 break;
2708 }
2709 case Instruction::CatchRet: {
2710 Code = bitc::FUNC_CODE_INST_CATCHRET;
2711 const auto &CRI = cast<CatchReturnInst>(I);
Teresa Johnson37687f32016-04-23 04:30:47 +00002712 pushValue(CRI.getCatchPad(), InstID, Vals);
David Majnemer654e1302015-07-31 17:58:14 +00002713 Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2714 break;
2715 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00002716 case Instruction::CleanupPad:
David Majnemer654e1302015-07-31 17:58:14 +00002717 case Instruction::CatchPad: {
David Majnemer8a1c45d2015-12-12 05:38:55 +00002718 const auto &FuncletPad = cast<FuncletPadInst>(I);
2719 Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2720 : bitc::FUNC_CODE_INST_CLEANUPPAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002721 pushValue(FuncletPad.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002722
2723 unsigned NumArgOperands = FuncletPad.getNumArgOperands();
David Majnemer654e1302015-07-31 17:58:14 +00002724 Vals.push_back(NumArgOperands);
2725 for (unsigned Op = 0; Op != NumArgOperands; ++Op)
Teresa Johnson37687f32016-04-23 04:30:47 +00002726 pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002727 break;
2728 }
2729 case Instruction::CatchSwitch: {
2730 Code = bitc::FUNC_CODE_INST_CATCHSWITCH;
2731 const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2732
Teresa Johnson37687f32016-04-23 04:30:47 +00002733 pushValue(CatchSwitch.getParentPad(), InstID, Vals);
David Majnemer8a1c45d2015-12-12 05:38:55 +00002734
2735 unsigned NumHandlers = CatchSwitch.getNumHandlers();
2736 Vals.push_back(NumHandlers);
2737 for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2738 Vals.push_back(VE.getValueID(CatchPadBB));
2739
2740 if (CatchSwitch.hasUnwindDest())
2741 Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
David Majnemer654e1302015-07-31 17:58:14 +00002742 break;
2743 }
Chris Lattnere6e364c2007-04-26 05:53:54 +00002744 case Instruction::Unreachable:
2745 Code = bitc::FUNC_CODE_INST_UNREACHABLE;
Chris Lattnercc6d4c92007-05-06 01:28:01 +00002746 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002747 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002748
Jay Foad372ad642011-06-20 14:18:48 +00002749 case Instruction::PHI: {
2750 const PHINode &PN = cast<PHINode>(I);
Chris Lattner0a603252007-05-01 02:13:26 +00002751 Code = bitc::FUNC_CODE_INST_PHI;
Jan Wen Voungafaced02012-10-11 20:20:40 +00002752 // With the newer instruction encoding, forward references could give
2753 // negative valued IDs. This is most common for PHIs, so we use
2754 // signed VBRs.
2755 SmallVector<uint64_t, 128> Vals64;
2756 Vals64.push_back(VE.getTypeID(PN.getType()));
Jay Foad372ad642011-06-20 14:18:48 +00002757 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002758 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002759 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
Jay Foad372ad642011-06-20 14:18:48 +00002760 }
Jan Wen Voungafaced02012-10-11 20:20:40 +00002761 // Emit a Vals64 vector and exit.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002762 Stream.EmitRecord(Code, Vals64, AbbrevToUse);
Jan Wen Voungafaced02012-10-11 20:20:40 +00002763 Vals64.clear();
2764 return;
Jay Foad372ad642011-06-20 14:18:48 +00002765 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002766
Bill Wendlingfae14752011-08-12 20:24:12 +00002767 case Instruction::LandingPad: {
2768 const LandingPadInst &LP = cast<LandingPadInst>(I);
2769 Code = bitc::FUNC_CODE_INST_LANDINGPAD;
2770 Vals.push_back(VE.getTypeID(LP.getType()));
Bill Wendlingfae14752011-08-12 20:24:12 +00002771 Vals.push_back(LP.isCleanup());
2772 Vals.push_back(LP.getNumClauses());
2773 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
2774 if (LP.isCatch(I))
2775 Vals.push_back(LandingPadInst::Catch);
2776 else
2777 Vals.push_back(LandingPadInst::Filter);
Teresa Johnson37687f32016-04-23 04:30:47 +00002778 pushValueAndType(LP.getClause(I), InstID, Vals);
Bill Wendlingfae14752011-08-12 20:24:12 +00002779 }
2780 break;
2781 }
2782
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002783 case Instruction::Alloca: {
Chris Lattner0a603252007-05-01 02:13:26 +00002784 Code = bitc::FUNC_CODE_INST_ALLOCA;
David Blaikiebdb49102015-04-28 16:51:01 +00002785 const AllocaInst &AI = cast<AllocaInst>(I);
2786 Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
Dan Gohman9da5bb02010-05-28 01:38:28 +00002787 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002788 Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002789 unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
2790 assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
2791 "not enough bits for maximum alignment");
2792 assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
2793 AlignRecord |= AI.isUsedWithInAlloca() << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00002794 AlignRecord |= 1 << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00002795 AlignRecord |= AI.isSwiftError() << 7;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002796 Vals.push_back(AlignRecord);
Chris Lattner0a603252007-05-01 02:13:26 +00002797 break;
Reid Kleckner56b56ea2014-07-16 01:34:27 +00002798 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002799
Chris Lattner0a603252007-05-01 02:13:26 +00002800 case Instruction::Load:
Eli Friedman59b66882011-08-09 23:02:53 +00002801 if (cast<LoadInst>(I).isAtomic()) {
2802 Code = bitc::FUNC_CODE_INST_LOADATOMIC;
Teresa Johnson37687f32016-04-23 04:30:47 +00002803 pushValueAndType(I.getOperand(0), InstID, Vals);
Eli Friedman59b66882011-08-09 23:02:53 +00002804 } else {
2805 Code = bitc::FUNC_CODE_INST_LOAD;
Teresa Johnson37687f32016-04-23 04:30:47 +00002806 if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
Eli Friedman59b66882011-08-09 23:02:53 +00002807 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
2808 }
David Blaikie85035652015-02-25 01:07:20 +00002809 Vals.push_back(VE.getTypeID(I.getType()));
Chris Lattner0a603252007-05-01 02:13:26 +00002810 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
2811 Vals.push_back(cast<LoadInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002812 if (cast<LoadInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002813 Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002814 Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
Eli Friedman59b66882011-08-09 23:02:53 +00002815 }
Chris Lattner0a603252007-05-01 02:13:26 +00002816 break;
2817 case Instruction::Store:
Eli Friedman59b66882011-08-09 23:02:53 +00002818 if (cast<StoreInst>(I).isAtomic())
2819 Code = bitc::FUNC_CODE_INST_STOREATOMIC;
2820 else
2821 Code = bitc::FUNC_CODE_INST_STORE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002822 pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
2823 pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
Chris Lattner0a603252007-05-01 02:13:26 +00002824 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
2825 Vals.push_back(cast<StoreInst>(I).isVolatile());
Eli Friedman59b66882011-08-09 23:02:53 +00002826 if (cast<StoreInst>(I).isAtomic()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00002827 Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002828 Vals.push_back(
2829 getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
Eli Friedman59b66882011-08-09 23:02:53 +00002830 }
Chris Lattner0a603252007-05-01 02:13:26 +00002831 break;
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002832 case Instruction::AtomicCmpXchg:
2833 Code = bitc::FUNC_CODE_INST_CMPXCHG;
Teresa Johnson37687f32016-04-23 04:30:47 +00002834 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2835 pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
2836 pushValue(I.getOperand(2), InstID, Vals); // newval.
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002837 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002838 Vals.push_back(
2839 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
2840 Vals.push_back(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002841 getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
Teresa Johnson37687f32016-04-23 04:30:47 +00002842 Vals.push_back(
2843 getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
Tim Northover420a2162014-06-13 14:24:07 +00002844 Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002845 break;
2846 case Instruction::AtomicRMW:
2847 Code = bitc::FUNC_CODE_INST_ATOMICRMW;
Teresa Johnson37687f32016-04-23 04:30:47 +00002848 pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
2849 pushValue(I.getOperand(1), InstID, Vals); // val.
2850 Vals.push_back(
2851 getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002852 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
Teresa Johnson37687f32016-04-23 04:30:47 +00002853 Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
2854 Vals.push_back(
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002855 getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
Eli Friedmanc9a551e2011-07-28 21:48:00 +00002856 break;
Eli Friedmanfee02c62011-07-25 23:16:38 +00002857 case Instruction::Fence:
2858 Code = bitc::FUNC_CODE_INST_FENCE;
Teresa Johnson37687f32016-04-23 04:30:47 +00002859 Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002860 Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
Eli Friedmanfee02c62011-07-25 23:16:38 +00002861 break;
Chris Lattner0a603252007-05-01 02:13:26 +00002862 case Instruction::Call: {
Gabor Greife9afee22010-06-26 09:35:09 +00002863 const CallInst &CI = cast<CallInst>(I);
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002864 FunctionType *FTy = CI.getFunctionType();
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002865
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002866 if (CI.hasOperandBundles())
Teresa Johnson37687f32016-04-23 04:30:47 +00002867 writeOperandBundles(&CI, InstID);
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00002868
Chris Lattnerc44070802011-06-17 18:17:37 +00002869 Code = bitc::FUNC_CODE_INST_CALL;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002870
Reid Klecknerb4a2d182017-04-24 20:38:30 +00002871 Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002872
Teresa Johnson37687f32016-04-23 04:30:47 +00002873 unsigned Flags = getOptimizationFlags(&I);
Akira Hatanaka97cb3972015-11-07 02:48:49 +00002874 Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
2875 unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
2876 unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
2877 1 << bitc::CALL_EXPLICIT_TYPE |
Sanjay Patelfa54ace2015-12-14 21:59:03 +00002878 unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
2879 unsigned(Flags != 0) << bitc::CALL_FMF);
2880 if (Flags != 0)
2881 Vals.push_back(Flags);
2882
David Blaikiedbe6e0f2015-04-17 06:40:14 +00002883 Vals.push_back(VE.getTypeID(FTy));
Teresa Johnson37687f32016-04-23 04:30:47 +00002884 pushValueAndType(CI.getCalledValue(), InstID, Vals); // Callee
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002885
Chris Lattner0a603252007-05-01 02:13:26 +00002886 // Emit value #'s for the fixed parameters.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002887 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
2888 // Check for labels (can happen with asm labels).
2889 if (FTy->getParamType(i)->isLabelTy())
2890 Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
2891 else
Teresa Johnson37687f32016-04-23 04:30:47 +00002892 pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002893 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002894
Chris Lattnerb811e952007-05-01 07:03:37 +00002895 // Emit type/value pairs for varargs params.
2896 if (FTy->isVarArg()) {
Gabor Greife9afee22010-06-26 09:35:09 +00002897 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
Chris Lattnerdf1233d2007-05-06 00:00:00 +00002898 i != e; ++i)
Teresa Johnson37687f32016-04-23 04:30:47 +00002899 pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
Chris Lattner0a603252007-05-01 02:13:26 +00002900 }
2901 break;
Chris Lattnerb811e952007-05-01 07:03:37 +00002902 }
Chris Lattner0a603252007-05-01 02:13:26 +00002903 case Instruction::VAArg:
2904 Code = bitc::FUNC_CODE_INST_VAARG;
2905 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
Teresa Johnson37687f32016-04-23 04:30:47 +00002906 pushValue(I.getOperand(0), InstID, Vals); // valist.
Chris Lattner0a603252007-05-01 02:13:26 +00002907 Vals.push_back(VE.getTypeID(I.getType())); // restype.
2908 break;
Chris Lattnere6e364c2007-04-26 05:53:54 +00002909 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002910
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002911 Stream.EmitRecord(Code, Vals, AbbrevToUse);
Chris Lattnere6e364c2007-04-26 05:53:54 +00002912 Vals.clear();
2913}
2914
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002915/// Write a GlobalValue VST to the module. The purpose of this data structure is
2916/// to allow clients to efficiently find the function body.
2917void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
2918 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
2919 // Get the offset of the VST we are writing, and backpatch it into
2920 // the VST forward declaration record.
2921 uint64_t VSTOffset = Stream.GetCurrentBitNo();
2922 // The BitcodeStartBit was the stream offset of the identification block.
2923 VSTOffset -= bitcodeStartBit();
2924 assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
2925 // Note that we add 1 here because the offset is relative to one word
2926 // before the start of the identification block, which was historically
2927 // always the start of the regular bitcode header.
2928 Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002929
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002930 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
Chris Lattner2eae59f2007-05-04 20:34:50 +00002931
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002932 auto Abbv = std::make_shared<BitCodeAbbrev>();
2933 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_FNENTRY));
2934 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
2935 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
2936 unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnsonff642b92015-09-17 20:12:00 +00002937
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002938 for (const Function &F : M) {
2939 uint64_t Record[2];
Teresa Johnsonff642b92015-09-17 20:12:00 +00002940
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002941 if (F.isDeclaration())
2942 continue;
Teresa Johnsoncd21a642016-07-17 14:47:01 +00002943
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002944 Record[0] = VE.getValueID(&F);
2945
2946 // Save the word offset of the function (from the start of the
2947 // actual bitcode written to the stream).
2948 uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
2949 assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
2950 // Note that we add 1 here because the offset is relative to one word
2951 // before the start of the identification block, which was historically
2952 // always the start of the regular bitcode header.
2953 Record[1] = BitcodeIndex / 32 + 1;
2954
2955 Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
Teresa Johnsonff642b92015-09-17 20:12:00 +00002956 }
2957
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002958 Stream.ExitBlock();
2959}
2960
2961/// Emit names for arguments, instructions and basic blocks in a function.
2962void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
2963 const ValueSymbolTable &VST) {
2964 if (VST.empty())
2965 return;
2966
2967 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
2968
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002969 // FIXME: Set up the abbrev, we know how many values there are!
2970 // FIXME: We know if the type names can use 7-bit ascii.
Teresa Johnsoncd21a642016-07-17 14:47:01 +00002971 SmallVector<uint64_t, 64> NameVals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002972
Yaron Keren001e2e42015-08-10 07:04:29 +00002973 for (const ValueName &Name : VST) {
Chris Lattner4d925982007-05-04 20:52:02 +00002974 // Figure out the encoding to use for the name.
David Blaikieb6b42e02017-06-02 17:24:26 +00002975 StringEncoding Bits = getStringEncoding(Name.getKey());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002976
Chris Lattnera0987962007-05-04 21:31:13 +00002977 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
Teresa Johnsonff642b92015-09-17 20:12:00 +00002978 NameVals.push_back(VE.getValueID(Name.getValue()));
2979
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002980 // VST_CODE_ENTRY: [valueid, namechar x N]
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002981 // VST_CODE_BBENTRY: [bbid, namechar x N]
Chris Lattner6be58c62007-05-03 22:18:21 +00002982 unsigned Code;
Yaron Keren001e2e42015-08-10 07:04:29 +00002983 if (isa<BasicBlock>(Name.getValue())) {
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002984 Code = bitc::VST_CODE_BBENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002985 if (Bits == SE_Char6)
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002986 AbbrevToUse = VST_BBENTRY_6_ABBREV;
Chris Lattner6be58c62007-05-03 22:18:21 +00002987 } else {
2988 Code = bitc::VST_CODE_ENTRY;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002989 if (Bits == SE_Char6)
Chris Lattnere760d6f2007-05-05 01:26:50 +00002990 AbbrevToUse = VST_ENTRY_6_ABBREV;
Teresa Johnsonc01e4cb2015-09-17 14:37:35 +00002991 else if (Bits == SE_Fixed7)
Chris Lattnere760d6f2007-05-05 01:26:50 +00002992 AbbrevToUse = VST_ENTRY_7_ABBREV;
Chris Lattner6be58c62007-05-03 22:18:21 +00002993 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002994
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002995 for (const auto P : Name.getKey())
2996 NameVals.push_back((unsigned char)P);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002997
Chris Lattnerfb6f9402007-05-01 02:14:57 +00002998 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00002999 Stream.EmitRecord(Code, NameVals, AbbrevToUse);
Chris Lattnerfb6f9402007-05-01 02:14:57 +00003000 NameVals.clear();
3001 }
Chris Lattnerfb6f9402007-05-01 02:14:57 +00003002
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003003 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003004}
3005
Teresa Johnson37687f32016-04-23 04:30:47 +00003006void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003007 assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3008 unsigned Code;
3009 if (isa<BasicBlock>(Order.V))
3010 Code = bitc::USELIST_CODE_BB;
3011 else
3012 Code = bitc::USELIST_CODE_DEFAULT;
3013
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00003014 SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003015 Record.push_back(VE.getValueID(Order.V));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003016 Stream.EmitRecord(Code, Record);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003017}
3018
Teresa Johnson37687f32016-04-23 04:30:47 +00003019void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00003020 assert(VE.shouldPreserveUseListOrder() &&
3021 "Expected to be preserving use-list order");
3022
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003023 auto hasMore = [&]() {
3024 return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3025 };
3026 if (!hasMore())
3027 // Nothing to do.
3028 return;
3029
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003030 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003031 while (hasMore()) {
Teresa Johnson37687f32016-04-23 04:30:47 +00003032 writeUseList(std::move(VE.UseListOrders.back()));
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003033 VE.UseListOrders.pop_back();
3034 }
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003035 Stream.ExitBlock();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003036}
3037
Teresa Johnson403a7872015-10-04 14:33:43 +00003038/// Emit a function body to the module stream.
Teresa Johnson37687f32016-04-23 04:30:47 +00003039void ModuleBitcodeWriter::writeFunction(
3040 const Function &F,
3041 DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00003042 // Save the bitcode index of the start of this function block for recording
3043 // in the VST.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003044 FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003045
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003046 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
Chad Rosier6a11b642011-06-03 17:02:19 +00003047 VE.incorporateFunction(F);
Chris Lattnere6e364c2007-04-26 05:53:54 +00003048
3049 SmallVector<unsigned, 64> Vals;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003050
Chris Lattnere6e364c2007-04-26 05:53:54 +00003051 // Emit the number of basic blocks, so the reader can create them ahead of
3052 // time.
3053 Vals.push_back(VE.getBasicBlocks().size());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003054 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
Chris Lattnere6e364c2007-04-26 05:53:54 +00003055 Vals.clear();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003056
Chris Lattnere6e364c2007-04-26 05:53:54 +00003057 // If there are function-local constants, emit them now.
3058 unsigned CstStart, CstEnd;
3059 VE.getFunctionConstantRange(CstStart, CstEnd);
Teresa Johnson37687f32016-04-23 04:30:47 +00003060 writeConstants(CstStart, CstEnd, false);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003061
Victor Hernandez6c730de2010-01-14 01:50:08 +00003062 // If there is function-local metadata, emit it now.
Teresa Johnson37687f32016-04-23 04:30:47 +00003063 writeFunctionMetadata(F);
Victor Hernandez6c730de2010-01-14 01:50:08 +00003064
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003065 // Keep a running idea of what the instruction ID is.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003066 unsigned InstID = CstEnd;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003067
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003068 bool NeedsMetadataAttachment = F.hasMetadata();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003069
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003070 DILocation *LastDL = nullptr;
Chris Lattnere6e364c2007-04-26 05:53:54 +00003071 // Finally, emit all the instructions, in order.
Nick Lewycky4d43d3c2008-04-25 16:53:59 +00003072 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003073 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
3074 I != E; ++I) {
Teresa Johnson37687f32016-04-23 04:30:47 +00003075 writeInstruction(*I, InstID, Vals);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003076
Chris Lattner2f2aa2b2009-12-28 23:41:32 +00003077 if (!I->getType()->isVoidTy())
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003078 ++InstID;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003079
Chris Lattner07d09ed2010-04-03 02:17:50 +00003080 // If the instruction has metadata, write a metadata attachment later.
3081 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003082
Chris Lattner07d09ed2010-04-03 02:17:50 +00003083 // If the instruction has a debug location, emit it.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00003084 DILocation *DL = I->getDebugLoc();
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00003085 if (!DL)
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003086 continue;
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003087
3088 if (DL == LastDL) {
Chris Lattner07d09ed2010-04-03 02:17:50 +00003089 // Just repeat the same debug loc as last time.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003090 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003091 continue;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003092 }
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003093
Duncan P. N. Exon Smithab659fb32015-03-30 19:40:05 +00003094 Vals.push_back(DL->getLine());
3095 Vals.push_back(DL->getColumn());
3096 Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3097 Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
Calixte Denizeteb7f6022018-09-20 08:53:06 +00003098 Vals.push_back(DL->isImplicitCode());
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003099 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
Duncan P. N. Exon Smith1facf7a2015-03-30 18:29:18 +00003100 Vals.clear();
Duncan P. N. Exon Smith538ef562015-05-06 22:51:12 +00003101
3102 LastDL = DL;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003103 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003104
Chris Lattnerfb6f9402007-05-01 02:14:57 +00003105 // Emit names for all the instructions etc.
Mehdi Aminia53d49e2016-09-17 06:00:02 +00003106 if (auto *Symtab = F.getValueSymbolTable())
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003107 writeFunctionLevelValueSymbolTable(*Symtab);
Devang Patelaf206b82009-09-18 19:26:43 +00003108
Chris Lattner07d09ed2010-04-03 02:17:50 +00003109 if (NeedsMetadataAttachment)
Peter Collingbournecceae7f2016-05-31 23:01:54 +00003110 writeFunctionMetadataAttachment(F);
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00003111 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00003112 writeUseListBlock(&F);
Chad Rosier6a11b642011-06-03 17:02:19 +00003113 VE.purgeFunction();
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003114 Stream.ExitBlock();
Chris Lattner831d4202007-04-26 03:27:58 +00003115}
3116
Chris Lattner702658c2007-05-04 18:26:27 +00003117// Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00003118void ModuleBitcodeWriter::writeBlockInfo() {
Chris Lattner702658c2007-05-04 18:26:27 +00003119 // We only want to emit block info records for blocks that have multiple
Jan Wen Voungafaced02012-10-11 20:20:40 +00003120 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
Jan Wen Voung8c9e9412012-10-11 21:45:16 +00003121 // Other blocks can define their abbrevs inline.
Peter Collingbourned3a6c702016-11-01 01:18:57 +00003122 Stream.EnterBlockInfoBlock();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003123
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003124 { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003125 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00003126 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3127 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3128 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3129 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003130 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003131 VST_ENTRY_8_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003132 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00003133 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003134
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003135 { // 7-bit fixed width VST_CODE_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003136 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00003137 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3138 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3139 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3140 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003141 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003142 VST_ENTRY_7_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003143 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00003144 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003145 { // 6-bit char6 VST_CODE_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003146 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnere760d6f2007-05-05 01:26:50 +00003147 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
3148 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3149 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3150 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003151 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003152 VST_ENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003153 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnere760d6f2007-05-05 01:26:50 +00003154 }
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00003155 { // 6-bit char6 VST_CODE_BBENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003156 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattner982ec1e2007-05-05 00:17:00 +00003157 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
3158 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3159 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
Chris Lattnere760d6f2007-05-05 01:26:50 +00003160 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003161 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003162 VST_BBENTRY_6_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003163 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattner982ec1e2007-05-05 00:17:00 +00003164 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00003165
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003166 { // SETTYPE abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003167 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003168 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
3169 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
David Blaikie7b028102015-02-25 00:51:52 +00003170 VE.computeBitsRequiredForTypeIndicies()));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003171 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003172 CONSTANTS_SETTYPE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003173 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003174 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003175
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003176 { // INTEGER abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003177 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003178 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
3179 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003180 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003181 CONSTANTS_INTEGER_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003182 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003183 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003184
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003185 { // CE_CAST abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003186 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003187 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
3188 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3189 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
David Blaikie7b028102015-02-25 00:51:52 +00003190 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003191 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3192
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003193 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003194 CONSTANTS_CE_CAST_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003195 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003196 }
3197 { // NULL abbrev for CONSTANTS_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003198 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003199 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003200 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003201 CONSTANTS_NULL_Abbrev)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003202 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003203 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003204
Chris Lattnerb80751d2007-05-05 07:44:49 +00003205 // FIXME: This should only use space for first class types!
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003206
Chris Lattnerb80751d2007-05-05 07:44:49 +00003207 { // INST_LOAD abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003208 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerb80751d2007-05-05 07:44:49 +00003209 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
Chris Lattnerb80751d2007-05-05 07:44:49 +00003210 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
David Blaikie85035652015-02-25 01:07:20 +00003211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3212 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerb80751d2007-05-05 07:44:49 +00003213 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3214 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003215 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003216 FUNCTION_INST_LOAD_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003217 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerb80751d2007-05-05 07:44:49 +00003218 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003219 { // INST_BINOP abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003220 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003221 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3222 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3223 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3224 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003225 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003226 FUNCTION_INST_BINOP_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003227 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003228 }
Dan Gohman0ebd6962009-07-20 21:19:07 +00003229 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003230 auto Abbv = std::make_shared<BitCodeAbbrev>();
Dan Gohman0ebd6962009-07-20 21:19:07 +00003231 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
3232 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3233 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Steven Wu545d34a2018-02-19 19:22:28 +00003235 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003236 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003237 FUNCTION_INST_BINOP_FLAGS_ABBREV)
Dan Gohman0ebd6962009-07-20 21:19:07 +00003238 llvm_unreachable("Unexpected abbrev ordering!");
3239 }
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003240 { // INST_CAST abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003241 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003242 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
3243 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
David Blaikie7b028102015-02-25 00:51:52 +00003245 VE.computeBitsRequiredForTypeIndicies()));
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003246 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003247 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003248 FUNCTION_INST_CAST_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003249 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnerc67e6d92007-05-06 02:38:57 +00003250 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003251
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003252 { // INST_RET abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003253 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003254 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003255 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003256 FUNCTION_INST_RET_VOID_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003257 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003258 }
3259 { // INST_RET abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003260 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003261 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
3262 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003263 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003264 FUNCTION_INST_RET_VAL_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003265 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003266 }
3267 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003268 auto Abbv = std::make_shared<BitCodeAbbrev>();
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003269 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003270 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
Teresa Johnson37687f32016-04-23 04:30:47 +00003271 FUNCTION_INST_UNREACHABLE_ABBREV)
Torok Edwinfbcc6632009-07-14 16:55:14 +00003272 llvm_unreachable("Unexpected abbrev ordering!");
Chris Lattnercc6d4c92007-05-06 01:28:01 +00003273 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00003274 {
David Blaikie7ad9dc12017-01-04 22:36:33 +00003275 auto Abbv = std::make_shared<BitCodeAbbrev>();
David Blaikieb5b5efd2015-02-25 01:08:52 +00003276 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_GEP));
3277 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3278 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3279 Log2_32_Ceil(VE.getTypes().size() + 1)));
3280 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3281 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003282 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
David Blaikieb5b5efd2015-02-25 01:08:52 +00003283 FUNCTION_INST_GEP_ABBREV)
3284 llvm_unreachable("Unexpected abbrev ordering!");
3285 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003286
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003287 Stream.ExitBlock();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003288}
3289
Teresa Johnson403a7872015-10-04 14:33:43 +00003290/// Write the module path strings, currently only used when generating
3291/// a combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003292void IndexBitcodeWriter::writeModStrings() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003293 Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
Teresa Johnson403a7872015-10-04 14:33:43 +00003294
3295 // TODO: See which abbrev sizes we actually need to emit
3296
3297 // 8-bit fixed-width MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003298 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003299 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3300 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3301 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3302 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003303 unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003304
3305 // 7-bit fixed width MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003306 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003307 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3308 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3309 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3310 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003311 unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003312
3313 // 6-bit char6 MST_ENTRY strings.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003314 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson403a7872015-10-04 14:33:43 +00003315 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_ENTRY));
3316 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3317 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3318 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003319 unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003320
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003321 // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003322 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003323 Abbv->Add(BitCodeAbbrevOp(bitc::MST_CODE_HASH));
3324 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3325 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3326 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3327 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3328 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003329 unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003330
3331 SmallVector<unsigned, 64> Vals;
Teresa Johnson7a27b132017-06-02 01:56:02 +00003332 forEachModule(
3333 [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
David Blaikieb6b42e02017-06-02 17:24:26 +00003334 StringRef Key = MPSE.getKey();
3335 const auto &Value = MPSE.getValue();
3336 StringEncoding Bits = getStringEncoding(Key);
Teresa Johnson7a27b132017-06-02 01:56:02 +00003337 unsigned AbbrevToUse = Abbrev8Bit;
3338 if (Bits == SE_Char6)
3339 AbbrevToUse = Abbrev6Bit;
3340 else if (Bits == SE_Fixed7)
3341 AbbrevToUse = Abbrev7Bit;
Teresa Johnson403a7872015-10-04 14:33:43 +00003342
David Blaikieb6b42e02017-06-02 17:24:26 +00003343 Vals.push_back(Value.first);
3344 Vals.append(Key.begin(), Key.end());
Teresa Johnson403a7872015-10-04 14:33:43 +00003345
Teresa Johnson7a27b132017-06-02 01:56:02 +00003346 // Emit the finished record.
3347 Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003348
Teresa Johnson7a27b132017-06-02 01:56:02 +00003349 // Emit an optional hash for the module now
David Blaikieb6b42e02017-06-02 17:24:26 +00003350 const auto &Hash = Value.second;
3351 if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3352 Vals.assign(Hash.begin(), Hash.end());
Teresa Johnson7a27b132017-06-02 01:56:02 +00003353 // Emit the hash record.
3354 Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3355 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003356
Teresa Johnson7a27b132017-06-02 01:56:02 +00003357 Vals.clear();
3358 });
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003359 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003360}
3361
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003362/// Write the function type metadata related records that need to appear before
3363/// a function summary entry (whether per-module or combined).
Vitaly Buka7e880a42018-09-19 18:51:25 +00003364static void writeFunctionTypeMetadataRecords(BitstreamWriter &Stream,
3365 FunctionSummary *FS) {
3366 if (!FS->type_tests().empty())
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00003367 Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3368
3369 SmallVector<uint64_t, 64> Record;
3370
3371 auto WriteVFuncIdVec = [&](uint64_t Ty,
3372 ArrayRef<FunctionSummary::VFuncId> VFs) {
3373 if (VFs.empty())
3374 return;
3375 Record.clear();
3376 for (auto &VF : VFs) {
3377 Record.push_back(VF.GUID);
3378 Record.push_back(VF.Offset);
3379 }
3380 Stream.EmitRecord(Ty, Record);
3381 };
3382
3383 WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3384 FS->type_test_assume_vcalls());
3385 WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3386 FS->type_checked_load_vcalls());
3387
3388 auto WriteConstVCallVec = [&](uint64_t Ty,
3389 ArrayRef<FunctionSummary::ConstVCall> VCs) {
3390 for (auto &VC : VCs) {
3391 Record.clear();
3392 Record.push_back(VC.VFunc.GUID);
3393 Record.push_back(VC.VFunc.Offset);
3394 Record.insert(Record.end(), VC.Args.begin(), VC.Args.end());
3395 Stream.EmitRecord(Ty, Record);
3396 }
3397 };
3398
3399 WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3400 FS->type_test_assume_const_vcalls());
3401 WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3402 FS->type_checked_load_const_vcalls());
3403}
3404
Vitaly Buka7e880a42018-09-19 18:51:25 +00003405/// Collect type IDs from type tests used by function.
3406static void
3407getReferencedTypeIds(FunctionSummary *FS,
3408 std::set<GlobalValue::GUID> &ReferencedTypeIds) {
3409 if (!FS->type_tests().empty())
3410 for (auto &TT : FS->type_tests())
3411 ReferencedTypeIds.insert(TT);
3412
3413 auto GetReferencedTypesFromVFuncIdVec =
3414 [&](ArrayRef<FunctionSummary::VFuncId> VFs) {
3415 for (auto &VF : VFs)
3416 ReferencedTypeIds.insert(VF.GUID);
3417 };
3418
3419 GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
3420 GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
3421
3422 auto GetReferencedTypesFromConstVCallVec =
3423 [&](ArrayRef<FunctionSummary::ConstVCall> VCs) {
3424 for (auto &VC : VCs)
3425 ReferencedTypeIds.insert(VC.VFunc.GUID);
3426 };
3427
3428 GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
3429 GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
3430}
3431
Vitaly Buka44396fa2018-02-14 22:41:15 +00003432static void writeWholeProgramDevirtResolutionByArg(
3433 SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
3434 const WholeProgramDevirtResolution::ByArg &ByArg) {
3435 NameVals.push_back(args.size());
3436 NameVals.insert(NameVals.end(), args.begin(), args.end());
3437
3438 NameVals.push_back(ByArg.TheKind);
3439 NameVals.push_back(ByArg.Info);
3440 NameVals.push_back(ByArg.Byte);
3441 NameVals.push_back(ByArg.Bit);
3442}
3443
3444static void writeWholeProgramDevirtResolution(
3445 SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3446 uint64_t Id, const WholeProgramDevirtResolution &Wpd) {
3447 NameVals.push_back(Id);
3448
3449 NameVals.push_back(Wpd.TheKind);
3450 NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
3451 NameVals.push_back(Wpd.SingleImplName.size());
3452
3453 NameVals.push_back(Wpd.ResByArg.size());
3454 for (auto &A : Wpd.ResByArg)
3455 writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
3456}
3457
3458static void writeTypeIdSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
3459 StringTableBuilder &StrtabBuilder,
3460 const std::string &Id,
3461 const TypeIdSummary &Summary) {
3462 NameVals.push_back(StrtabBuilder.add(Id));
3463 NameVals.push_back(Id.size());
3464
3465 NameVals.push_back(Summary.TTRes.TheKind);
3466 NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
3467 NameVals.push_back(Summary.TTRes.AlignLog2);
3468 NameVals.push_back(Summary.TTRes.SizeM1);
3469 NameVals.push_back(Summary.TTRes.BitMask);
3470 NameVals.push_back(Summary.TTRes.InlineBits);
3471
3472 for (auto &W : Summary.WPDRes)
3473 writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
3474 W.second);
3475}
3476
Teresa Johnson403a7872015-10-04 14:33:43 +00003477// Helper to emit a single function summary record.
Haojie Wang1dec57d2017-07-21 17:25:20 +00003478void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
Teresa Johnson28e457b2016-04-24 14:57:11 +00003479 SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
Teresa Johnson37687f32016-04-23 04:30:47 +00003480 unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3481 const Function &F) {
Teresa Johnson403a7872015-10-04 14:33:43 +00003482 NameVals.push_back(ValueID);
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003483
Teresa Johnson28e457b2016-04-24 14:57:11 +00003484 FunctionSummary *FS = cast<FunctionSummary>(Summary);
Vitaly Buka7e880a42018-09-19 18:51:25 +00003485 writeFunctionTypeMetadataRecords(Stream, FS);
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00003486
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003487 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
Teresa Johnson403a7872015-10-04 14:33:43 +00003488 NameVals.push_back(FS->instCount());
Charles Saternos75da10d2017-08-04 16:00:58 +00003489 NameVals.push_back(getEncodedFFlags(FS->fflags()));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003490 NameVals.push_back(FS->refs().size());
3491
3492 for (auto &RI : FS->refs())
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003493 NameVals.push_back(VE.getValueID(RI.getValue()));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003494
Teresa Johnsondb83ace2018-03-31 00:18:08 +00003495 bool HasProfileData =
3496 F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None;
Peter Collingbourne0c30f082016-12-20 21:12:28 +00003497 for (auto &ECI : FS->calls()) {
Teresa Johnsoncd21a642016-07-17 14:47:01 +00003498 NameVals.push_back(getValueId(ECI.first));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003499 if (HasProfileData)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003500 NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
Easwaran Ramanc73cec82018-01-25 19:27:17 +00003501 else if (WriteRelBFToSummary)
3502 NameVals.push_back(ECI.second.RelBlockFreq);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003503 }
3504
3505 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3506 unsigned Code =
Easwaran Ramanc73cec82018-01-25 19:27:17 +00003507 (HasProfileData ? bitc::FS_PERMODULE_PROFILE
3508 : (WriteRelBFToSummary ? bitc::FS_PERMODULE_RELBF
3509 : bitc::FS_PERMODULE));
Teresa Johnson403a7872015-10-04 14:33:43 +00003510
3511 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003512 Stream.EmitRecord(Code, NameVals, FSAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003513 NameVals.clear();
3514}
3515
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003516// Collect the global value references in the given variable's initializer,
3517// and emit them in a summary record.
Haojie Wang1dec57d2017-07-21 17:25:20 +00003518void ModuleBitcodeWriterBase::writeModuleLevelReferences(
Teresa Johnson37687f32016-04-23 04:30:47 +00003519 const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3520 unsigned FSModRefsAbbrev) {
Teresa Johnson7bea1aa2018-06-26 00:20:49 +00003521 auto VI = Index->getValueInfo(V.getGUID());
Peter Collingbourne9667b912017-05-04 18:03:25 +00003522 if (!VI || VI.getSummaryList().empty()) {
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003523 // Only declarations should not have a summary (a declaration might however
3524 // have a summary if the def was in module level asm).
3525 assert(V.isDeclaration());
Teresa Johnson13968092016-03-15 19:35:45 +00003526 return;
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003527 }
Peter Collingbourne9667b912017-05-04 18:03:25 +00003528 auto *Summary = VI.getSummaryList()[0].get();
Teresa Johnson13968092016-03-15 19:35:45 +00003529 NameVals.push_back(VE.getValueID(&V));
Teresa Johnson28e457b2016-04-24 14:57:11 +00003530 GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
Teresa Johnson7c31cb12016-10-28 19:36:00 +00003531 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003532
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003533 unsigned SizeBeforeRefs = NameVals.size();
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003534 for (auto &RI : VS->refs())
Mehdi Aminifdbb8f42016-05-16 22:47:15 +00003535 NameVals.push_back(VE.getValueID(RI.getValue()));
3536 // Sort the refs for determinism output, the vector returned by FS->refs() has
3537 // been initialized from a DenseSet.
Mandeep Singh Grang176c3ef2018-04-05 19:27:04 +00003538 llvm::sort(NameVals.begin() + SizeBeforeRefs, NameVals.end());
Mehdi Aminif606c8d2016-05-16 08:50:27 +00003539
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003540 Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3541 FSModRefsAbbrev);
Teresa Johnson13968092016-03-15 19:35:45 +00003542 NameVals.clear();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003543}
Teresa Johnson403a7872015-10-04 14:33:43 +00003544
Mehdi Amini8fe69362016-04-24 03:18:11 +00003545// Current version for the summary.
3546// This is bumped whenever we introduce changes in the way some record are
3547// interpreted, like flags for instance.
Charles Saternos75da10d2017-08-04 16:00:58 +00003548static const uint64_t INDEX_VERSION = 4;
Mehdi Amini8fe69362016-04-24 03:18:11 +00003549
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003550/// Emit the per-module summary section alongside the rest of
3551/// the module's bitcode.
Haojie Wang1dec57d2017-07-21 17:25:20 +00003552void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
Peter Collingbournee357fbd2017-06-08 23:01:49 +00003553 // By default we compile with ThinLTO if the module has a summary, but the
3554 // client can request full LTO with a module flag.
3555 bool IsThinLTO = true;
3556 if (auto *MD =
3557 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3558 IsThinLTO = MD->getZExtValue();
3559 Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
3560 : bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID,
3561 4);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003562
Mehdi Amini8fe69362016-04-24 03:18:11 +00003563 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
3564
Teresa Johnson620c1402016-09-20 23:07:17 +00003565 if (Index->begin() == Index->end()) {
3566 Stream.ExitBlock();
3567 return;
3568 }
3569
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003570 for (const auto &GVI : valueIds()) {
3571 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3572 ArrayRef<uint64_t>{GVI.second, GVI.first});
3573 }
3574
Easwaran Ramanbf38dee2018-01-24 18:15:29 +00003575 // Abbrev for FS_PERMODULE_PROFILE.
Easwaran Ramanc73cec82018-01-25 19:27:17 +00003576 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003577 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_PROFILE));
3578 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003579 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003580 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Charles Saternos75da10d2017-08-04 16:00:58 +00003581 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003582 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003583 // numrefs x valueid, n x (valueid, hotness)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003584 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3585 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003586 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003587
Easwaran Ramanc73cec82018-01-25 19:27:17 +00003588 // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
3589 Abbv = std::make_shared<BitCodeAbbrev>();
3590 if (WriteRelBFToSummary)
3591 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_RELBF));
3592 else
3593 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
3594 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
3595 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
3596 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
3597 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
3598 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
3599 // numrefs x valueid, n x (valueid [, rel_block_freq])
3600 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3601 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3602 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3603
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003604 // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003605 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003606 Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS));
3607 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003608 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003609 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3610 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003611 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003612
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003613 // Abbrev for FS_ALIAS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003614 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003615 Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
3616 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003617 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003618 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
David Blaikie7ad9dc12017-01-04 22:36:33 +00003619 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003620
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003621 SmallVector<uint64_t, 64> NameVals;
Teresa Johnson2d5487c2016-04-11 13:58:45 +00003622 // Iterate over the list of functions instead of the Index to
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003623 // ensure the ordering is stable.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003624 for (const Function &F : M) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003625 // Summary emission does not support anonymous functions, they have to
3626 // renamed using the anonymous function renaming pass.
Teresa Johnson2d9da4dc2016-02-01 20:16:35 +00003627 if (!F.hasName())
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003628 report_fatal_error("Unexpected anonymous function when writing summary");
Teresa Johnson403a7872015-10-04 14:33:43 +00003629
Teresa Johnson7bea1aa2018-06-26 00:20:49 +00003630 ValueInfo VI = Index->getValueInfo(F.getGUID());
Peter Collingbourne9667b912017-05-04 18:03:25 +00003631 if (!VI || VI.getSummaryList().empty()) {
Teresa Johnson3624bdf2016-11-14 17:12:32 +00003632 // Only declarations should not have a summary (a declaration might
3633 // however have a summary if the def was in module level asm).
3634 assert(F.isDeclaration());
3635 continue;
3636 }
Peter Collingbourne9667b912017-05-04 18:03:25 +00003637 auto *Summary = VI.getSummaryList()[0].get();
Peter Collingbourne832e7fa2016-05-06 02:41:23 +00003638 writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
3639 FSCallsAbbrev, FSCallsProfileAbbrev, F);
Teresa Johnson403a7872015-10-04 14:33:43 +00003640 }
3641
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003642 // Capture references from GlobalVariable initializers, which are outside
3643 // of a function scope.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003644 for (const GlobalVariable &G : M.globals())
Teresa Johnson37687f32016-04-23 04:30:47 +00003645 writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003646
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003647 for (const GlobalAlias &A : M.aliases()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003648 auto *Aliasee = A.getBaseObject();
3649 if (!Aliasee->hasName())
3650 // Nameless function don't have an entry in the summary, skip it.
3651 continue;
3652 auto AliasId = VE.getValueID(&A);
3653 auto AliaseeId = VE.getValueID(Aliasee);
3654 NameVals.push_back(AliasId);
Teresa Johnson02563cd2016-10-28 02:39:38 +00003655 auto *Summary = Index->getGlobalValueSummary(A);
3656 AliasSummary *AS = cast<AliasSummary>(Summary);
3657 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003658 NameVals.push_back(AliaseeId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003659 Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003660 NameVals.clear();
3661 }
3662
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003663 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003664}
3665
Teresa Johnson26ab5772016-03-15 00:04:37 +00003666/// Emit the combined summary section into the combined index file.
Teresa Johnson37687f32016-04-23 04:30:47 +00003667void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003668 Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
Mehdi Amini8fe69362016-04-24 03:18:11 +00003669 Stream.EmitRecord(bitc::FS_VERSION, ArrayRef<uint64_t>{INDEX_VERSION});
Teresa Johnson403a7872015-10-04 14:33:43 +00003670
Vitaly Buka769134d2018-02-16 23:38:22 +00003671 // Write the index flags.
3672 uint64_t Flags = 0;
3673 if (Index.withGlobalValueDeadStripping())
3674 Flags |= 0x1;
3675 if (Index.skipModuleByDistributedBackend())
3676 Flags |= 0x2;
3677 Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
Teresa Johnsonf3681012018-02-07 04:05:59 +00003678
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003679 for (const auto &GVI : valueIds()) {
3680 Stream.EmitRecord(bitc::FS_VALUE_GUID,
3681 ArrayRef<uint64_t>{GVI.second, GVI.first});
3682 }
3683
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003684 // Abbrev for FS_COMBINED.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003685 auto Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003686 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
Teresa Johnson02e98332016-04-27 13:28:35 +00003687 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003688 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003689 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003690 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Charles Saternos75da10d2017-08-04 16:00:58 +00003691 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003692 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003693 // numrefs x valueid, n x (valueid)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003694 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3695 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003696 unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson403a7872015-10-04 14:33:43 +00003697
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003698 // Abbrev for FS_COMBINED_PROFILE.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003699 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003700 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_PROFILE));
Teresa Johnson02e98332016-04-27 13:28:35 +00003701 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003702 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003703 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003704 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
Charles Saternos75da10d2017-08-04 16:00:58 +00003705 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003706 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003707 // numrefs x valueid, n x (valueid, hotness)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003708 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3709 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003710 unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003711
3712 // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003713 Abbv = std::make_shared<BitCodeAbbrev>();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003714 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003715 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003716 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003717 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003718 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
3719 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003720 unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003721
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003722 // Abbrev for FS_COMBINED_ALIAS.
David Blaikie7ad9dc12017-01-04 22:36:33 +00003723 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003724 Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED_ALIAS));
Teresa Johnson02e98332016-04-27 13:28:35 +00003725 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003726 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003727 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
Teresa Johnson02e98332016-04-27 13:28:35 +00003728 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
David Blaikie7ad9dc12017-01-04 22:36:33 +00003729 unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003730
Teresa Johnson02e98332016-04-27 13:28:35 +00003731 // The aliases are emitted as a post-pass, and will point to the value
3732 // id of the aliasee. Save them in a vector for post-processing.
Teresa Johnson28e457b2016-04-24 14:57:11 +00003733 SmallVector<AliasSummary *, 64> Aliases;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003734
Teresa Johnson02e98332016-04-27 13:28:35 +00003735 // Save the value id for each summary for alias emission.
3736 DenseMap<const GlobalValueSummary *, unsigned> SummaryToValueIdMap;
3737
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003738 SmallVector<uint64_t, 64> NameVals;
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003739
Teresa Johnson0c432b12018-07-19 22:25:56 +00003740 // Set that will be populated during call to writeFunctionTypeMetadataRecords
3741 // with the type ids referenced by this index file.
3742 std::set<GlobalValue::GUID> ReferencedTypeIds;
3743
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003744 // For local linkage, we also emit the original name separately
3745 // immediately after the record.
3746 auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
3747 if (!GlobalValue::isLocalLinkage(S.linkage()))
3748 return;
3749 NameVals.push_back(S.getOriginalName());
3750 Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
3751 NameVals.clear();
3752 };
3753
Teresa Johnson81bbf742017-12-16 00:18:12 +00003754 forEachSummary([&](GVInfo I, bool IsAliasee) {
Teresa Johnson84174c32016-05-10 13:48:23 +00003755 GlobalValueSummary *S = I.second;
3756 assert(S);
Teresa Johnson02e98332016-04-27 13:28:35 +00003757
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003758 auto ValueId = getValueId(I.first);
3759 assert(ValueId);
3760 SummaryToValueIdMap[S] = *ValueId;
Teresa Johnson02e98332016-04-27 13:28:35 +00003761
Teresa Johnson81bbf742017-12-16 00:18:12 +00003762 // If this is invoked for an aliasee, we want to record the above
3763 // mapping, but then not emit a summary entry (if the aliasee is
3764 // to be imported, we will invoke this separately with IsAliasee=false).
3765 if (IsAliasee)
3766 return;
3767
Teresa Johnson84174c32016-05-10 13:48:23 +00003768 if (auto *AS = dyn_cast<AliasSummary>(S)) {
3769 // Will process aliases as a post-pass because the reader wants all
3770 // global to be loaded first.
3771 Aliases.push_back(AS);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003772 return;
Teresa Johnson84174c32016-05-10 13:48:23 +00003773 }
Teresa Johnson403a7872015-10-04 14:33:43 +00003774
Teresa Johnson84174c32016-05-10 13:48:23 +00003775 if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003776 NameVals.push_back(*ValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003777 NameVals.push_back(Index.getModuleId(VS->modulePath()));
3778 NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3779 for (auto &RI : VS->refs()) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003780 auto RefValueId = getValueId(RI.getGUID());
3781 if (!RefValueId)
3782 continue;
3783 NameVals.push_back(*RefValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00003784 }
3785
Teresa Johnson403a7872015-10-04 14:33:43 +00003786 // Emit the finished record.
Teresa Johnson84174c32016-05-10 13:48:23 +00003787 Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
3788 FSModRefsAbbrev);
Teresa Johnson403a7872015-10-04 14:33:43 +00003789 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003790 MaybeEmitOriginalName(*S);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003791 return;
Teresa Johnson403a7872015-10-04 14:33:43 +00003792 }
Teresa Johnson84174c32016-05-10 13:48:23 +00003793
3794 auto *FS = cast<FunctionSummary>(S);
Vitaly Buka7e880a42018-09-19 18:51:25 +00003795 writeFunctionTypeMetadataRecords(Stream, FS);
3796 getReferencedTypeIds(FS, ReferencedTypeIds);
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00003797
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003798 NameVals.push_back(*ValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003799 NameVals.push_back(Index.getModuleId(FS->modulePath()));
3800 NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3801 NameVals.push_back(FS->instCount());
Charles Saternos75da10d2017-08-04 16:00:58 +00003802 NameVals.push_back(getEncodedFFlags(FS->fflags()));
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003803 // Fill in below
3804 NameVals.push_back(0);
Teresa Johnson84174c32016-05-10 13:48:23 +00003805
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003806 unsigned Count = 0;
Teresa Johnson84174c32016-05-10 13:48:23 +00003807 for (auto &RI : FS->refs()) {
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003808 auto RefValueId = getValueId(RI.getGUID());
3809 if (!RefValueId)
3810 continue;
3811 NameVals.push_back(*RefValueId);
3812 Count++;
Teresa Johnson84174c32016-05-10 13:48:23 +00003813 }
Charles Saternos75da10d2017-08-04 16:00:58 +00003814 NameVals[5] = Count;
Teresa Johnson84174c32016-05-10 13:48:23 +00003815
3816 bool HasProfileData = false;
3817 for (auto &EI : FS->calls()) {
Easwaran Ramanc73cec82018-01-25 19:27:17 +00003818 HasProfileData |=
3819 EI.second.getHotness() != CalleeInfo::HotnessType::Unknown;
Teresa Johnson84174c32016-05-10 13:48:23 +00003820 if (HasProfileData)
3821 break;
3822 }
3823
3824 for (auto &EI : FS->calls()) {
3825 // If this GUID doesn't have a value id, it doesn't have a function
3826 // summary and we don't need to record any calls to it.
Dehao Chen4a435e02017-03-14 17:33:01 +00003827 GlobalValue::GUID GUID = EI.first.getGUID();
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003828 auto CallValueId = getValueId(GUID);
3829 if (!CallValueId) {
Dehao Chen4a435e02017-03-14 17:33:01 +00003830 // For SamplePGO, the indirect call targets for local functions will
3831 // have its original name annotated in profile. We try to find the
3832 // corresponding PGOFuncName as the GUID.
3833 GUID = Index.getGUIDFromOriginalID(GUID);
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003834 if (GUID == 0)
3835 continue;
3836 CallValueId = getValueId(GUID);
3837 if (!CallValueId)
Dehao Chen4a435e02017-03-14 17:33:01 +00003838 continue;
Xinliang David Li71ecaa12017-08-16 17:18:01 +00003839 // The mapping from OriginalId to GUID may return a GUID
Xinliang David Li5a57b842017-08-16 17:33:43 +00003840 // that corresponds to a static variable. Filter it out here.
Fangrui Songf78650a2018-07-30 19:41:25 +00003841 // This can happen when
Xinliang David Li5a57b842017-08-16 17:33:43 +00003842 // 1) There is a call to a library function which does not have
3843 // a CallValidId;
3844 // 2) There is a static variable with the OriginalGUID identical
3845 // to the GUID of the library function in 1);
3846 // When this happens, the logic for SamplePGO kicks in and
Mandeep Singh Grang1be19e62017-09-15 20:01:43 +00003847 // the static variable in 2) will be found, which needs to be
Xinliang David Li5a57b842017-08-16 17:33:43 +00003848 // filtered out.
Xinliang David Li71ecaa12017-08-16 17:18:01 +00003849 auto *GVSum = Index.getGlobalValueSummary(GUID, false);
3850 if (GVSum &&
3851 GVSum->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
3852 continue;
Dehao Chen4a435e02017-03-14 17:33:01 +00003853 }
Teresa Johnsona6a3fb52017-05-31 18:58:11 +00003854 NameVals.push_back(*CallValueId);
Teresa Johnson84174c32016-05-10 13:48:23 +00003855 if (HasProfileData)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00003856 NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
Teresa Johnson84174c32016-05-10 13:48:23 +00003857 }
3858
3859 unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3860 unsigned Code =
3861 (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
3862
3863 // Emit the finished record.
3864 Stream.EmitRecord(Code, NameVals, FSAbbrev);
3865 NameVals.clear();
3866 MaybeEmitOriginalName(*S);
Peter Collingbourne7c2c4092017-05-02 17:48:39 +00003867 });
Teresa Johnson403a7872015-10-04 14:33:43 +00003868
Teresa Johnson28e457b2016-04-24 14:57:11 +00003869 for (auto *AS : Aliases) {
Teresa Johnson02e98332016-04-27 13:28:35 +00003870 auto AliasValueId = SummaryToValueIdMap[AS];
3871 assert(AliasValueId);
3872 NameVals.push_back(AliasValueId);
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003873 NameVals.push_back(Index.getModuleId(AS->modulePath()));
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00003874 NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
Teresa Johnson02e98332016-04-27 13:28:35 +00003875 auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
3876 assert(AliaseeValueId);
3877 NameVals.push_back(AliaseeValueId);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003878
3879 // Emit the finished record.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003880 Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003881 NameVals.clear();
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00003882 MaybeEmitOriginalName(*AS);
Vitaly Buka84d912b2018-09-19 18:51:42 +00003883
3884 if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
3885 getReferencedTypeIds(FS, ReferencedTypeIds);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00003886 }
3887
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00003888 if (!Index.cfiFunctionDefs().empty()) {
3889 for (auto &S : Index.cfiFunctionDefs()) {
3890 NameVals.push_back(StrtabBuilder.add(S));
3891 NameVals.push_back(S.size());
3892 }
3893 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
3894 NameVals.clear();
3895 }
3896
3897 if (!Index.cfiFunctionDecls().empty()) {
3898 for (auto &S : Index.cfiFunctionDecls()) {
3899 NameVals.push_back(StrtabBuilder.add(S));
3900 NameVals.push_back(S.size());
3901 }
3902 Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
3903 NameVals.clear();
3904 }
3905
Teresa Johnson7fb39df2018-09-25 20:14:40 +00003906 // Walk the GUIDs that were referenced, and write the
3907 // corresponding type id records.
3908 for (auto &T : ReferencedTypeIds) {
3909 auto TidIter = Index.typeIds().equal_range(T);
3910 for (auto It = TidIter.first; It != TidIter.second; ++It) {
3911 writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,
3912 It->second.second);
Vitaly Buka44396fa2018-02-14 22:41:15 +00003913 Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
3914 NameVals.clear();
3915 }
3916 }
3917
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003918 Stream.ExitBlock();
Teresa Johnson403a7872015-10-04 14:33:43 +00003919}
3920
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003921/// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
3922/// current llvm version, and a record for the epoch number.
Benjamin Kramerefcf06f2017-02-11 11:06:55 +00003923static void writeIdentificationBlock(BitstreamWriter &Stream) {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003924 Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
Mehdi Amini5d303282015-10-26 18:37:00 +00003925
3926 // Write the "user readable" string identifying the bitcode producer
David Blaikie7ad9dc12017-01-04 22:36:33 +00003927 auto Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini5d303282015-10-26 18:37:00 +00003928 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_STRING));
3929 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
3930 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003931 auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003932 writeStringRecord(Stream, bitc::IDENTIFICATION_CODE_STRING,
Teresa Johnson37687f32016-04-23 04:30:47 +00003933 "LLVM" LLVM_VERSION_STRING, StringAbbrev);
Mehdi Amini5d303282015-10-26 18:37:00 +00003934
3935 // Write the epoch version
David Blaikie7ad9dc12017-01-04 22:36:33 +00003936 Abbv = std::make_shared<BitCodeAbbrev>();
Mehdi Amini5d303282015-10-26 18:37:00 +00003937 Abbv->Add(BitCodeAbbrevOp(bitc::IDENTIFICATION_CODE_EPOCH));
3938 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
David Blaikie7ad9dc12017-01-04 22:36:33 +00003939 auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
Mehdi Amini5d303282015-10-26 18:37:00 +00003940 SmallVector<unsigned, 1> Vals = {bitc::BITCODE_CURRENT_EPOCH};
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003941 Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
3942 Stream.ExitBlock();
Mehdi Amini5d303282015-10-26 18:37:00 +00003943}
3944
Teresa Johnson37687f32016-04-23 04:30:47 +00003945void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003946 // Emit the module's hash.
3947 // MODULE_CODE_HASH: [5*i32]
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003948 if (GenerateHash) {
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003949 uint32_t Vals[5];
3950 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
3951 Buffer.size() - BlockStartPos));
3952 StringRef Hash = Hasher.result();
3953 for (int Pos = 0; Pos < 20; Pos += 4) {
3954 Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
3955 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003956
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00003957 // Emit the finished record.
3958 Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
3959
3960 if (ModHash)
3961 // Save the written hash value.
3962 std::copy(std::begin(Vals), std::end(Vals), std::begin(*ModHash));
Haojie Wang1dec57d2017-07-21 17:25:20 +00003963 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00003964}
3965
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00003966void ModuleBitcodeWriter::write() {
3967 writeIdentificationBlock(Stream);
Teresa Johnson37687f32016-04-23 04:30:47 +00003968
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00003969 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
3970 size_t BlockStartPos = Buffer.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003971
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003972 writeModuleVersion();
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003973
3974 // Emit blockinfo, which defines the standard abbreviations etc.
Teresa Johnson37687f32016-04-23 04:30:47 +00003975 writeBlockInfo();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003976
Bill Wendlingdc095552013-02-10 23:09:32 +00003977 // Emit information about attribute groups.
Teresa Johnson37687f32016-04-23 04:30:47 +00003978 writeAttributeGroupTable();
Bill Wendlingdc095552013-02-10 23:09:32 +00003979
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003980 // Emit information about parameter attributes.
Teresa Johnson37687f32016-04-23 04:30:47 +00003981 writeAttributeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003982
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003983 // Emit information describing all of the types in the module.
Teresa Johnson37687f32016-04-23 04:30:47 +00003984 writeTypeTable();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003985
Teresa Johnson37687f32016-04-23 04:30:47 +00003986 writeComdats();
David Majnemerdad0a642014-06-27 18:19:56 +00003987
Chris Lattnerda5e5d22007-05-05 07:36:14 +00003988 // Emit top-level description of module, including target triple, inline asm,
3989 // descriptors for global variables, and function prototype info.
Teresa Johnson37687f32016-04-23 04:30:47 +00003990 writeModuleInfo();
Devang Patel7428d8a2009-07-22 17:43:22 +00003991
Devang Patele059ba6e2009-07-23 01:07:34 +00003992 // Emit constants.
Teresa Johnson37687f32016-04-23 04:30:47 +00003993 writeModuleConstants();
Devang Patele059ba6e2009-07-23 01:07:34 +00003994
Peter Collingbourne21521892016-06-21 23:42:48 +00003995 // Emit metadata kind names.
3996 writeModuleMetadataKinds();
Devang Patel8cca7b42009-08-04 05:01:35 +00003997
Devang Patelaf206b82009-09-18 19:26:43 +00003998 // Emit metadata.
Peter Collingbourne21521892016-06-21 23:42:48 +00003999 writeModuleMetadata();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004000
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004001 // Emit module-level use-lists.
Duncan P. N. Exon Smith458593a2015-04-14 23:45:11 +00004002 if (VE.shouldPreserveUseListOrder())
Teresa Johnson37687f32016-04-23 04:30:47 +00004003 writeUseListBlock(nullptr);
Chad Rosierca2567b2011-12-07 21:44:12 +00004004
Teresa Johnson37687f32016-04-23 04:30:47 +00004005 writeOperandBundleTags();
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004006 writeSyncScopeNames();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004007
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004008 // Emit function bodies.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00004009 DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00004010 for (Module::const_iterator F = M.begin(), E = M.end(); F != E; ++F)
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004011 if (!F->isDeclaration())
Teresa Johnson37687f32016-04-23 04:30:47 +00004012 writeFunction(*F, FunctionToBitcodeIndex);
Teresa Johnson403a7872015-10-04 14:33:43 +00004013
4014 // Need to write after the above call to WriteFunction which populates
4015 // the summary information in the index.
Teresa Johnson2d5487c2016-04-11 13:58:45 +00004016 if (Index)
Teresa Johnson37687f32016-04-23 04:30:47 +00004017 writePerModuleGlobalValueSummary();
Teresa Johnsonff642b92015-09-17 20:12:00 +00004018
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004019 writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004020
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004021 writeModuleHash(BlockStartPos);
Mehdi Aminid7ad2212016-04-01 05:33:11 +00004022
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00004023 Stream.ExitBlock();
Chris Lattner702658c2007-05-04 18:26:27 +00004024}
4025
Teresa Johnson37687f32016-04-23 04:30:47 +00004026static void writeInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
4027 uint32_t &Position) {
4028 support::endian::write32le(&Buffer[Position], Value);
4029 Position += 4;
4030}
4031
4032/// If generating a bc file on darwin, we have to emit a
Chris Lattnera660f4b2008-07-09 05:14:23 +00004033/// header and trailer to make it compatible with the system archiver. To do
4034/// this we emit the following header, and then emit a trailer that pads the
4035/// file out to be a multiple of 16 bytes.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004036///
Chris Lattnera660f4b2008-07-09 05:14:23 +00004037/// struct bc_header {
4038/// uint32_t Magic; // 0x0B17C0DE
4039/// uint32_t Version; // Version, currently always 0.
4040/// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
4041/// uint32_t BitcodeSize; // Size of traditional bitcode file.
4042/// uint32_t CPUType; // CPU specifier.
4043/// ... potentially more later ...
4044/// };
Teresa Johnson37687f32016-04-23 04:30:47 +00004045static void emitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004046 const Triple &TT) {
Chris Lattnera660f4b2008-07-09 05:14:23 +00004047 unsigned CPUType = ~0U;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004048
Evan Cheng9aa30fb2010-02-12 20:13:44 +00004049 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
Evan Cheng545d3602010-02-12 20:39:35 +00004050 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
4051 // number from /usr/include/mach/machine.h. It is ok to reproduce the
4052 // specific constants here because they are implicitly part of the Darwin ABI.
Chris Lattnera660f4b2008-07-09 05:14:23 +00004053 enum {
4054 DARWIN_CPU_ARCH_ABI64 = 0x01000000,
4055 DARWIN_CPU_TYPE_X86 = 7,
Evan Cheng9aa30fb2010-02-12 20:13:44 +00004056 DARWIN_CPU_TYPE_ARM = 12,
Chris Lattnera660f4b2008-07-09 05:14:23 +00004057 DARWIN_CPU_TYPE_POWERPC = 18
4058 };
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004059
Evan Chengcffdcae2011-06-14 01:51:33 +00004060 Triple::ArchType Arch = TT.getArch();
4061 if (Arch == Triple::x86_64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00004062 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00004063 else if (Arch == Triple::x86)
Chris Lattnera660f4b2008-07-09 05:14:23 +00004064 CPUType = DARWIN_CPU_TYPE_X86;
Evan Chengcffdcae2011-06-14 01:51:33 +00004065 else if (Arch == Triple::ppc)
Chris Lattnera660f4b2008-07-09 05:14:23 +00004066 CPUType = DARWIN_CPU_TYPE_POWERPC;
Evan Chengcffdcae2011-06-14 01:51:33 +00004067 else if (Arch == Triple::ppc64)
Chris Lattnera660f4b2008-07-09 05:14:23 +00004068 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
Evan Chengcffdcae2011-06-14 01:51:33 +00004069 else if (Arch == Triple::arm || Arch == Triple::thumb)
Evan Cheng9aa30fb2010-02-12 20:13:44 +00004070 CPUType = DARWIN_CPU_TYPE_ARM;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004071
Chris Lattnera660f4b2008-07-09 05:14:23 +00004072 // Traditional Bitcode starts after header.
Akira Hatanaka4f472a882016-01-29 05:55:09 +00004073 assert(Buffer.size() >= BWH_HeaderSize &&
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004074 "Expected header size to be reserved");
Akira Hatanaka4f472a882016-01-29 05:55:09 +00004075 unsigned BCOffset = BWH_HeaderSize;
4076 unsigned BCSize = Buffer.size() - BWH_HeaderSize;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004077
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004078 // Write the magic and version.
4079 unsigned Position = 0;
Teresa Johnson37687f32016-04-23 04:30:47 +00004080 writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
4081 writeInt32ToBuffer(0, Buffer, Position); // Version.
4082 writeInt32ToBuffer(BCOffset, Buffer, Position);
4083 writeInt32ToBuffer(BCSize, Buffer, Position);
4084 writeInt32ToBuffer(CPUType, Buffer, Position);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004085
Chris Lattnera660f4b2008-07-09 05:14:23 +00004086 // If the file is not a multiple of 16 bytes, insert dummy padding.
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004087 while (Buffer.size() & 15)
4088 Buffer.push_back(0);
Chris Lattnera660f4b2008-07-09 05:14:23 +00004089}
4090
Teresa Johnson403a7872015-10-04 14:33:43 +00004091/// Helper to write the header common to all bitcode files.
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004092static void writeBitcodeHeader(BitstreamWriter &Stream) {
Teresa Johnson403a7872015-10-04 14:33:43 +00004093 // Emit the file header.
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00004094 Stream.Emit((unsigned)'B', 8);
4095 Stream.Emit((unsigned)'C', 8);
4096 Stream.Emit(0x0, 4);
4097 Stream.Emit(0xC, 4);
4098 Stream.Emit(0xE, 4);
4099 Stream.Emit(0xD, 4);
Teresa Johnson403a7872015-10-04 14:33:43 +00004100}
4101
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004102BitcodeWriter::BitcodeWriter(SmallVectorImpl<char> &Buffer)
4103 : Buffer(Buffer), Stream(new BitstreamWriter(Buffer)) {
4104 writeBitcodeHeader(*Stream);
4105}
4106
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004107BitcodeWriter::~BitcodeWriter() { assert(WroteStrtab); }
4108
4109void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
4110 Stream->EnterSubblock(Block, 3);
4111
4112 auto Abbv = std::make_shared<BitCodeAbbrev>();
4113 Abbv->Add(BitCodeAbbrevOp(Record));
4114 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4115 auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
4116
4117 Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
4118
4119 Stream->ExitBlock();
4120}
4121
Peter Collingbourne92648c22017-06-27 23:50:11 +00004122void BitcodeWriter::writeSymtab() {
4123 assert(!WroteStrtab && !WroteSymtab);
4124
4125 // If any module has module-level inline asm, we will require a registered asm
4126 // parser for the target so that we can create an accurate symbol table for
4127 // the module.
4128 for (Module *M : Mods) {
4129 if (M->getModuleInlineAsm().empty())
4130 continue;
4131
4132 std::string Err;
4133 const Triple TT(M->getTargetTriple());
4134 const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
4135 if (!T || !T->hasMCAsmParser())
4136 return;
4137 }
4138
4139 WroteSymtab = true;
4140 SmallVector<char, 0> Symtab;
4141 // The irsymtab::build function may be unable to create a symbol table if the
4142 // module is malformed (e.g. it contains an invalid alias). Writing a symbol
4143 // table is not required for correctness, but we still want to be able to
4144 // write malformed modules to bitcode files, so swallow the error.
4145 if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
4146 consumeError(std::move(E));
4147 return;
4148 }
4149
4150 writeBlob(bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB,
4151 {Symtab.data(), Symtab.size()});
4152}
4153
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004154void BitcodeWriter::writeStrtab() {
4155 assert(!WroteStrtab);
4156
4157 std::vector<char> Strtab;
4158 StrtabBuilder.finalizeInOrder();
4159 Strtab.resize(StrtabBuilder.getSize());
4160 StrtabBuilder.write((uint8_t *)Strtab.data());
4161
4162 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB,
4163 {Strtab.data(), Strtab.size()});
4164
4165 WroteStrtab = true;
4166}
4167
4168void BitcodeWriter::copyStrtab(StringRef Strtab) {
4169 writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
4170 WroteStrtab = true;
4171}
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004172
Rafael Espindola6a86e252018-02-14 19:11:32 +00004173void BitcodeWriter::writeModule(const Module &M,
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004174 bool ShouldPreserveUseListOrder,
4175 const ModuleSummaryIndex *Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004176 bool GenerateHash, ModuleHash *ModHash) {
Peter Collingbourne92648c22017-06-27 23:50:11 +00004177 assert(!WroteStrtab);
4178
4179 // The Mods vector is used by irsymtab::build, which requires non-const
4180 // Modules in case it needs to materialize metadata. But the bitcode writer
4181 // requires that the module is materialized, so we can cast to non-const here,
4182 // after checking that it is in fact materialized.
Rafael Espindola6a86e252018-02-14 19:11:32 +00004183 assert(M.isMaterialized());
4184 Mods.push_back(const_cast<Module *>(&M));
Peter Collingbourne92648c22017-06-27 23:50:11 +00004185
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004186 ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004187 ShouldPreserveUseListOrder, Index,
4188 GenerateHash, ModHash);
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004189 ModuleWriter.write();
4190}
4191
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00004192void BitcodeWriter::writeIndex(
4193 const ModuleSummaryIndex *Index,
4194 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4195 IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
4196 ModuleToSummariesForIndex);
4197 IndexWriter.write();
4198}
4199
Rafael Espindola6a86e252018-02-14 19:11:32 +00004200/// Write the specified module to the specified output stream.
4201void llvm::WriteBitcodeToFile(const Module &M, raw_ostream &Out,
Teresa Johnson403a7872015-10-04 14:33:43 +00004202 bool ShouldPreserveUseListOrder,
Teresa Johnson2d5487c2016-04-11 13:58:45 +00004203 const ModuleSummaryIndex *Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004204 bool GenerateHash, ModuleHash *ModHash) {
Michael Ilsemane26658d2012-12-03 21:29:36 +00004205 SmallVector<char, 0> Buffer;
Chris Lattnerc1d10d62007-04-22 06:24:45 +00004206 Buffer.reserve(256*1024);
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00004207
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004208 // If this is darwin or another generic macho target, reserve space for the
4209 // header.
Rafael Espindola6a86e252018-02-14 19:11:32 +00004210 Triple TT(M.getTargetTriple());
Akira Hatanaka1235d282016-01-23 16:02:10 +00004211 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Akira Hatanaka4f472a882016-01-29 05:55:09 +00004212 Buffer.insert(Buffer.begin(), BWH_HeaderSize, 0);
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004213
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004214 BitcodeWriter Writer(Buffer);
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +00004215 Writer.writeModule(M, ShouldPreserveUseListOrder, Index, GenerateHash,
4216 ModHash);
Peter Collingbourne92648c22017-06-27 23:50:11 +00004217 Writer.writeSymtab();
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004218 Writer.writeStrtab();
Daniel Dunbar6e45c022012-02-29 20:31:01 +00004219
Akira Hatanaka1235d282016-01-23 16:02:10 +00004220 if (TT.isOSDarwin() || TT.isOSBinFormatMachO())
Teresa Johnson37687f32016-04-23 04:30:47 +00004221 emitDarwinBCHeaderAndTrailer(Buffer, TT);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004222
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00004223 // Write the generated bitstream to "Out".
4224 Out.write((char*)&Buffer.front(), Buffer.size());
Chris Lattneraf4c0bf2008-12-19 18:37:59 +00004225}
Teresa Johnson403a7872015-10-04 14:33:43 +00004226
Peter Collingbourne5a0a2e62016-11-29 20:43:47 +00004227void IndexBitcodeWriter::write() {
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00004228 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
Teresa Johnson37687f32016-04-23 04:30:47 +00004229
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004230 writeModuleVersion();
Teresa Johnson37687f32016-04-23 04:30:47 +00004231
4232 // Write the module paths in the combined index.
4233 writeModStrings();
4234
4235 // Write the summary combined index records.
4236 writeCombinedGlobalValueSummary();
4237
Teresa Johnsonc814e0c2016-04-23 04:31:20 +00004238 Stream.ExitBlock();
Teresa Johnson37687f32016-04-23 04:30:47 +00004239}
4240
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004241// Write the specified module summary index to the given raw output stream,
Teresa Johnson403a7872015-10-04 14:33:43 +00004242// where it will be written in a new bitcode block. This is used when
Teresa Johnson84174c32016-05-10 13:48:23 +00004243// writing the combined index file for ThinLTO. When writing a subset of the
4244// index for a distributed backend, provide a \p ModuleToSummariesForIndex map.
4245void llvm::WriteIndexToFile(
4246 const ModuleSummaryIndex &Index, raw_ostream &Out,
Mehdi Aminicc1fe9b2016-08-19 06:06:18 +00004247 const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
Teresa Johnson403a7872015-10-04 14:33:43 +00004248 SmallVector<char, 0> Buffer;
4249 Buffer.reserve(256 * 1024);
4250
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00004251 BitcodeWriter Writer(Buffer);
4252 Writer.writeIndex(&Index, ModuleToSummariesForIndex);
4253 Writer.writeStrtab();
Teresa Johnson403a7872015-10-04 14:33:43 +00004254
4255 Out.write((char *)&Buffer.front(), Buffer.size());
4256}
Haojie Wang1dec57d2017-07-21 17:25:20 +00004257
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00004258namespace {
Eugene Zelenko975293f2017-09-07 23:28:24 +00004259
Haojie Wang1dec57d2017-07-21 17:25:20 +00004260/// Class to manage the bitcode writing for a thin link bitcode file.
4261class ThinLinkBitcodeWriter : public ModuleBitcodeWriterBase {
4262 /// ModHash is for use in ThinLTO incremental build, generated while writing
4263 /// the module bitcode file.
4264 const ModuleHash *ModHash;
4265
4266public:
Rafael Espindola6a86e252018-02-14 19:11:32 +00004267 ThinLinkBitcodeWriter(const Module &M, StringTableBuilder &StrtabBuilder,
Haojie Wang1dec57d2017-07-21 17:25:20 +00004268 BitstreamWriter &Stream,
4269 const ModuleSummaryIndex &Index,
4270 const ModuleHash &ModHash)
4271 : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
4272 /*ShouldPreserveUseListOrder=*/false, &Index),
4273 ModHash(&ModHash) {}
4274
4275 void write();
4276
4277private:
4278 void writeSimplifiedModuleInfo();
4279};
Eugene Zelenko975293f2017-09-07 23:28:24 +00004280
4281} // end anonymous namespace
Haojie Wang1dec57d2017-07-21 17:25:20 +00004282
4283// This function writes a simpilified module info for thin link bitcode file.
4284// It only contains the source file name along with the name(the offset and
4285// size in strtab) and linkage for global values. For the global value info
4286// entry, in order to keep linkage at offset 5, there are three zeros used
4287// as padding.
4288void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
4289 SmallVector<unsigned, 64> Vals;
4290 // Emit the module's source file name.
4291 {
4292 StringEncoding Bits = getStringEncoding(M.getSourceFileName());
4293 BitCodeAbbrevOp AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8);
4294 if (Bits == SE_Char6)
4295 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
4296 else if (Bits == SE_Fixed7)
4297 AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
4298
4299 // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4300 auto Abbv = std::make_shared<BitCodeAbbrev>();
4301 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_SOURCE_FILENAME));
4302 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
4303 Abbv->Add(AbbrevOpToUse);
4304 unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4305
4306 for (const auto P : M.getSourceFileName())
4307 Vals.push_back((unsigned char)P);
4308
4309 Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
4310 Vals.clear();
4311 }
4312
4313 // Emit the global variable information.
4314 for (const GlobalVariable &GV : M.globals()) {
4315 // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
4316 Vals.push_back(StrtabBuilder.add(GV.getName()));
4317 Vals.push_back(GV.getName().size());
4318 Vals.push_back(0);
4319 Vals.push_back(0);
4320 Vals.push_back(0);
4321 Vals.push_back(getEncodedLinkage(GV));
4322
4323 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals);
4324 Vals.clear();
4325 }
4326
4327 // Emit the function proto information.
4328 for (const Function &F : M) {
4329 // FUNCTION: [strtab offset, strtab size, 0, 0, 0, linkage]
4330 Vals.push_back(StrtabBuilder.add(F.getName()));
4331 Vals.push_back(F.getName().size());
4332 Vals.push_back(0);
4333 Vals.push_back(0);
4334 Vals.push_back(0);
4335 Vals.push_back(getEncodedLinkage(F));
4336
4337 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals);
4338 Vals.clear();
4339 }
4340
4341 // Emit the alias information.
4342 for (const GlobalAlias &A : M.aliases()) {
4343 // ALIAS: [strtab offset, strtab size, 0, 0, 0, linkage]
4344 Vals.push_back(StrtabBuilder.add(A.getName()));
4345 Vals.push_back(A.getName().size());
4346 Vals.push_back(0);
4347 Vals.push_back(0);
4348 Vals.push_back(0);
4349 Vals.push_back(getEncodedLinkage(A));
4350
4351 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals);
4352 Vals.clear();
4353 }
4354
4355 // Emit the ifunc information.
4356 for (const GlobalIFunc &I : M.ifuncs()) {
4357 // IFUNC: [strtab offset, strtab size, 0, 0, 0, linkage]
4358 Vals.push_back(StrtabBuilder.add(I.getName()));
4359 Vals.push_back(I.getName().size());
4360 Vals.push_back(0);
4361 Vals.push_back(0);
4362 Vals.push_back(0);
4363 Vals.push_back(getEncodedLinkage(I));
4364
4365 Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
4366 Vals.clear();
4367 }
4368}
4369
4370void ThinLinkBitcodeWriter::write() {
4371 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4372
4373 writeModuleVersion();
4374
4375 writeSimplifiedModuleInfo();
4376
4377 writePerModuleGlobalValueSummary();
4378
4379 // Write module hash.
4380 Stream.EmitRecord(bitc::MODULE_CODE_HASH, ArrayRef<uint32_t>(*ModHash));
4381
4382 Stream.ExitBlock();
4383}
4384
Rafael Espindola6a86e252018-02-14 19:11:32 +00004385void BitcodeWriter::writeThinLinkBitcode(const Module &M,
Haojie Wang1dec57d2017-07-21 17:25:20 +00004386 const ModuleSummaryIndex &Index,
4387 const ModuleHash &ModHash) {
4388 assert(!WroteStrtab);
4389
4390 // The Mods vector is used by irsymtab::build, which requires non-const
4391 // Modules in case it needs to materialize metadata. But the bitcode writer
4392 // requires that the module is materialized, so we can cast to non-const here,
4393 // after checking that it is in fact materialized.
Rafael Espindola6a86e252018-02-14 19:11:32 +00004394 assert(M.isMaterialized());
4395 Mods.push_back(const_cast<Module *>(&M));
Haojie Wang1dec57d2017-07-21 17:25:20 +00004396
4397 ThinLinkBitcodeWriter ThinLinkWriter(M, StrtabBuilder, *Stream, Index,
4398 ModHash);
4399 ThinLinkWriter.write();
4400}
4401
4402// Write the specified thin link bitcode file to the given raw output stream,
4403// where it will be written in a new bitcode block. This is used when
4404// writing the per-module index file for ThinLTO.
Rafael Espindola6a86e252018-02-14 19:11:32 +00004405void llvm::WriteThinLinkBitcodeToFile(const Module &M, raw_ostream &Out,
Haojie Wang1dec57d2017-07-21 17:25:20 +00004406 const ModuleSummaryIndex &Index,
4407 const ModuleHash &ModHash) {
4408 SmallVector<char, 0> Buffer;
4409 Buffer.reserve(256 * 1024);
4410
4411 BitcodeWriter Writer(Buffer);
4412 Writer.writeThinLinkBitcode(M, Index, ModHash);
4413 Writer.writeSymtab();
4414 Writer.writeStrtab();
4415
4416 Out.write((char *)&Buffer.front(), Buffer.size());
4417}