blob: ac72f69c76ee6e0cd8522a1ecd4ad9dbc31e01bd [file] [log] [blame]
Chris Lattner1314b992007-04-22 06:23:29 +00001//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
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 Lattner1314b992007-04-22 06:23:29 +00007//
8//===----------------------------------------------------------------------===//
Chris Lattner1314b992007-04-22 06:23:29 +00009
Benjamin Kramer0a446fd2015-03-01 21:28:53 +000010#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000011#include "llvm/ADT/SmallString.h"
12#include "llvm/ADT/SmallVector.h"
David Majnemer3087b222015-01-20 05:58:07 +000013#include "llvm/ADT/Triple.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000014#include "llvm/Bitcode/BitstreamReader.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000015#include "llvm/Bitcode/LLVMBitCodes.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000016#include "llvm/Bitcode/ReaderWriter.h"
Chandler Carruth91065212014-03-05 10:34:14 +000017#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/Constants.h"
Rafael Espindola0d68b4c2015-03-30 21:36:43 +000019#include "llvm/IR/DebugInfo.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000020#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/DerivedTypes.h"
Rafael Espindolad0b23be2015-01-10 00:07:30 +000022#include "llvm/IR/DiagnosticPrinter.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000023#include "llvm/IR/GVMaterializer.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/InlineAsm.h"
25#include "llvm/IR/IntrinsicInst.h"
Manman Ren209b17c2013-09-28 00:22:27 +000026#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Module.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000028#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/OperandTraits.h"
30#include "llvm/IR/Operator.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000031#include "llvm/IR/ValueHandle.h"
Teresa Johnson916495d2016-04-04 18:52:58 +000032#include "llvm/Support/CommandLine.h"
Derek Schuff8b2dcad2012-02-06 22:30:29 +000033#include "llvm/Support/DataStream.h"
Teresa Johnson916495d2016-04-04 18:52:58 +000034#include "llvm/Support/Debug.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000035#include "llvm/Support/ManagedStatic.h"
Chris Lattner08feb1e2007-04-24 04:04:35 +000036#include "llvm/Support/MathExtras.h"
Chris Lattner6694f602007-04-29 07:54:31 +000037#include "llvm/Support/MemoryBuffer.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000038#include "llvm/Support/raw_ostream.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000039#include <deque>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000040#include <utility>
Eugene Zelenko6ac3f732016-01-26 18:48:36 +000041
Chris Lattner1314b992007-04-22 06:23:29 +000042using namespace llvm;
43
Teresa Johnson916495d2016-04-04 18:52:58 +000044static cl::opt<bool> PrintSummaryGUIDs(
45 "print-summary-global-ids", cl::init(false), cl::Hidden,
46 cl::desc(
47 "Print the global id for each value when reading the module summary"));
48
Benjamin Kramercced8be2015-03-17 20:40:24 +000049namespace {
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +000050enum {
51 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
52};
53
Benjamin Kramercced8be2015-03-17 20:40:24 +000054class BitcodeReaderValueList {
55 std::vector<WeakVH> ValuePtrs;
56
Rafael Espindolacbdcb502015-06-15 20:55:37 +000057 /// As we resolve forward-referenced constants, we add information about them
58 /// to this vector. This allows us to resolve them in bulk instead of
59 /// resolving each reference at a time. See the code in
Benjamin Kramercced8be2015-03-17 20:40:24 +000060 /// ResolveConstantForwardRefs for more information about this.
61 ///
62 /// The key of this vector is the placeholder constant, the value is the slot
63 /// number that holds the resolved value.
64 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
65 ResolveConstantsTy ResolveConstants;
66 LLVMContext &Context;
67public:
68 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
69 ~BitcodeReaderValueList() {
70 assert(ResolveConstants.empty() && "Constants not resolved?");
71 }
72
73 // vector compatibility methods
74 unsigned size() const { return ValuePtrs.size(); }
75 void resize(unsigned N) { ValuePtrs.resize(N); }
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +000076 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
Benjamin Kramercced8be2015-03-17 20:40:24 +000077
78 void clear() {
79 assert(ResolveConstants.empty() && "Constants not resolved?");
80 ValuePtrs.clear();
81 }
82
83 Value *operator[](unsigned i) const {
84 assert(i < ValuePtrs.size());
85 return ValuePtrs[i];
86 }
87
88 Value *back() const { return ValuePtrs.back(); }
Duncan P. N. Exon Smith7457ecb2016-03-30 04:21:52 +000089 void pop_back() { ValuePtrs.pop_back(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +000090 bool empty() const { return ValuePtrs.empty(); }
91 void shrinkTo(unsigned N) {
92 assert(N <= size() && "Invalid shrinkTo request!");
93 ValuePtrs.resize(N);
94 }
95
96 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
David Majnemer8a1c45d2015-12-12 05:38:55 +000097 Value *getValueFwdRef(unsigned Idx, Type *Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +000098
David Majnemer8a1c45d2015-12-12 05:38:55 +000099 void assignValue(Value *V, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000100
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000101 /// Once all constants are read, this method bulk resolves any forward
102 /// references.
103 void resolveConstantForwardRefs();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000104};
105
Teresa Johnson61b406e2015-12-29 23:00:22 +0000106class BitcodeReaderMetadataList {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000107 unsigned NumFwdRefs;
108 bool AnyFwdRefs;
109 unsigned MinFwdRef;
110 unsigned MaxFwdRef;
Duncan P. N. Exon Smith3c406c22016-04-20 20:14:09 +0000111
112 /// Array of metadata references.
113 ///
114 /// Don't use std::vector here. Some versions of libc++ copy (instead of
115 /// move) on resize, and TrackingMDRef is very expensive to copy.
116 SmallVector<TrackingMDRef, 1> MetadataPtrs;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000117
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000118 /// Structures for resolving old type refs.
119 struct {
120 SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
121 SmallDenseMap<MDString *, DICompositeType *, 1> Final;
122 SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
Duncan P. N. Exon Smith69bdc8a2016-04-23 21:36:59 +0000123 SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000124 } OldTypeRefs;
125
Benjamin Kramercced8be2015-03-17 20:40:24 +0000126 LLVMContext &Context;
127public:
Teresa Johnson61b406e2015-12-29 23:00:22 +0000128 BitcodeReaderMetadataList(LLVMContext &C)
Teresa Johnson34702952015-12-21 15:38:13 +0000129 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
Benjamin Kramercced8be2015-03-17 20:40:24 +0000130
131 // vector compatibility methods
Teresa Johnson61b406e2015-12-29 23:00:22 +0000132 unsigned size() const { return MetadataPtrs.size(); }
133 void resize(unsigned N) { MetadataPtrs.resize(N); }
134 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
135 void clear() { MetadataPtrs.clear(); }
136 Metadata *back() const { return MetadataPtrs.back(); }
137 void pop_back() { MetadataPtrs.pop_back(); }
138 bool empty() const { return MetadataPtrs.empty(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000139
140 Metadata *operator[](unsigned i) const {
Teresa Johnson61b406e2015-12-29 23:00:22 +0000141 assert(i < MetadataPtrs.size());
142 return MetadataPtrs[i];
Benjamin Kramercced8be2015-03-17 20:40:24 +0000143 }
144
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000145 Metadata *lookup(unsigned I) const {
Duncan P. N. Exon Smithe9f85c42016-04-23 04:23:57 +0000146 if (I < MetadataPtrs.size())
147 return MetadataPtrs[I];
148 return nullptr;
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000149 }
150
Benjamin Kramercced8be2015-03-17 20:40:24 +0000151 void shrinkTo(unsigned N) {
152 assert(N <= size() && "Invalid shrinkTo request!");
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +0000153 assert(!AnyFwdRefs && "Unexpected forward refs");
Teresa Johnson61b406e2015-12-29 23:00:22 +0000154 MetadataPtrs.resize(N);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000155 }
156
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000157 /// Return the given metadata, creating a replaceable forward reference if
158 /// necessary.
Justin Bognerae341c62016-03-17 20:12:06 +0000159 Metadata *getMetadataFwdRef(unsigned Idx);
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000160
161 /// Return the the given metadata only if it is fully resolved.
162 ///
163 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
164 /// would give \c false.
165 Metadata *getMetadataIfResolved(unsigned Idx);
166
Justin Bognerae341c62016-03-17 20:12:06 +0000167 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000168 void assignValue(Metadata *MD, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000169 void tryToResolveCycles();
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +0000170 bool hasFwdRefs() const { return AnyFwdRefs; }
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000171
172 /// Upgrade a type that had an MDString reference.
173 void addTypeRef(MDString &UUID, DICompositeType &CT);
174
175 /// Upgrade a type that had an MDString reference.
176 Metadata *upgradeTypeRef(Metadata *MaybeUUID);
177
178 /// Upgrade a type ref array that may have MDString references.
179 Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
180
181private:
182 Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000183};
184
185class BitcodeReader : public GVMaterializer {
186 LLVMContext &Context;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000187 Module *TheModule = nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000188 std::unique_ptr<MemoryBuffer> Buffer;
189 std::unique_ptr<BitstreamReader> StreamFile;
190 BitstreamCursor Stream;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000191 // Next offset to start scanning for lazy parsing of function bodies.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000192 uint64_t NextUnreadBit = 0;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000193 // Last function offset found in the VST.
194 uint64_t LastFunctionBlockBit = 0;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000195 bool SeenValueSymbolTable = false;
Peter Collingbourne128a9762015-10-27 23:01:25 +0000196 uint64_t VSTOffset = 0;
Mehdi Amini5d303282015-10-26 18:37:00 +0000197 // Contains an arbitrary and optional string identifying the bitcode producer
198 std::string ProducerIdentification;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000199
200 std::vector<Type*> TypeList;
201 BitcodeReaderValueList ValueList;
Teresa Johnson61b406e2015-12-29 23:00:22 +0000202 BitcodeReaderMetadataList MetadataList;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000203 std::vector<Comdat *> ComdatList;
204 SmallVector<Instruction *, 64> InstructionList;
205
206 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000207 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > IndirectSymbolInits;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000208 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
209 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
David Majnemer7fddecc2015-06-17 20:52:32 +0000210 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000211
212 SmallVector<Instruction*, 64> InstsWithTBAATag;
213
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +0000214 bool HasSeenOldLoopTags = false;
215
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000216 /// The set of attributes by index. Index zero in the file is for null, and
217 /// is thus not represented here. As such all indices are off by one.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000218 std::vector<AttributeSet> MAttributes;
219
Karl Schimpf36440082015-08-31 16:43:55 +0000220 /// The set of attribute groups.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000221 std::map<unsigned, AttributeSet> MAttributeGroups;
222
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000223 /// While parsing a function body, this is a list of the basic blocks for the
224 /// function.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000225 std::vector<BasicBlock*> FunctionBBs;
226
227 // When reading the module header, this list is populated with functions that
228 // have bodies later in the file.
229 std::vector<Function*> FunctionsWithBodies;
230
231 // When intrinsic functions are encountered which require upgrading they are
232 // stored here with their replacement function.
Rafael Espindola4e721212015-07-02 16:22:40 +0000233 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000234 UpgradedIntrinsicMap UpgradedIntrinsics;
235
236 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
237 DenseMap<unsigned, unsigned> MDKindMap;
238
239 // Several operations happen after the module header has been read, but
240 // before function bodies are processed. This keeps track of whether
241 // we've done this yet.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000242 bool SeenFirstFunctionBody = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000243
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000244 /// When function bodies are initially scanned, this map contains info about
245 /// where to find deferred function body in the stream.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000246 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
247
248 /// When Metadata block is initially scanned when parsing the module, we may
249 /// choose to defer parsing of the metadata. This vector contains info about
250 /// which Metadata blocks are deferred.
251 std::vector<uint64_t> DeferredMetadataInfo;
252
253 /// These are basic blocks forward-referenced by block addresses. They are
254 /// inserted lazily into functions when they're loaded. The basic block ID is
255 /// its index into the vector.
256 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
257 std::deque<Function *> BasicBlockFwdRefQueue;
258
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000259 /// Indicates that we are using a new encoding for instruction operands where
260 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
261 /// instruction number, for a more compact encoding. Some instruction
262 /// operands are not relative to the instruction ID: basic block numbers, and
263 /// types. Once the old style function blocks have been phased out, we would
Benjamin Kramercced8be2015-03-17 20:40:24 +0000264 /// not need this flag.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000265 bool UseRelativeIDs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000266
267 /// True if all functions will be materialized, negating the need to process
268 /// (e.g.) blockaddress forward references.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000269 bool WillMaterializeAllForwardRefs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000270
Benjamin Kramercced8be2015-03-17 20:40:24 +0000271 /// True if any Metadata block has been materialized.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000272 bool IsMetadataMaterialized = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000273
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000274 bool StripDebugInfo = false;
275
Peter Collingbourned4bff302015-11-05 22:03:56 +0000276 /// Functions that need to be matched with subprograms when upgrading old
277 /// metadata.
278 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
279
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000280 std::vector<std::string> BundleTags;
281
Benjamin Kramercced8be2015-03-17 20:40:24 +0000282public:
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000283 std::error_code error(BitcodeError E, const Twine &Message);
284 std::error_code error(BitcodeError E);
285 std::error_code error(const Twine &Message);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000286
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000287 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context);
288 BitcodeReader(LLVMContext &Context);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000289 ~BitcodeReader() override { freeState(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000290
291 std::error_code materializeForwardReferencedFunctions();
292
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000293 void freeState();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000294
295 void releaseBuffer();
296
Benjamin Kramercced8be2015-03-17 20:40:24 +0000297 std::error_code materialize(GlobalValue *GV) override;
Rafael Espindola79753a02015-12-18 21:18:57 +0000298 std::error_code materializeModule() override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000299 std::vector<StructType *> getIdentifiedStructTypes() const override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000300
Rafael Espindola6ace6852015-06-15 21:02:49 +0000301 /// \brief Main interface to parsing a bitcode buffer.
302 /// \returns true if an error occurred.
Rafael Espindola1aabf982015-06-16 23:29:49 +0000303 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
304 Module *M,
Benjamin Kramercced8be2015-03-17 20:40:24 +0000305 bool ShouldLazyLoadMetadata = false);
306
Rafael Espindola6ace6852015-06-15 21:02:49 +0000307 /// \brief Cheap mechanism to just extract module triple
308 /// \returns true if an error occurred.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000309 ErrorOr<std::string> parseTriple();
310
Mehdi Amini3383ccc2015-11-09 02:46:41 +0000311 /// Cheap mechanism to just extract the identification block out of bitcode.
312 ErrorOr<std::string> parseIdentificationBlock();
313
Benjamin Kramercced8be2015-03-17 20:40:24 +0000314 static uint64_t decodeSignRotatedValue(uint64_t V);
315
316 /// Materialize any deferred Metadata block.
317 std::error_code materializeMetadata() override;
318
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000319 void setStripDebugInfo() override;
320
Benjamin Kramercced8be2015-03-17 20:40:24 +0000321private:
Mehdi Amini5d303282015-10-26 18:37:00 +0000322 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
323 // ProducerIdentification data member, and do some basic enforcement on the
324 // "epoch" encoded in the bitcode.
325 std::error_code parseBitcodeVersion();
326
Benjamin Kramercced8be2015-03-17 20:40:24 +0000327 std::vector<StructType *> IdentifiedStructTypes;
328 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
329 StructType *createIdentifiedStructType(LLVMContext &Context);
330
331 Type *getTypeByID(unsigned ID);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000332 Value *getFnValueByID(unsigned ID, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000333 if (Ty && Ty->isMetadataTy())
334 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
David Majnemer8a1c45d2015-12-12 05:38:55 +0000335 return ValueList.getValueFwdRef(ID, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000336 }
337 Metadata *getFnMetadataByID(unsigned ID) {
Justin Bognerae341c62016-03-17 20:12:06 +0000338 return MetadataList.getMetadataFwdRef(ID);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000339 }
340 BasicBlock *getBasicBlock(unsigned ID) const {
341 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
342 return FunctionBBs[ID];
343 }
344 AttributeSet getAttributes(unsigned i) const {
345 if (i-1 < MAttributes.size())
346 return MAttributes[i-1];
347 return AttributeSet();
348 }
349
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000350 /// Read a value/type pair out of the specified record from slot 'Slot'.
351 /// Increment Slot past the number of slots used in the record. Return true on
352 /// failure.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000353 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
354 unsigned InstNum, Value *&ResVal) {
355 if (Slot == Record.size()) return true;
356 unsigned ValNo = (unsigned)Record[Slot++];
357 // Adjust the ValNo, if it was encoded relative to the InstNum.
358 if (UseRelativeIDs)
359 ValNo = InstNum - ValNo;
360 if (ValNo < InstNum) {
361 // If this is not a forward reference, just return the value we already
362 // have.
363 ResVal = getFnValueByID(ValNo, nullptr);
364 return ResVal == nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000365 }
David Blaikiedbe6e0f2015-04-17 06:40:14 +0000366 if (Slot == Record.size())
367 return true;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000368
369 unsigned TypeNo = (unsigned)Record[Slot++];
370 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
371 return ResVal == nullptr;
372 }
373
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000374 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
375 /// past the number of slots used by the value in the record. Return true if
376 /// there is an error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000377 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000378 unsigned InstNum, Type *Ty, Value *&ResVal) {
379 if (getValue(Record, Slot, InstNum, Ty, ResVal))
Benjamin Kramercced8be2015-03-17 20:40:24 +0000380 return true;
381 // All values currently take a single record slot.
382 ++Slot;
383 return false;
384 }
385
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000386 /// Like popValue, but does not increment the Slot number.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000387 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000388 unsigned InstNum, Type *Ty, Value *&ResVal) {
389 ResVal = getValue(Record, Slot, InstNum, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000390 return ResVal == nullptr;
391 }
392
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000393 /// Version of getValue that returns ResVal directly, or 0 if there is an
394 /// error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000395 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000396 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000397 if (Slot == Record.size()) return nullptr;
398 unsigned ValNo = (unsigned)Record[Slot];
399 // Adjust the ValNo, if it was encoded relative to the InstNum.
400 if (UseRelativeIDs)
401 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000402 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000403 }
404
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000405 /// Like getValue, but decodes signed VBRs.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000406 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000407 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000408 if (Slot == Record.size()) return nullptr;
409 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
410 // Adjust the ValNo, if it was encoded relative to the InstNum.
411 if (UseRelativeIDs)
412 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000413 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000414 }
415
416 /// Converts alignment exponent (i.e. power of two (or zero)) to the
417 /// corresponding alignment to use. If alignment is too large, returns
418 /// a corresponding error code.
419 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000420 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
Teresa Johnson1493ad92015-10-10 14:18:36 +0000421 std::error_code parseModule(uint64_t ResumeBit,
422 bool ShouldLazyLoadMetadata = false);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000423 std::error_code parseAttributeBlock();
424 std::error_code parseAttributeGroupBlock();
425 std::error_code parseTypeTable();
426 std::error_code parseTypeTableBody();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000427 std::error_code parseOperandBundleTags();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000428
Teresa Johnsonff642b92015-09-17 20:12:00 +0000429 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
430 unsigned NameIndex, Triple &TT);
Peter Collingbourne128a9762015-10-27 23:01:25 +0000431 std::error_code parseValueSymbolTable(uint64_t Offset = 0);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000432 std::error_code parseConstants();
Teresa Johnson1493ad92015-10-10 14:18:36 +0000433 std::error_code rememberAndSkipFunctionBodies();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000434 std::error_code rememberAndSkipFunctionBody();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000435 /// Save the positions of the Metadata blocks and skip parsing the blocks.
436 std::error_code rememberAndSkipMetadata();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000437 std::error_code parseFunctionBody(Function *F);
438 std::error_code globalCleanup();
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000439 std::error_code resolveGlobalAndIndirectSymbolInits();
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +0000440 std::error_code parseMetadata(bool ModuleLevel = false);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +0000441 std::error_code parseMetadataStrings(ArrayRef<uint64_t> Record,
442 StringRef Blob,
443 unsigned &NextMetadataNo);
Teresa Johnson12545072015-11-15 02:00:09 +0000444 std::error_code parseMetadataKinds();
445 std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000446 std::error_code
447 parseGlobalObjectAttachment(GlobalObject &GO,
448 ArrayRef<uint64_t> Record);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000449 std::error_code parseMetadataAttachment(Function &F);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000450 ErrorOr<std::string> parseModuleTriple();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000451 std::error_code parseUseLists();
Rafael Espindola1aabf982015-06-16 23:29:49 +0000452 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000453 std::error_code initStreamFromBuffer();
Rafael Espindola1aabf982015-06-16 23:29:49 +0000454 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000455 std::error_code findFunctionInStream(
Benjamin Kramercced8be2015-03-17 20:40:24 +0000456 Function *F,
457 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
458};
Teresa Johnson403a7872015-10-04 14:33:43 +0000459
460/// Class to manage reading and parsing function summary index bitcode
461/// files/sections.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000462class ModuleSummaryIndexBitcodeReader {
Teresa Johnson403a7872015-10-04 14:33:43 +0000463 DiagnosticHandlerFunction DiagnosticHandler;
464
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000465 /// Eventually points to the module index built during parsing.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000466 ModuleSummaryIndex *TheIndex = nullptr;
Teresa Johnson403a7872015-10-04 14:33:43 +0000467
468 std::unique_ptr<MemoryBuffer> Buffer;
469 std::unique_ptr<BitstreamReader> StreamFile;
470 BitstreamCursor Stream;
471
Teresa Johnson403a7872015-10-04 14:33:43 +0000472 /// Used to indicate whether caller only wants to check for the presence
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000473 /// of the global value summary bitcode section. All blocks are skipped,
474 /// but the SeenGlobalValSummary boolean is set.
475 bool CheckGlobalValSummaryPresenceOnly = false;
Teresa Johnson403a7872015-10-04 14:33:43 +0000476
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000477 /// Indicates whether we have encountered a global value summary section
478 /// yet during parsing, used when checking if file contains global value
Teresa Johnson403a7872015-10-04 14:33:43 +0000479 /// summary section.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000480 bool SeenGlobalValSummary = false;
Teresa Johnson403a7872015-10-04 14:33:43 +0000481
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000482 /// Indicates whether we have already parsed the VST, used for error checking.
483 bool SeenValueSymbolTable = false;
484
485 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
486 /// Used to enable on-demand parsing of the VST.
487 uint64_t VSTOffset = 0;
488
489 // Map to save ValueId to GUID association that was recorded in the
490 // ValueSymbolTable. It is used after the VST is parsed to convert
491 // call graph edges read from the function summary from referencing
492 // callees by their ValueId to using the GUID instead, which is how
Teresa Johnson26ab5772016-03-15 00:04:37 +0000493 // they are recorded in the summary index being built.
Mehdi Aminiae64eaf2016-04-23 23:38:17 +0000494 // We save a second GUID which is the same as the first one, but ignoring the
495 // linkage, i.e. for value other than local linkage they are identical.
496 DenseMap<unsigned, std::pair<GlobalValue::GUID, GlobalValue::GUID>>
497 ValueIdToCallGraphGUIDMap;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000498
Teresa Johnson403a7872015-10-04 14:33:43 +0000499 /// Map populated during module path string table parsing, from the
500 /// module ID to a string reference owned by the index's module
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000501 /// path string table, used to correlate with combined index
Teresa Johnson403a7872015-10-04 14:33:43 +0000502 /// summary records.
503 DenseMap<uint64_t, StringRef> ModuleIdMap;
504
Teresa Johnsone1164de2016-02-10 21:55:02 +0000505 /// Original source file name recorded in a bitcode record.
506 std::string SourceFileName;
507
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000508public:
Teresa Johnson403a7872015-10-04 14:33:43 +0000509 std::error_code error(BitcodeError E, const Twine &Message);
510 std::error_code error(BitcodeError E);
511 std::error_code error(const Twine &Message);
512
Teresa Johnson26ab5772016-03-15 00:04:37 +0000513 ModuleSummaryIndexBitcodeReader(
514 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson6fb3f192016-04-22 01:52:00 +0000515 bool CheckGlobalValSummaryPresenceOnly = false);
Teresa Johnson26ab5772016-03-15 00:04:37 +0000516 ModuleSummaryIndexBitcodeReader(
Teresa Johnson6fb3f192016-04-22 01:52:00 +0000517 DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000518 bool CheckGlobalValSummaryPresenceOnly = false);
519 ~ModuleSummaryIndexBitcodeReader() { freeState(); }
Teresa Johnson403a7872015-10-04 14:33:43 +0000520
521 void freeState();
522
523 void releaseBuffer();
524
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000525 /// Check if the parser has encountered a summary section.
526 bool foundGlobalValSummary() { return SeenGlobalValSummary; }
Teresa Johnson403a7872015-10-04 14:33:43 +0000527
528 /// \brief Main interface to parsing a bitcode buffer.
529 /// \returns true if an error occurred.
530 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000531 ModuleSummaryIndex *I);
Teresa Johnson403a7872015-10-04 14:33:43 +0000532
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000533private:
Teresa Johnson403a7872015-10-04 14:33:43 +0000534 std::error_code parseModule();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000535 std::error_code parseValueSymbolTable(
536 uint64_t Offset,
537 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
Teresa Johnson403a7872015-10-04 14:33:43 +0000538 std::error_code parseEntireSummary();
539 std::error_code parseModuleStringTable();
540 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
541 std::error_code initStreamFromBuffer();
542 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +0000543 std::pair<GlobalValue::GUID, GlobalValue::GUID>
544 getGUIDFromValueId(unsigned ValueId);
Teresa Johnson403a7872015-10-04 14:33:43 +0000545};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000546} // end anonymous namespace
Benjamin Kramercced8be2015-03-17 20:40:24 +0000547
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000548BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
549 DiagnosticSeverity Severity,
550 const Twine &Msg)
551 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
552
553void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
554
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000555static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000556 std::error_code EC, const Twine &Message) {
557 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
558 DiagnosticHandler(DI);
559 return EC;
560}
561
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000562static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000563 std::error_code EC) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000564 return error(DiagnosticHandler, EC, EC.message());
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000565}
566
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000567static std::error_code error(LLVMContext &Context, std::error_code EC,
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000568 const Twine &Message) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000569 return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC,
570 Message);
571}
572
573static std::error_code error(LLVMContext &Context, std::error_code EC) {
574 return error(Context, EC, EC.message());
575}
576
577static std::error_code error(LLVMContext &Context, const Twine &Message) {
578 return error(Context, make_error_code(BitcodeError::CorruptedBitcode),
579 Message);
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000580}
581
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000582std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
Mehdi Amini5d303282015-10-26 18:37:00 +0000583 if (!ProducerIdentification.empty()) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000584 return ::error(Context, make_error_code(E),
Filipe Cabecinhasf3e167a2015-11-03 13:48:21 +0000585 Message + " (Producer: '" + ProducerIdentification +
586 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
Mehdi Amini5d303282015-10-26 18:37:00 +0000587 }
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000588 return ::error(Context, make_error_code(E), Message);
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000589}
590
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000591std::error_code BitcodeReader::error(const Twine &Message) {
Mehdi Amini5d303282015-10-26 18:37:00 +0000592 if (!ProducerIdentification.empty()) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000593 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
Filipe Cabecinhasf3e167a2015-11-03 13:48:21 +0000594 Message + " (Producer: '" + ProducerIdentification +
595 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
Mehdi Amini5d303282015-10-26 18:37:00 +0000596 }
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000597 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
598 Message);
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000599}
600
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000601std::error_code BitcodeReader::error(BitcodeError E) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000602 return ::error(Context, make_error_code(E));
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000603}
604
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000605BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context)
606 : Context(Context), Buffer(Buffer), ValueList(Context),
Teresa Johnson61b406e2015-12-29 23:00:22 +0000607 MetadataList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000608
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000609BitcodeReader::BitcodeReader(LLVMContext &Context)
610 : Context(Context), Buffer(nullptr), ValueList(Context),
Teresa Johnson61b406e2015-12-29 23:00:22 +0000611 MetadataList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000612
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000613std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
614 if (WillMaterializeAllForwardRefs)
615 return std::error_code();
616
617 // Prevent recursion.
618 WillMaterializeAllForwardRefs = true;
619
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000620 while (!BasicBlockFwdRefQueue.empty()) {
621 Function *F = BasicBlockFwdRefQueue.front();
622 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000623 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000624 if (!BasicBlockFwdRefs.count(F))
625 // Already materialized.
626 continue;
627
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000628 // Check for a function that isn't materializable to prevent an infinite
629 // loop. When parsing a blockaddress stored in a global variable, there
630 // isn't a trivial way to check if a function will have a body without a
631 // linear search through FunctionsWithBodies, so just check it here.
632 if (!F->isMaterializable())
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000633 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000634
635 // Try to materialize F.
Rafael Espindola5a52e6d2014-10-24 22:50:48 +0000636 if (std::error_code EC = materialize(F))
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000637 return EC;
Rafael Espindolab7993462012-01-02 07:49:53 +0000638 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000639 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000640
641 // Reset state.
642 WillMaterializeAllForwardRefs = false;
643 return std::error_code();
Rafael Espindolab7993462012-01-02 07:49:53 +0000644}
645
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000646void BitcodeReader::freeState() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000647 Buffer = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000648 std::vector<Type*>().swap(TypeList);
Chris Lattner9eeada92007-05-18 04:02:46 +0000649 ValueList.clear();
Teresa Johnson61b406e2015-12-29 23:00:22 +0000650 MetadataList.clear();
David Majnemerdad0a642014-06-27 18:19:56 +0000651 std::vector<Comdat *>().swap(ComdatList);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000652
Bill Wendlinge94d8432012-12-07 23:16:57 +0000653 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattner9eeada92007-05-18 04:02:46 +0000654 std::vector<BasicBlock*>().swap(FunctionBBs);
655 std::vector<Function*>().swap(FunctionsWithBodies);
656 DeferredFunctionInfo.clear();
Manman Ren4a9b0eb2015-03-13 19:24:30 +0000657 DeferredMetadataInfo.clear();
Dan Gohman43aa8f02010-07-20 21:42:28 +0000658 MDKindMap.clear();
Benjamin Kramer736a4fc2012-09-21 14:34:31 +0000659
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +0000660 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000661 BasicBlockFwdRefQueue.clear();
Chris Lattner6694f602007-04-29 07:54:31 +0000662}
663
Chris Lattnerfee5a372007-05-04 03:30:17 +0000664//===----------------------------------------------------------------------===//
665// Helper functions to implement forward reference resolution, etc.
666//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +0000667
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000668/// Convert a string from a record into an std::string, return true on failure.
669template <typename StrTy>
670static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattnerccaa4482007-04-23 21:26:05 +0000671 StrTy &Result) {
Chris Lattnere14cb882007-05-04 19:11:41 +0000672 if (Idx > Record.size())
Chris Lattner1314b992007-04-22 06:23:29 +0000673 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000674
Chris Lattnere14cb882007-05-04 19:11:41 +0000675 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
676 Result += (char)Record[i];
Chris Lattner1314b992007-04-22 06:23:29 +0000677 return false;
678}
679
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000680static bool hasImplicitComdat(size_t Val) {
681 switch (Val) {
682 default:
683 return false;
684 case 1: // Old WeakAnyLinkage
685 case 4: // Old LinkOnceAnyLinkage
686 case 10: // Old WeakODRLinkage
687 case 11: // Old LinkOnceODRLinkage
688 return true;
689 }
690}
691
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000692static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000693 switch (Val) {
694 default: // Map unknown/new linkages to external
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000695 case 0:
696 return GlobalValue::ExternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000697 case 2:
698 return GlobalValue::AppendingLinkage;
699 case 3:
700 return GlobalValue::InternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000701 case 5:
702 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
703 case 6:
704 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
705 case 7:
706 return GlobalValue::ExternalWeakLinkage;
707 case 8:
708 return GlobalValue::CommonLinkage;
709 case 9:
710 return GlobalValue::PrivateLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000711 case 12:
712 return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000713 case 13:
714 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
715 case 14:
716 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Rafael Espindolabec6af62015-01-08 15:39:50 +0000717 case 15:
718 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000719 case 1: // Old value with implicit comdat.
720 case 16:
721 return GlobalValue::WeakAnyLinkage;
722 case 10: // Old value with implicit comdat.
723 case 17:
724 return GlobalValue::WeakODRLinkage;
725 case 4: // Old value with implicit comdat.
726 case 18:
727 return GlobalValue::LinkOnceAnyLinkage;
728 case 11: // Old value with implicit comdat.
729 case 19:
730 return GlobalValue::LinkOnceODRLinkage;
Chris Lattner1314b992007-04-22 06:23:29 +0000731 }
732}
733
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000734// Decode the flags for GlobalValue in the summary
735static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
736 uint64_t Version) {
737 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
738 // like getDecodedLinkage() above. Any future change to the linkage enum and
739 // to getDecodedLinkage() will need to be taken into account here as above.
740 auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000741 RawFlags = RawFlags >> 4;
742 auto HasSection = RawFlags & 0x1; // bool
743 return GlobalValueSummary::GVFlags(Linkage, HasSection);
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000744}
745
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000746static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000747 switch (Val) {
748 default: // Map unknown visibilities to default.
749 case 0: return GlobalValue::DefaultVisibility;
750 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000751 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000752 }
753}
754
Nico Rieck7157bb72014-01-14 15:22:47 +0000755static GlobalValue::DLLStorageClassTypes
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000756getDecodedDLLStorageClass(unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000757 switch (Val) {
758 default: // Map unknown values to default.
759 case 0: return GlobalValue::DefaultStorageClass;
760 case 1: return GlobalValue::DLLImportStorageClass;
761 case 2: return GlobalValue::DLLExportStorageClass;
762 }
763}
764
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000765static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000766 switch (Val) {
767 case 0: return GlobalVariable::NotThreadLocal;
768 default: // Map unknown non-zero value to general dynamic.
769 case 1: return GlobalVariable::GeneralDynamicTLSModel;
770 case 2: return GlobalVariable::LocalDynamicTLSModel;
771 case 3: return GlobalVariable::InitialExecTLSModel;
772 case 4: return GlobalVariable::LocalExecTLSModel;
773 }
774}
775
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000776static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
777 switch (Val) {
778 default: // Map unknown to UnnamedAddr::None.
779 case 0: return GlobalVariable::UnnamedAddr::None;
780 case 1: return GlobalVariable::UnnamedAddr::Global;
781 case 2: return GlobalVariable::UnnamedAddr::Local;
782 }
783}
784
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000785static int getDecodedCastOpcode(unsigned Val) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000786 switch (Val) {
787 default: return -1;
788 case bitc::CAST_TRUNC : return Instruction::Trunc;
789 case bitc::CAST_ZEXT : return Instruction::ZExt;
790 case bitc::CAST_SEXT : return Instruction::SExt;
791 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
792 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
793 case bitc::CAST_UITOFP : return Instruction::UIToFP;
794 case bitc::CAST_SITOFP : return Instruction::SIToFP;
795 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
796 case bitc::CAST_FPEXT : return Instruction::FPExt;
797 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
798 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
799 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000800 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000801 }
802}
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000803
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000804static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000805 bool IsFP = Ty->isFPOrFPVectorTy();
806 // BinOps are only valid for int/fp or vector of int/fp types
807 if (!IsFP && !Ty->isIntOrIntVectorTy())
808 return -1;
809
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000810 switch (Val) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000811 default:
812 return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000813 case bitc::BINOP_ADD:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000814 return IsFP ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000815 case bitc::BINOP_SUB:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000816 return IsFP ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000817 case bitc::BINOP_MUL:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000818 return IsFP ? Instruction::FMul : Instruction::Mul;
819 case bitc::BINOP_UDIV:
820 return IsFP ? -1 : Instruction::UDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000821 case bitc::BINOP_SDIV:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000822 return IsFP ? Instruction::FDiv : Instruction::SDiv;
823 case bitc::BINOP_UREM:
824 return IsFP ? -1 : Instruction::URem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000825 case bitc::BINOP_SREM:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000826 return IsFP ? Instruction::FRem : Instruction::SRem;
827 case bitc::BINOP_SHL:
828 return IsFP ? -1 : Instruction::Shl;
829 case bitc::BINOP_LSHR:
830 return IsFP ? -1 : Instruction::LShr;
831 case bitc::BINOP_ASHR:
832 return IsFP ? -1 : Instruction::AShr;
833 case bitc::BINOP_AND:
834 return IsFP ? -1 : Instruction::And;
835 case bitc::BINOP_OR:
836 return IsFP ? -1 : Instruction::Or;
837 case bitc::BINOP_XOR:
838 return IsFP ? -1 : Instruction::Xor;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000839 }
840}
841
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000842static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000843 switch (Val) {
844 default: return AtomicRMWInst::BAD_BINOP;
845 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
846 case bitc::RMW_ADD: return AtomicRMWInst::Add;
847 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
848 case bitc::RMW_AND: return AtomicRMWInst::And;
849 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
850 case bitc::RMW_OR: return AtomicRMWInst::Or;
851 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
852 case bitc::RMW_MAX: return AtomicRMWInst::Max;
853 case bitc::RMW_MIN: return AtomicRMWInst::Min;
854 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
855 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
856 }
857}
858
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000859static AtomicOrdering getDecodedOrdering(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000860 switch (Val) {
JF Bastien800f87a2016-04-06 21:19:33 +0000861 case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
862 case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
863 case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
864 case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
865 case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
866 case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000867 default: // Map unknown orderings to sequentially-consistent.
JF Bastien800f87a2016-04-06 21:19:33 +0000868 case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000869 }
870}
871
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000872static SynchronizationScope getDecodedSynchScope(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000873 switch (Val) {
874 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
875 default: // Map unknown scopes to cross-thread.
876 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
877 }
878}
879
David Majnemerdad0a642014-06-27 18:19:56 +0000880static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
881 switch (Val) {
882 default: // Map unknown selection kinds to any.
883 case bitc::COMDAT_SELECTION_KIND_ANY:
884 return Comdat::Any;
885 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
886 return Comdat::ExactMatch;
887 case bitc::COMDAT_SELECTION_KIND_LARGEST:
888 return Comdat::Largest;
889 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
890 return Comdat::NoDuplicates;
891 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
892 return Comdat::SameSize;
893 }
894}
895
James Molloy88eb5352015-07-10 12:52:00 +0000896static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
897 FastMathFlags FMF;
898 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
899 FMF.setUnsafeAlgebra();
900 if (0 != (Val & FastMathFlags::NoNaNs))
901 FMF.setNoNaNs();
902 if (0 != (Val & FastMathFlags::NoInfs))
903 FMF.setNoInfs();
904 if (0 != (Val & FastMathFlags::NoSignedZeros))
905 FMF.setNoSignedZeros();
906 if (0 != (Val & FastMathFlags::AllowReciprocal))
907 FMF.setAllowReciprocal();
908 return FMF;
909}
910
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000911static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000912 switch (Val) {
913 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
914 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
915 }
916}
917
Gabor Greiff6caff662008-05-10 08:32:32 +0000918namespace llvm {
Chris Lattner1663cca2007-04-24 05:48:56 +0000919namespace {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000920/// \brief A class for maintaining the slot number definition
921/// as a placeholder for the actual definition for forward constants defs.
922class ConstantPlaceHolder : public ConstantExpr {
923 void operator=(const ConstantPlaceHolder &) = delete;
924
925public:
926 // allocate space for exactly one operand
927 void *operator new(size_t s) { return User::operator new(s, 1); }
928 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
Gabor Greiff6caff662008-05-10 08:32:32 +0000929 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000930 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
931 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000932
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000933 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
934 static bool classof(const Value *V) {
935 return isa<ConstantExpr>(V) &&
936 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
937 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000938
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000939 /// Provide fast operand accessors
940 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
941};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000942} // end anonymous namespace
Chris Lattner1663cca2007-04-24 05:48:56 +0000943
Chris Lattner2d8cd802009-03-31 22:55:09 +0000944// FIXME: can we inherit this from ConstantExpr?
Gabor Greiff6caff662008-05-10 08:32:32 +0000945template <>
Jay Foadc8adf5f2011-01-11 15:07:38 +0000946struct OperandTraits<ConstantPlaceHolder> :
947 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greiff6caff662008-05-10 08:32:32 +0000948};
Richard Trieue3d126c2014-11-21 02:42:08 +0000949DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000950} // end namespace llvm
Gabor Greiff6caff662008-05-10 08:32:32 +0000951
David Majnemer8a1c45d2015-12-12 05:38:55 +0000952void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000953 if (Idx == size()) {
954 push_back(V);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000955 return;
Chris Lattner2d8cd802009-03-31 22:55:09 +0000956 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000957
Chris Lattner2d8cd802009-03-31 22:55:09 +0000958 if (Idx >= size())
959 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000960
Chris Lattner2d8cd802009-03-31 22:55:09 +0000961 WeakVH &OldV = ValuePtrs[Idx];
Craig Topper2617dcc2014-04-15 06:32:26 +0000962 if (!OldV) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000963 OldV = V;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000964 return;
Chris Lattner2d8cd802009-03-31 22:55:09 +0000965 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000966
Chris Lattner2d8cd802009-03-31 22:55:09 +0000967 // Handle constants and non-constants (e.g. instrs) differently for
968 // efficiency.
969 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
970 ResolveConstants.push_back(std::make_pair(PHC, Idx));
971 OldV = V;
972 } else {
973 // If there was a forward reference to this value, replace it.
974 Value *PrevVal = OldV;
975 OldV->replaceAllUsesWith(V);
976 delete PrevVal;
Gabor Greiff6caff662008-05-10 08:32:32 +0000977 }
978}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000979
Chris Lattner1663cca2007-04-24 05:48:56 +0000980Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattner229907c2011-07-18 04:54:35 +0000981 Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000982 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000983 resize(Idx + 1);
Chris Lattner1663cca2007-04-24 05:48:56 +0000984
Chris Lattner2d8cd802009-03-31 22:55:09 +0000985 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhas6a92a3f2015-05-27 01:05:40 +0000986 if (Ty != V->getType())
987 report_fatal_error("Type mismatch in constant table!");
Chris Lattner83930552007-05-01 07:01:57 +0000988 return cast<Constant>(V);
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000989 }
Chris Lattner1663cca2007-04-24 05:48:56 +0000990
991 // Create and return a placeholder, which will later be RAUW'd.
Owen Andersone9f98042009-07-07 20:18:58 +0000992 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000993 ValuePtrs[Idx] = C;
Chris Lattner1663cca2007-04-24 05:48:56 +0000994 return C;
995}
996
David Majnemer8a1c45d2015-12-12 05:38:55 +0000997Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Filipe Cabecinhasbad07792015-04-30 00:52:42 +0000998 // Bail out for a clearly invalid value. This would make us call resize(0)
999 if (Idx == UINT_MAX)
1000 return nullptr;
1001
Chris Lattner2d8cd802009-03-31 22:55:09 +00001002 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +00001003 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001004
Chris Lattner2d8cd802009-03-31 22:55:09 +00001005 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhasb435d0f2015-04-28 20:18:47 +00001006 // If the types don't match, it's invalid.
1007 if (Ty && Ty != V->getType())
1008 return nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +00001009 return V;
Chris Lattner83930552007-05-01 07:01:57 +00001010 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001011
Chris Lattner1fc27f02007-05-02 05:16:49 +00001012 // No type specified, must be invalid reference.
Craig Topper2617dcc2014-04-15 06:32:26 +00001013 if (!Ty) return nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001014
Chris Lattner83930552007-05-01 07:01:57 +00001015 // Create and return a placeholder, which will later be RAUW'd.
David Majnemer8a1c45d2015-12-12 05:38:55 +00001016 Value *V = new Argument(Ty);
Chris Lattner2d8cd802009-03-31 22:55:09 +00001017 ValuePtrs[Idx] = V;
Chris Lattner83930552007-05-01 07:01:57 +00001018 return V;
1019}
1020
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001021/// Once all constants are read, this method bulk resolves any forward
1022/// references. The idea behind this is that we sometimes get constants (such
1023/// as large arrays) which reference *many* forward ref constants. Replacing
1024/// each of these causes a lot of thrashing when building/reuniquing the
1025/// constant. Instead of doing this, we look at all the uses and rewrite all
1026/// the place holders at once for any constant that uses a placeholder.
1027void BitcodeReaderValueList::resolveConstantForwardRefs() {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001028 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattner74429932008-08-21 02:34:16 +00001029 // binary search.
1030 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001031
Chris Lattner74429932008-08-21 02:34:16 +00001032 SmallVector<Constant*, 64> NewOps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001033
Chris Lattner74429932008-08-21 02:34:16 +00001034 while (!ResolveConstants.empty()) {
Chris Lattner2d8cd802009-03-31 22:55:09 +00001035 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattner74429932008-08-21 02:34:16 +00001036 Constant *Placeholder = ResolveConstants.back().first;
1037 ResolveConstants.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001038
Chris Lattner74429932008-08-21 02:34:16 +00001039 // Loop over all users of the placeholder, updating them to reference the
1040 // new value. If they reference more than one placeholder, update them all
1041 // at once.
1042 while (!Placeholder->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001043 auto UI = Placeholder->user_begin();
Gabor Greif2c0ab482010-07-09 16:01:21 +00001044 User *U = *UI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001045
Chris Lattner74429932008-08-21 02:34:16 +00001046 // If the using object isn't uniqued, just update the operands. This
1047 // handles instructions and initializers for global variables.
Gabor Greif2c0ab482010-07-09 16:01:21 +00001048 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattner479c5d92008-08-21 17:31:45 +00001049 UI.getUse().set(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +00001050 continue;
1051 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001052
Chris Lattner74429932008-08-21 02:34:16 +00001053 // Otherwise, we have a constant that uses the placeholder. Replace that
1054 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greif2c0ab482010-07-09 16:01:21 +00001055 Constant *UserC = cast<Constant>(U);
Chris Lattner74429932008-08-21 02:34:16 +00001056 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
1057 I != E; ++I) {
1058 Value *NewOp;
1059 if (!isa<ConstantPlaceHolder>(*I)) {
1060 // Not a placeholder reference.
1061 NewOp = *I;
1062 } else if (*I == Placeholder) {
1063 // Common case is that it just references this one placeholder.
1064 NewOp = RealVal;
1065 } else {
1066 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001067 ResolveConstantsTy::iterator It =
1068 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattner74429932008-08-21 02:34:16 +00001069 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1070 0));
1071 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner2d8cd802009-03-31 22:55:09 +00001072 NewOp = operator[](It->second);
Chris Lattner74429932008-08-21 02:34:16 +00001073 }
1074
1075 NewOps.push_back(cast<Constant>(NewOp));
1076 }
1077
1078 // Make the new constant.
1079 Constant *NewC;
1080 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad83be3612011-06-22 09:24:39 +00001081 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001082 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnercc19efa2011-06-20 04:01:31 +00001083 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001084 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner69229312011-02-15 00:14:00 +00001085 NewC = ConstantVector::get(NewOps);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001086 } else {
1087 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foad5c984e562011-04-13 13:46:01 +00001088 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001089 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001090
Chris Lattner74429932008-08-21 02:34:16 +00001091 UserC->replaceAllUsesWith(NewC);
1092 UserC->destroyConstant();
1093 NewOps.clear();
1094 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001095
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001096 // Update all ValueHandles, they should be the only users at this point.
1097 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +00001098 delete Placeholder;
1099 }
1100}
1101
Teresa Johnson61b406e2015-12-29 23:00:22 +00001102void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +00001103 if (Idx == size()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001104 push_back(MD);
Devang Patel05eb6172009-08-04 06:00:18 +00001105 return;
1106 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001107
Devang Patel05eb6172009-08-04 06:00:18 +00001108 if (Idx >= size())
1109 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001110
Teresa Johnson61b406e2015-12-29 23:00:22 +00001111 TrackingMDRef &OldMD = MetadataPtrs[Idx];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001112 if (!OldMD) {
1113 OldMD.reset(MD);
Devang Patel05eb6172009-08-04 06:00:18 +00001114 return;
1115 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001116
Devang Patel05eb6172009-08-04 06:00:18 +00001117 // If there was a forward reference to this value, replace it.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +00001118 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001119 PrevMD->replaceAllUsesWith(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001120 --NumFwdRefs;
Devang Patel05eb6172009-08-04 06:00:18 +00001121}
1122
Justin Bognerae341c62016-03-17 20:12:06 +00001123Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +00001124 if (Idx >= size())
1125 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001126
Teresa Johnson61b406e2015-12-29 23:00:22 +00001127 if (Metadata *MD = MetadataPtrs[Idx])
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001128 return MD;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001129
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001130 // Track forward refs to be resolved later.
1131 if (AnyFwdRefs) {
1132 MinFwdRef = std::min(MinFwdRef, Idx);
1133 MaxFwdRef = std::max(MaxFwdRef, Idx);
1134 } else {
1135 AnyFwdRefs = true;
1136 MinFwdRef = MaxFwdRef = Idx;
1137 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001138 ++NumFwdRefs;
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001139
1140 // Create and return a placeholder, which will later be RAUW'd.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +00001141 Metadata *MD = MDNode::getTemporary(Context, None).release();
Teresa Johnson61b406e2015-12-29 23:00:22 +00001142 MetadataPtrs[Idx].reset(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001143 return MD;
1144}
1145
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00001146Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
1147 Metadata *MD = lookup(Idx);
1148 if (auto *N = dyn_cast_or_null<MDNode>(MD))
1149 if (!N->isResolved())
1150 return nullptr;
1151 return MD;
1152}
1153
Justin Bognerae341c62016-03-17 20:12:06 +00001154MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
1155 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
1156}
1157
Teresa Johnson61b406e2015-12-29 23:00:22 +00001158void BitcodeReaderMetadataList::tryToResolveCycles() {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001159 if (NumFwdRefs)
1160 // Still forward references... can't resolve cycles.
1161 return;
1162
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00001163 bool DidReplaceTypeRefs = false;
1164
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001165 // Give up on finding a full definition for any forward decls that remain.
1166 for (const auto &Ref : OldTypeRefs.FwdDecls)
1167 OldTypeRefs.Final.insert(Ref);
1168 OldTypeRefs.FwdDecls.clear();
1169
1170 // Upgrade from old type ref arrays. In strange cases, this could add to
1171 // OldTypeRefs.Unknown.
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00001172 for (const auto &Array : OldTypeRefs.Arrays) {
1173 DidReplaceTypeRefs = true;
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001174 Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00001175 }
1176 OldTypeRefs.Arrays.clear();
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001177
1178 // Replace old string-based type refs with the resolved node, if possible.
1179 // If we haven't seen the node, leave it to the verifier to complain about
1180 // the invalid string reference.
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00001181 for (const auto &Ref : OldTypeRefs.Unknown) {
1182 DidReplaceTypeRefs = true;
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001183 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
1184 Ref.second->replaceAllUsesWith(CT);
1185 else
1186 Ref.second->replaceAllUsesWith(Ref.first);
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00001187 }
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001188 OldTypeRefs.Unknown.clear();
1189
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00001190 // Make sure all the upgraded types are resolved.
1191 if (DidReplaceTypeRefs) {
1192 AnyFwdRefs = true;
1193 MinFwdRef = 0;
1194 MaxFwdRef = MetadataPtrs.size() - 1;
1195 }
1196
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001197 if (!AnyFwdRefs)
1198 // Nothing to do.
1199 return;
1200
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001201 // Resolve any cycles.
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001202 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
Teresa Johnson61b406e2015-12-29 23:00:22 +00001203 auto &MD = MetadataPtrs[I];
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +00001204 auto *N = dyn_cast_or_null<MDNode>(MD);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +00001205 if (!N)
1206 continue;
1207
1208 assert(!N->isTemporary() && "Unexpected forward reference");
1209 N->resolveCycles();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001210 }
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001211
1212 // Make sure we return early again until there's another forward ref.
1213 AnyFwdRefs = false;
Devang Patel05eb6172009-08-04 06:00:18 +00001214}
Chris Lattner1314b992007-04-22 06:23:29 +00001215
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001216void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
1217 DICompositeType &CT) {
1218 assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
1219 if (CT.isForwardDecl())
1220 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
1221 else
1222 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
1223}
1224
1225Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
1226 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
1227 if (LLVM_LIKELY(!UUID))
1228 return MaybeUUID;
1229
1230 if (auto *CT = OldTypeRefs.Final.lookup(UUID))
1231 return CT;
1232
1233 auto &Ref = OldTypeRefs.Unknown[UUID];
1234 if (!Ref)
1235 Ref = MDNode::getTemporary(Context, None);
1236 return Ref.get();
1237}
1238
1239Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
1240 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
1241 if (!Tuple || Tuple->isDistinct())
1242 return MaybeTuple;
1243
1244 // Look through the array immediately if possible.
1245 if (!Tuple->isTemporary())
1246 return resolveTypeRefArray(Tuple);
1247
1248 // Create and return a placeholder to use for now. Eventually
1249 // resolveTypeRefArrays() will be resolve this forward reference.
Duncan P. N. Exon Smithc3f89972016-06-09 20:46:33 +00001250 OldTypeRefs.Arrays.emplace_back(
1251 std::piecewise_construct, std::forward_as_tuple(Tuple),
1252 std::forward_as_tuple(MDTuple::getTemporary(Context, None)));
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001253 return OldTypeRefs.Arrays.back().second.get();
1254}
1255
1256Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
1257 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
1258 if (!Tuple || Tuple->isDistinct())
1259 return MaybeTuple;
1260
1261 // Look through the DITypeRefArray, upgrading each DITypeRef.
1262 SmallVector<Metadata *, 32> Ops;
1263 Ops.reserve(Tuple->getNumOperands());
1264 for (Metadata *MD : Tuple->operands())
1265 Ops.push_back(upgradeTypeRef(MD));
1266
1267 return MDTuple::get(Context, Ops);
1268}
1269
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001270Type *BitcodeReader::getTypeByID(unsigned ID) {
1271 // The type table size is always specified correctly.
1272 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +00001273 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +00001274
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001275 if (Type *Ty = TypeList[ID])
1276 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001277
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001278 // If we have a forward reference, the only possible case is when it is to a
1279 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001280 return TypeList[ID] = createIdentifiedStructType(Context);
1281}
1282
1283StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1284 StringRef Name) {
1285 auto *Ret = StructType::create(Context, Name);
1286 IdentifiedStructTypes.push_back(Ret);
1287 return Ret;
1288}
1289
1290StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1291 auto *Ret = StructType::create(Context);
1292 IdentifiedStructTypes.push_back(Ret);
1293 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +00001294}
1295
Chris Lattnerfee5a372007-05-04 03:30:17 +00001296//===----------------------------------------------------------------------===//
1297// Functions for parsing blocks from the bitcode file
1298//===----------------------------------------------------------------------===//
1299
Bill Wendling56aeccc2013-02-04 23:32:23 +00001300
1301/// \brief This fills an AttrBuilder object with the LLVM attributes that have
1302/// been decoded from the given integer. This function must stay in sync with
1303/// 'encodeLLVMAttributesForBitcode'.
1304static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1305 uint64_t EncodedAttrs) {
1306 // FIXME: Remove in 4.0.
1307
1308 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1309 // the bits above 31 down by 11 bits.
1310 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1311 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1312 "Alignment must be a power of two.");
1313
1314 if (Alignment)
1315 B.addAlignmentAttr(Alignment);
Kostya Serebryanyd688bab2013-02-11 08:13:54 +00001316 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
Bill Wendling56aeccc2013-02-04 23:32:23 +00001317 (EncodedAttrs & 0xffff));
1318}
1319
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001320std::error_code BitcodeReader::parseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001321 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001322 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001323
Devang Patela05633e2008-09-26 22:53:05 +00001324 if (!MAttributes.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001325 return error("Invalid multiple blocks");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001326
Chris Lattnerfee5a372007-05-04 03:30:17 +00001327 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001328
Bill Wendling71173cb2013-01-27 00:36:48 +00001329 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001330
Chris Lattnerfee5a372007-05-04 03:30:17 +00001331 // Read all the records.
1332 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001333 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001334
Chris Lattner27d38752013-01-20 02:13:19 +00001335 switch (Entry.Kind) {
1336 case BitstreamEntry::SubBlock: // Handled for us already.
1337 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001338 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001339 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001340 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001341 case BitstreamEntry::Record:
1342 // The interesting case.
1343 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001344 }
Joe Abbey97b7a172013-02-06 22:14:06 +00001345
Chris Lattnerfee5a372007-05-04 03:30:17 +00001346 // Read a record.
1347 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001348 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +00001349 default: // Default behavior: ignore.
1350 break;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001351 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1352 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +00001353 if (Record.size() & 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001354 return error("Invalid record");
Chris Lattnerfee5a372007-05-04 03:30:17 +00001355
Chris Lattnerfee5a372007-05-04 03:30:17 +00001356 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +00001357 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001358 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling60011b82013-01-29 01:43:29 +00001359 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +00001360 }
Devang Patela05633e2008-09-26 22:53:05 +00001361
Bill Wendlinge94d8432012-12-07 23:16:57 +00001362 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +00001363 Attrs.clear();
1364 break;
1365 }
Bill Wendling0dc08912013-02-12 08:13:50 +00001366 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1367 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1368 Attrs.push_back(MAttributeGroups[Record[i]]);
1369
1370 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1371 Attrs.clear();
1372 break;
1373 }
Duncan Sands04eb67e2007-11-20 14:09:29 +00001374 }
Chris Lattnerfee5a372007-05-04 03:30:17 +00001375 }
1376}
1377
Reid Klecknere9f36af2013-11-12 01:31:00 +00001378// Returns Attribute::None on unrecognized codes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001379static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
Reid Klecknere9f36af2013-11-12 01:31:00 +00001380 switch (Code) {
1381 default:
1382 return Attribute::None;
1383 case bitc::ATTR_KIND_ALIGNMENT:
1384 return Attribute::Alignment;
1385 case bitc::ATTR_KIND_ALWAYS_INLINE:
1386 return Attribute::AlwaysInline;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001387 case bitc::ATTR_KIND_ARGMEMONLY:
1388 return Attribute::ArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001389 case bitc::ATTR_KIND_BUILTIN:
1390 return Attribute::Builtin;
1391 case bitc::ATTR_KIND_BY_VAL:
1392 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +00001393 case bitc::ATTR_KIND_IN_ALLOCA:
1394 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001395 case bitc::ATTR_KIND_COLD:
1396 return Attribute::Cold;
Owen Anderson85fa7d52015-05-26 23:48:40 +00001397 case bitc::ATTR_KIND_CONVERGENT:
1398 return Attribute::Convergent;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001399 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1400 return Attribute::InaccessibleMemOnly;
1401 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1402 return Attribute::InaccessibleMemOrArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001403 case bitc::ATTR_KIND_INLINE_HINT:
1404 return Attribute::InlineHint;
1405 case bitc::ATTR_KIND_IN_REG:
1406 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +00001407 case bitc::ATTR_KIND_JUMP_TABLE:
1408 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001409 case bitc::ATTR_KIND_MIN_SIZE:
1410 return Attribute::MinSize;
1411 case bitc::ATTR_KIND_NAKED:
1412 return Attribute::Naked;
1413 case bitc::ATTR_KIND_NEST:
1414 return Attribute::Nest;
1415 case bitc::ATTR_KIND_NO_ALIAS:
1416 return Attribute::NoAlias;
1417 case bitc::ATTR_KIND_NO_BUILTIN:
1418 return Attribute::NoBuiltin;
1419 case bitc::ATTR_KIND_NO_CAPTURE:
1420 return Attribute::NoCapture;
1421 case bitc::ATTR_KIND_NO_DUPLICATE:
1422 return Attribute::NoDuplicate;
1423 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1424 return Attribute::NoImplicitFloat;
1425 case bitc::ATTR_KIND_NO_INLINE:
1426 return Attribute::NoInline;
James Molloye6f87ca2015-11-06 10:32:53 +00001427 case bitc::ATTR_KIND_NO_RECURSE:
1428 return Attribute::NoRecurse;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001429 case bitc::ATTR_KIND_NON_LAZY_BIND:
1430 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001431 case bitc::ATTR_KIND_NON_NULL:
1432 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001433 case bitc::ATTR_KIND_DEREFERENCEABLE:
1434 return Attribute::Dereferenceable;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001435 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1436 return Attribute::DereferenceableOrNull;
George Burgess IV278199f2016-04-12 01:05:35 +00001437 case bitc::ATTR_KIND_ALLOC_SIZE:
1438 return Attribute::AllocSize;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001439 case bitc::ATTR_KIND_NO_RED_ZONE:
1440 return Attribute::NoRedZone;
1441 case bitc::ATTR_KIND_NO_RETURN:
1442 return Attribute::NoReturn;
1443 case bitc::ATTR_KIND_NO_UNWIND:
1444 return Attribute::NoUnwind;
1445 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1446 return Attribute::OptimizeForSize;
1447 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1448 return Attribute::OptimizeNone;
1449 case bitc::ATTR_KIND_READ_NONE:
1450 return Attribute::ReadNone;
1451 case bitc::ATTR_KIND_READ_ONLY:
1452 return Attribute::ReadOnly;
1453 case bitc::ATTR_KIND_RETURNED:
1454 return Attribute::Returned;
1455 case bitc::ATTR_KIND_RETURNS_TWICE:
1456 return Attribute::ReturnsTwice;
1457 case bitc::ATTR_KIND_S_EXT:
1458 return Attribute::SExt;
1459 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1460 return Attribute::StackAlignment;
1461 case bitc::ATTR_KIND_STACK_PROTECT:
1462 return Attribute::StackProtect;
1463 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1464 return Attribute::StackProtectReq;
1465 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1466 return Attribute::StackProtectStrong;
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001467 case bitc::ATTR_KIND_SAFESTACK:
1468 return Attribute::SafeStack;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001469 case bitc::ATTR_KIND_STRUCT_RET:
1470 return Attribute::StructRet;
1471 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1472 return Attribute::SanitizeAddress;
1473 case bitc::ATTR_KIND_SANITIZE_THREAD:
1474 return Attribute::SanitizeThread;
1475 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1476 return Attribute::SanitizeMemory;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001477 case bitc::ATTR_KIND_SWIFT_ERROR:
1478 return Attribute::SwiftError;
Manman Renf46262e2016-03-29 17:37:21 +00001479 case bitc::ATTR_KIND_SWIFT_SELF:
1480 return Attribute::SwiftSelf;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001481 case bitc::ATTR_KIND_UW_TABLE:
1482 return Attribute::UWTable;
1483 case bitc::ATTR_KIND_Z_EXT:
1484 return Attribute::ZExt;
1485 }
1486}
1487
JF Bastien30bf96b2015-02-22 19:32:03 +00001488std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1489 unsigned &Alignment) {
1490 // Note: Alignment in bitcode files is incremented by 1, so that zero
1491 // can be used for default alignment.
1492 if (Exponent > Value::MaxAlignmentExponent + 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001493 return error("Invalid alignment value");
JF Bastien30bf96b2015-02-22 19:32:03 +00001494 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1495 return std::error_code();
1496}
1497
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001498std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001499 Attribute::AttrKind *Kind) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001500 *Kind = getAttrFromCode(Code);
Reid Klecknere9f36af2013-11-12 01:31:00 +00001501 if (*Kind == Attribute::None)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001502 return error(BitcodeError::CorruptedBitcode,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001503 "Unknown attribute kind (" + Twine(Code) + ")");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001504 return std::error_code();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001505}
1506
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001507std::error_code BitcodeReader::parseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +00001508 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001509 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001510
1511 if (!MAttributeGroups.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001512 return error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +00001513
1514 SmallVector<uint64_t, 64> Record;
1515
1516 // Read all the records.
1517 while (1) {
1518 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1519
1520 switch (Entry.Kind) {
1521 case BitstreamEntry::SubBlock: // Handled for us already.
1522 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001523 return error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +00001524 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001525 return std::error_code();
Bill Wendlingba629332013-02-10 23:24:25 +00001526 case BitstreamEntry::Record:
1527 // The interesting case.
1528 break;
1529 }
1530
1531 // Read a record.
1532 Record.clear();
1533 switch (Stream.readRecord(Entry.ID, Record)) {
1534 default: // Default behavior: ignore.
1535 break;
1536 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1537 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001538 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001539
Bill Wendlinge46707e2013-02-11 22:32:29 +00001540 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +00001541 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1542
1543 AttrBuilder B;
1544 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1545 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001546 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001547 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001548 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001549
1550 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +00001551 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001552 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001553 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001554 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001555 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001556 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001557 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001558 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001559 else if (Kind == Attribute::Dereferenceable)
1560 B.addDereferenceableAttr(Record[++i]);
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001561 else if (Kind == Attribute::DereferenceableOrNull)
1562 B.addDereferenceableOrNullAttr(Record[++i]);
George Burgess IV278199f2016-04-12 01:05:35 +00001563 else if (Kind == Attribute::AllocSize)
1564 B.addAllocSizeAttrFromRawRepr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +00001565 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +00001566 assert((Record[i] == 3 || Record[i] == 4) &&
1567 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +00001568 bool HasValue = (Record[i++] == 4);
1569 SmallString<64> KindStr;
1570 SmallString<64> ValStr;
1571
1572 while (Record[i] != 0 && i != e)
1573 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001574 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001575
1576 if (HasValue) {
1577 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +00001578 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +00001579 while (Record[i] != 0 && i != e)
1580 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001581 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001582 }
1583
1584 B.addAttribute(KindStr.str(), ValStr.str());
1585 }
1586 }
1587
Bill Wendlinge46707e2013-02-11 22:32:29 +00001588 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +00001589 break;
1590 }
1591 }
1592 }
1593}
1594
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001595std::error_code BitcodeReader::parseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001596 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001597 return error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +00001598
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001599 return parseTypeTableBody();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001600}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001601
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001602std::error_code BitcodeReader::parseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +00001603 if (!TypeList.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001604 return error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +00001605
1606 SmallVector<uint64_t, 64> Record;
1607 unsigned NumRecords = 0;
1608
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001609 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +00001610
Chris Lattner1314b992007-04-22 06:23:29 +00001611 // Read all the records for this type table.
1612 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001613 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001614
Chris Lattner27d38752013-01-20 02:13:19 +00001615 switch (Entry.Kind) {
1616 case BitstreamEntry::SubBlock: // Handled for us already.
1617 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001618 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001619 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +00001620 if (NumRecords != TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001621 return error("Malformed block");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001622 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001623 case BitstreamEntry::Record:
1624 // The interesting case.
1625 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001626 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001627
Chris Lattner1314b992007-04-22 06:23:29 +00001628 // Read a record.
1629 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001630 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001631 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001632 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001633 return error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +00001634 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1635 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1636 // type list. This allows us to reserve space.
1637 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001638 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001639 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001640 continue;
Chris Lattner1314b992007-04-22 06:23:29 +00001641 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +00001642 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001643 break;
Dan Gohman518cda42011-12-17 00:04:22 +00001644 case bitc::TYPE_CODE_HALF: // HALF
1645 ResultTy = Type::getHalfTy(Context);
1646 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001647 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +00001648 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001649 break;
1650 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +00001651 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001652 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001653 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +00001654 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001655 break;
1656 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001657 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001658 break;
1659 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001660 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001661 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001662 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +00001663 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001664 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001665 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +00001666 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001667 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +00001668 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1669 ResultTy = Type::getX86_MMXTy(Context);
1670 break;
David Majnemerb611e3f2015-08-14 05:09:07 +00001671 case bitc::TYPE_CODE_TOKEN: // TOKEN
1672 ResultTy = Type::getTokenTy(Context);
1673 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001674 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
Chris Lattner1314b992007-04-22 06:23:29 +00001675 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001676 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001677
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001678 uint64_t NumBits = Record[0];
1679 if (NumBits < IntegerType::MIN_INT_BITS ||
1680 NumBits > IntegerType::MAX_INT_BITS)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001681 return error("Bitwidth for integer type out of range");
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001682 ResultTy = IntegerType::get(Context, NumBits);
Chris Lattner1314b992007-04-22 06:23:29 +00001683 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001684 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001685 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001686 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +00001687 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001688 return error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001689 unsigned AddressSpace = 0;
1690 if (Record.size() == 2)
1691 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001692 ResultTy = getTypeByID(Record[0]);
Filipe Cabecinhasd8a1bcd2015-04-29 02:27:28 +00001693 if (!ResultTy ||
1694 !PointerType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001695 return error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001696 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +00001697 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001698 }
Nuno Lopes561dae02012-05-23 15:19:39 +00001699 case bitc::TYPE_CODE_FUNCTION_OLD: {
1700 // FIXME: attrid is dead, remove it in LLVM 4.0
1701 // FUNCTION: [vararg, attrid, retty, paramty x N]
1702 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001703 return error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +00001704 SmallVector<Type*, 8> ArgTys;
1705 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1706 if (Type *T = getTypeByID(Record[i]))
1707 ArgTys.push_back(T);
1708 else
1709 break;
1710 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001711
Nuno Lopes561dae02012-05-23 15:19:39 +00001712 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001713 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001714 return error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +00001715
1716 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1717 break;
1718 }
Chad Rosier95898722011-11-03 00:14:01 +00001719 case bitc::TYPE_CODE_FUNCTION: {
1720 // FUNCTION: [vararg, retty, paramty x N]
1721 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001722 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001723 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +00001724 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001725 if (Type *T = getTypeByID(Record[i])) {
1726 if (!FunctionType::isValidArgumentType(T))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001727 return error("Invalid function argument type");
Chad Rosier95898722011-11-03 00:14:01 +00001728 ArgTys.push_back(T);
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001729 }
Chad Rosier95898722011-11-03 00:14:01 +00001730 else
1731 break;
1732 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001733
Chad Rosier95898722011-11-03 00:14:01 +00001734 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001735 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001736 return error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +00001737
1738 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1739 break;
1740 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001741 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +00001742 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001743 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001744 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001745 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1746 if (Type *T = getTypeByID(Record[i]))
1747 EltTys.push_back(T);
1748 else
1749 break;
1750 }
1751 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001752 return error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001753 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001754 break;
1755 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001756 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001757 if (convertToString(Record, 0, TypeName))
1758 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001759 continue;
1760
1761 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1762 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001763 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001764
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001765 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001766 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001767
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001768 // Check to see if this was forward referenced, if so fill in the temp.
1769 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1770 if (Res) {
1771 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001772 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001773 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001774 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001775 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001776
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001777 SmallVector<Type*, 8> EltTys;
1778 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1779 if (Type *T = getTypeByID(Record[i]))
1780 EltTys.push_back(T);
1781 else
1782 break;
1783 }
1784 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001785 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001786 Res->setBody(EltTys, Record[0]);
1787 ResultTy = Res;
1788 break;
1789 }
1790 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1791 if (Record.size() != 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001792 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001793
1794 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001795 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001796
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001797 // Check to see if this was forward referenced, if so fill in the temp.
1798 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1799 if (Res) {
1800 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001801 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001802 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001803 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001804 TypeName.clear();
1805 ResultTy = Res;
1806 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001807 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001808 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1809 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001810 return error("Invalid record");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001811 ResultTy = getTypeByID(Record[1]);
1812 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001813 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001814 ResultTy = ArrayType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001815 break;
1816 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1817 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001818 return error("Invalid record");
Filipe Cabecinhas8e421902015-06-03 00:05:30 +00001819 if (Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001820 return error("Invalid vector length");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001821 ResultTy = getTypeByID(Record[1]);
1822 if (!ResultTy || !StructType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001823 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001824 ResultTy = VectorType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001825 break;
1826 }
1827
1828 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001829 return error("Invalid TYPE table");
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001830 if (TypeList[NumRecords])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001831 return error(
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001832 "Invalid TYPE table: Only named structs can be forward referenced");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001833 assert(ResultTy && "Didn't read a type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001834 TypeList[NumRecords++] = ResultTy;
1835 }
1836}
1837
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001838std::error_code BitcodeReader::parseOperandBundleTags() {
1839 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1840 return error("Invalid record");
1841
1842 if (!BundleTags.empty())
1843 return error("Invalid multiple blocks");
1844
1845 SmallVector<uint64_t, 64> Record;
1846
1847 while (1) {
1848 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1849
1850 switch (Entry.Kind) {
1851 case BitstreamEntry::SubBlock: // Handled for us already.
1852 case BitstreamEntry::Error:
1853 return error("Malformed block");
1854 case BitstreamEntry::EndBlock:
1855 return std::error_code();
1856 case BitstreamEntry::Record:
1857 // The interesting case.
1858 break;
1859 }
1860
1861 // Tags are implicitly mapped to integers by their order.
1862
1863 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1864 return error("Invalid record");
1865
1866 // OPERAND_BUNDLE_TAG: [strchr x N]
1867 BundleTags.emplace_back();
1868 if (convertToString(Record, 0, BundleTags.back()))
1869 return error("Invalid record");
1870 Record.clear();
1871 }
1872}
1873
Teresa Johnsonff642b92015-09-17 20:12:00 +00001874/// Associate a value with its name from the given index in the provided record.
1875ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1876 unsigned NameIndex, Triple &TT) {
1877 SmallString<128> ValueName;
1878 if (convertToString(Record, NameIndex, ValueName))
1879 return error("Invalid record");
1880 unsigned ValueID = Record[0];
1881 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1882 return error("Invalid record");
1883 Value *V = ValueList[ValueID];
1884
Filipe Cabecinhasa2b0ac42015-11-04 14:53:36 +00001885 StringRef NameStr(ValueName.data(), ValueName.size());
1886 if (NameStr.find_first_of(0) != StringRef::npos)
1887 return error("Invalid value name");
1888 V->setName(NameStr);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001889 auto *GO = dyn_cast<GlobalObject>(V);
1890 if (GO) {
1891 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1892 if (TT.isOSBinFormatMachO())
1893 GO->setComdat(nullptr);
1894 else
1895 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1896 }
1897 }
1898 return V;
1899}
1900
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001901/// Helper to note and return the current location, and jump to the given
1902/// offset.
1903static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1904 BitstreamCursor &Stream) {
1905 // Save the current parsing location so we can jump back at the end
1906 // of the VST read.
1907 uint64_t CurrentBit = Stream.GetCurrentBitNo();
1908 Stream.JumpToBit(Offset * 32);
1909#ifndef NDEBUG
1910 // Do some checking if we are in debug mode.
1911 BitstreamEntry Entry = Stream.advance();
1912 assert(Entry.Kind == BitstreamEntry::SubBlock);
1913 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1914#else
1915 // In NDEBUG mode ignore the output so we don't get an unused variable
1916 // warning.
1917 Stream.advance();
1918#endif
1919 return CurrentBit;
1920}
1921
Teresa Johnsonff642b92015-09-17 20:12:00 +00001922/// Parse the value symbol table at either the current parsing location or
1923/// at the given bit offset if provided.
Peter Collingbourne128a9762015-10-27 23:01:25 +00001924std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001925 uint64_t CurrentBit;
1926 // Pass in the Offset to distinguish between calling for the module-level
1927 // VST (where we want to jump to the VST offset) and the function-level
1928 // VST (where we don't).
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001929 if (Offset > 0)
1930 CurrentBit = jumpToValueSymbolTable(Offset, Stream);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001931
1932 // Compute the delta between the bitcode indices in the VST (the word offset
1933 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1934 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1935 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1936 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1937 // just before entering the VST subblock because: 1) the EnterSubBlock
1938 // changes the AbbrevID width; 2) the VST block is nested within the same
1939 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1940 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1941 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1942 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1943 unsigned FuncBitcodeOffsetDelta =
1944 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1945
Chris Lattner982ec1e2007-05-05 00:17:00 +00001946 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001947 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001948
1949 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001950
David Majnemer3087b222015-01-20 05:58:07 +00001951 Triple TT(TheModule->getTargetTriple());
1952
Chris Lattnerccaa4482007-04-23 21:26:05 +00001953 // Read all the records for this value table.
1954 SmallString<128> ValueName;
1955 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001956 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001957
Chris Lattner27d38752013-01-20 02:13:19 +00001958 switch (Entry.Kind) {
1959 case BitstreamEntry::SubBlock: // Handled for us already.
1960 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001961 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001962 case BitstreamEntry::EndBlock:
Teresa Johnsonff642b92015-09-17 20:12:00 +00001963 if (Offset > 0)
1964 Stream.JumpToBit(CurrentBit);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001965 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001966 case BitstreamEntry::Record:
1967 // The interesting case.
1968 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001969 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001970
Chris Lattnerccaa4482007-04-23 21:26:05 +00001971 // Read a record.
1972 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001973 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001974 default: // Default behavior: unknown type.
1975 break;
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001976 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
Teresa Johnsonff642b92015-09-17 20:12:00 +00001977 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1978 if (std::error_code EC = ValOrErr.getError())
1979 return EC;
1980 ValOrErr.get();
1981 break;
1982 }
1983 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001984 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonff642b92015-09-17 20:12:00 +00001985 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1986 if (std::error_code EC = ValOrErr.getError())
1987 return EC;
1988 Value *V = ValOrErr.get();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001989
Teresa Johnsonff642b92015-09-17 20:12:00 +00001990 auto *GO = dyn_cast<GlobalObject>(V);
1991 if (!GO) {
1992 // If this is an alias, need to get the actual Function object
1993 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1994 auto *GA = dyn_cast<GlobalAlias>(V);
1995 if (GA)
1996 GO = GA->getBaseObject();
1997 assert(GO);
Rafael Espindola12ca34f2015-01-19 15:16:06 +00001998 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001999
2000 uint64_t FuncWordOffset = Record[1];
2001 Function *F = dyn_cast<Function>(GO);
2002 assert(F);
2003 uint64_t FuncBitOffset = FuncWordOffset * 32;
2004 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
Teresa Johnson1493ad92015-10-10 14:18:36 +00002005 // Set the LastFunctionBlockBit to point to the last function block.
Teresa Johnsonff642b92015-09-17 20:12:00 +00002006 // Later when parsing is resumed after function materialization,
2007 // we can simply skip that last function block.
Teresa Johnson1493ad92015-10-10 14:18:36 +00002008 if (FuncBitOffset > LastFunctionBlockBit)
2009 LastFunctionBlockBit = FuncBitOffset;
Chris Lattnerccaa4482007-04-23 21:26:05 +00002010 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00002011 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002012 case bitc::VST_CODE_BBENTRY: {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002013 if (convertToString(Record, 1, ValueName))
2014 return error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00002015 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002016 if (!BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002017 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002018
Daniel Dunbard786b512009-07-26 00:34:27 +00002019 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00002020 ValueName.clear();
2021 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00002022 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00002023 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00002024 }
2025}
2026
Teresa Johnson12545072015-11-15 02:00:09 +00002027/// Parse a single METADATA_KIND record, inserting result in MDKindMap.
2028std::error_code
2029BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
2030 if (Record.size() < 2)
2031 return error("Invalid record");
2032
2033 unsigned Kind = Record[0];
2034 SmallString<8> Name(Record.begin() + 1, Record.end());
2035
2036 unsigned NewKind = TheModule->getMDKindID(Name.str());
2037 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2038 return error("Conflicting METADATA_KIND records");
2039 return std::error_code();
2040}
2041
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002042static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
2043
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002044std::error_code BitcodeReader::parseMetadataStrings(ArrayRef<uint64_t> Record,
2045 StringRef Blob,
2046 unsigned &NextMetadataNo) {
2047 // All the MDStrings in the block are emitted together in a single
2048 // record. The strings are concatenated and stored in a blob along with
2049 // their sizes.
2050 if (Record.size() != 2)
2051 return error("Invalid record: metadata strings layout");
2052
2053 unsigned NumStrings = Record[0];
2054 unsigned StringsOffset = Record[1];
2055 if (!NumStrings)
2056 return error("Invalid record: metadata strings with no strings");
Duncan P. N. Exon Smithbb7ce3b2016-03-29 05:25:17 +00002057 if (StringsOffset > Blob.size())
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002058 return error("Invalid record: metadata strings corrupt offset");
2059
2060 StringRef Lengths = Blob.slice(0, StringsOffset);
2061 SimpleBitstreamCursor R(*StreamFile);
2062 R.jumpToPointer(Lengths.begin());
2063
2064 // Ensure that Blob doesn't get invalidated, even if this is reading from
2065 // a StreamingMemoryObject with corrupt data.
2066 R.setArtificialByteLimit(R.getCurrentByteNo() + StringsOffset);
2067
2068 StringRef Strings = Blob.drop_front(StringsOffset);
2069 do {
2070 if (R.AtEndOfStream())
2071 return error("Invalid record: metadata strings bad length");
2072
2073 unsigned Size = R.ReadVBR(6);
2074 if (Strings.size() < Size)
2075 return error("Invalid record: metadata strings truncated chars");
2076
2077 MetadataList.assignValue(MDString::get(Context, Strings.slice(0, Size)),
2078 NextMetadataNo++);
2079 Strings = Strings.drop_front(Size);
2080 } while (--NumStrings);
2081
2082 return std::error_code();
2083}
2084
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002085namespace {
2086class PlaceholderQueue {
2087 // Placeholders would thrash around when moved, so store in a std::deque
2088 // instead of some sort of vector.
2089 std::deque<DistinctMDOperandPlaceholder> PHs;
2090
2091public:
2092 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
2093 void flush(BitcodeReaderMetadataList &MetadataList);
2094};
2095} // end namespace
2096
2097DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
2098 PHs.emplace_back(ID);
2099 return PHs.back();
2100}
2101
2102void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
2103 while (!PHs.empty()) {
2104 PHs.front().replaceUseWith(
2105 MetadataList.getMetadataFwdRef(PHs.front().getID()));
2106 PHs.pop_front();
2107 }
2108}
2109
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00002110/// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
2111/// module level metadata.
2112std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
Duncan P. N. Exon Smith03a04a52016-04-24 15:04:28 +00002113 assert((ModuleLevel || DeferredMetadataInfo.empty()) &&
2114 "Must read all module-level metadata before function-level");
2115
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002116 IsMetadataMaterialized = true;
Teresa Johnson61b406e2015-12-29 23:00:22 +00002117 unsigned NextMetadataNo = MetadataList.size();
Devang Patel7428d8a2009-07-22 17:43:22 +00002118
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00002119 if (!ModuleLevel && MetadataList.hasFwdRefs())
2120 return error("Invalid metadata: fwd refs into function blocks");
2121
Devang Patel7428d8a2009-07-22 17:43:22 +00002122 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002123 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002124
Adrian Prantl75819ae2016-04-15 15:57:41 +00002125 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
Devang Patel7428d8a2009-07-22 17:43:22 +00002126 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002127
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002128 PlaceholderQueue Placeholders;
2129 bool IsDistinct;
Duncan P. N. Exon Smith498b4972016-04-23 04:52:47 +00002130 auto getMD = [&](unsigned ID) -> Metadata * {
2131 if (!IsDistinct)
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002132 return MetadataList.getMetadataFwdRef(ID);
2133 if (auto *MD = MetadataList.getMetadataIfResolved(ID))
2134 return MD;
2135 return &Placeholders.getPlaceholderOp(ID);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002136 };
Duncan P. N. Exon Smith498b4972016-04-23 04:52:47 +00002137 auto getMDOrNull = [&](unsigned ID) -> Metadata * {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002138 if (ID)
Duncan P. N. Exon Smith498b4972016-04-23 04:52:47 +00002139 return getMD(ID - 1);
2140 return nullptr;
2141 };
2142 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
2143 if (ID)
2144 return MetadataList.getMetadataFwdRef(ID - 1);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002145 return nullptr;
2146 };
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002147 auto getMDString = [&](unsigned ID) -> MDString *{
2148 // This requires that the ID is not really a forward reference. In
2149 // particular, the MDString must already have been resolved.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002150 return cast_or_null<MDString>(getMDOrNull(ID));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002151 };
2152
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002153 // Support for old type refs.
2154 auto getDITypeRefOrNull = [&](unsigned ID) {
2155 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
2156 };
2157
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002158#define GET_OR_DISTINCT(CLASS, ARGS) \
2159 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002160
Devang Patel7428d8a2009-07-22 17:43:22 +00002161 // Read all the records.
2162 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002163 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002164
Chris Lattner27d38752013-01-20 02:13:19 +00002165 switch (Entry.Kind) {
2166 case BitstreamEntry::SubBlock: // Handled for us already.
2167 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002168 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002169 case BitstreamEntry::EndBlock:
Adrian Prantl75819ae2016-04-15 15:57:41 +00002170 // Upgrade old-style CU <-> SP pointers to point from SP to CU.
2171 for (auto CU_SP : CUSubprograms)
2172 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
2173 for (auto &Op : SPs->operands())
2174 if (auto *SP = dyn_cast_or_null<MDNode>(Op))
2175 SP->replaceOperandWith(7, CU_SP.first);
2176
Teresa Johnson61b406e2015-12-29 23:00:22 +00002177 MetadataList.tryToResolveCycles();
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002178 Placeholders.flush(MetadataList);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002179 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002180 case BitstreamEntry::Record:
2181 // The interesting case.
2182 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00002183 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002184
Devang Patel7428d8a2009-07-22 17:43:22 +00002185 // Read a record.
2186 Record.clear();
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002187 StringRef Blob;
2188 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002189 IsDistinct = false;
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00002190 switch (Code) {
Devang Patel7428d8a2009-07-22 17:43:22 +00002191 default: // Default behavior: ignore.
2192 break;
Devang Patel27c87ff2009-07-29 22:34:41 +00002193 case bitc::METADATA_NAME: {
Chris Lattner8d140532013-01-20 02:54:05 +00002194 // Read name of the named metadata.
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002195 SmallString<8> Name(Record.begin(), Record.end());
Devang Patel27c87ff2009-07-29 22:34:41 +00002196 Record.clear();
2197 Code = Stream.ReadCode();
2198
Chris Lattner27d38752013-01-20 02:13:19 +00002199 unsigned NextBitCode = Stream.readRecord(Code, Record);
Filipe Cabecinhas14e68672015-05-30 00:17:20 +00002200 if (NextBitCode != bitc::METADATA_NAMED_NODE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002201 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
Devang Patel27c87ff2009-07-29 22:34:41 +00002202
2203 // Read named metadata elements.
2204 unsigned Size = Record.size();
Dan Gohman2637cc12010-07-21 23:38:33 +00002205 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patel27c87ff2009-07-29 22:34:41 +00002206 for (unsigned i = 0; i != Size; ++i) {
Justin Bognerae341c62016-03-17 20:12:06 +00002207 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002208 if (!MD)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002209 return error("Invalid record");
Dan Gohman2637cc12010-07-21 23:38:33 +00002210 NMD->addOperand(MD);
Devang Patel27c87ff2009-07-29 22:34:41 +00002211 }
Devang Patel27c87ff2009-07-29 22:34:41 +00002212 break;
2213 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00002214 case bitc::METADATA_OLD_FN_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00002215 // FIXME: Remove in 4.0.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002216 // This is a LocalAsMetadata record, the only type of function-local
2217 // metadata.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002218 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002219 return error("Invalid record");
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002220
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002221 // If this isn't a LocalAsMetadata record, we're dropping it. This used
2222 // to be legal, but there's no upgrade path.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002223 auto dropRecord = [&] {
Teresa Johnson61b406e2015-12-29 23:00:22 +00002224 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002225 };
2226 if (Record.size() != 2) {
2227 dropRecord();
2228 break;
2229 }
2230
2231 Type *Ty = getTypeByID(Record[0]);
2232 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
2233 dropRecord();
2234 break;
2235 }
2236
Teresa Johnson61b406e2015-12-29 23:00:22 +00002237 MetadataList.assignValue(
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002238 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002239 NextMetadataNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002240 break;
2241 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00002242 case bitc::METADATA_OLD_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00002243 // FIXME: Remove in 4.0.
Dan Gohman1e0213a2010-07-13 19:33:27 +00002244 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002245 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002246
Devang Patele059ba6e2009-07-23 01:07:34 +00002247 unsigned Size = Record.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002248 SmallVector<Metadata *, 8> Elts;
Devang Patele059ba6e2009-07-23 01:07:34 +00002249 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00002250 Type *Ty = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002251 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002252 return error("Invalid record");
Chris Lattnerfdd87902009-10-05 05:54:46 +00002253 if (Ty->isMetadataTy())
Duncan P. N. Exon Smith004509d2016-04-23 03:55:14 +00002254 Elts.push_back(getMD(Record[i + 1]));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002255 else if (!Ty->isVoidTy()) {
2256 auto *MD =
2257 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2258 assert(isa<ConstantAsMetadata>(MD) &&
2259 "Expected non-function-local metadata");
2260 Elts.push_back(MD);
2261 } else
Craig Topper2617dcc2014-04-15 06:32:26 +00002262 Elts.push_back(nullptr);
Devang Patele059ba6e2009-07-23 01:07:34 +00002263 }
Teresa Johnson61b406e2015-12-29 23:00:22 +00002264 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++);
Devang Patele059ba6e2009-07-23 01:07:34 +00002265 break;
2266 }
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002267 case bitc::METADATA_VALUE: {
2268 if (Record.size() != 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002269 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002270
2271 Type *Ty = getTypeByID(Record[0]);
2272 if (Ty->isMetadataTy() || Ty->isVoidTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002273 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002274
Teresa Johnson61b406e2015-12-29 23:00:22 +00002275 MetadataList.assignValue(
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002276 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002277 NextMetadataNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002278 break;
2279 }
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00002280 case bitc::METADATA_DISTINCT_NODE:
2281 IsDistinct = true;
2282 // fallthrough...
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002283 case bitc::METADATA_NODE: {
2284 SmallVector<Metadata *, 8> Elts;
2285 Elts.reserve(Record.size());
2286 for (unsigned ID : Record)
Duncan P. N. Exon Smith004509d2016-04-23 03:55:14 +00002287 Elts.push_back(getMDOrNull(ID));
Teresa Johnson61b406e2015-12-29 23:00:22 +00002288 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2289 : MDNode::get(Context, Elts),
2290 NextMetadataNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002291 break;
2292 }
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002293 case bitc::METADATA_LOCATION: {
2294 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002295 return error("Invalid record");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002296
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002297 IsDistinct = Record[0];
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002298 unsigned Line = Record[1];
2299 unsigned Column = Record[2];
Duncan P. N. Exon Smith004509d2016-04-23 03:55:14 +00002300 Metadata *Scope = getMD(Record[3]);
2301 Metadata *InlinedAt = getMDOrNull(Record[4]);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002302 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002303 GET_OR_DISTINCT(DILocation,
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00002304 (Context, Line, Column, Scope, InlinedAt)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002305 NextMetadataNo++);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002306 break;
2307 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002308 case bitc::METADATA_GENERIC_DEBUG: {
2309 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002310 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002311
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002312 IsDistinct = Record[0];
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002313 unsigned Tag = Record[1];
2314 unsigned Version = Record[2];
2315
2316 if (Tag >= 1u << 16 || Version != 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002317 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002318
2319 auto *Header = getMDString(Record[3]);
2320 SmallVector<Metadata *, 8> DwarfOps;
2321 for (unsigned I = 4, E = Record.size(); I != E; ++I)
Duncan P. N. Exon Smith004509d2016-04-23 03:55:14 +00002322 DwarfOps.push_back(getMDOrNull(Record[I]));
Teresa Johnson61b406e2015-12-29 23:00:22 +00002323 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002324 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002325 NextMetadataNo++);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002326 break;
2327 }
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002328 case bitc::METADATA_SUBRANGE: {
2329 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002330 return error("Invalid record");
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002331
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002332 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002333 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002334 GET_OR_DISTINCT(DISubrange,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002335 (Context, Record[1], unrotateSign(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002336 NextMetadataNo++);
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002337 break;
2338 }
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002339 case bitc::METADATA_ENUMERATOR: {
2340 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002341 return error("Invalid record");
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002342
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002343 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002344 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002345 GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]),
2346 getMDString(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002347 NextMetadataNo++);
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002348 break;
2349 }
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002350 case bitc::METADATA_BASIC_TYPE: {
2351 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002352 return error("Invalid record");
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002353
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002354 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002355 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002356 GET_OR_DISTINCT(DIBasicType,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002357 (Context, Record[1], getMDString(Record[2]),
2358 Record[3], Record[4], Record[5])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002359 NextMetadataNo++);
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002360 break;
2361 }
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002362 case bitc::METADATA_DERIVED_TYPE: {
2363 if (Record.size() != 12)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002364 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002365
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002366 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002367 MetadataList.assignValue(
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00002368 GET_OR_DISTINCT(
2369 DIDerivedType,
2370 (Context, Record[1], getMDString(Record[2]),
2371 getMDOrNull(Record[3]), Record[4], getDITypeRefOrNull(Record[5]),
2372 getDITypeRefOrNull(Record[6]), Record[7], Record[8], Record[9],
2373 Record[10], getDITypeRefOrNull(Record[11]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002374 NextMetadataNo++);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002375 break;
2376 }
2377 case bitc::METADATA_COMPOSITE_TYPE: {
2378 if (Record.size() != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002379 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002380
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002381 // If we have a UUID and this is not a forward declaration, lookup the
2382 // mapping.
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002383 IsDistinct = Record[0] & 0x1;
2384 bool IsNotUsedInTypeRef = Record[0] >= 2;
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002385 unsigned Tag = Record[1];
2386 MDString *Name = getMDString(Record[2]);
2387 Metadata *File = getMDOrNull(Record[3]);
2388 unsigned Line = Record[4];
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002389 Metadata *Scope = getDITypeRefOrNull(Record[5]);
2390 Metadata *BaseType = getDITypeRefOrNull(Record[6]);
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002391 uint64_t SizeInBits = Record[7];
2392 uint64_t AlignInBits = Record[8];
2393 uint64_t OffsetInBits = Record[9];
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002394 unsigned Flags = Record[10];
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002395 Metadata *Elements = getMDOrNull(Record[11]);
2396 unsigned RuntimeLang = Record[12];
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002397 Metadata *VTableHolder = getDITypeRefOrNull(Record[13]);
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002398 Metadata *TemplateParams = getMDOrNull(Record[14]);
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002399 auto *Identifier = getMDString(Record[15]);
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002400 DICompositeType *CT = nullptr;
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00002401 if (Identifier)
2402 CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002403 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
2404 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
2405 VTableHolder, TemplateParams);
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002406
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002407 // Create a node if we didn't get a lazy ODR type.
2408 if (!CT)
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002409 CT = GET_OR_DISTINCT(DICompositeType,
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002410 (Context, Tag, Name, File, Line, Scope, BaseType,
2411 SizeInBits, AlignInBits, OffsetInBits, Flags,
2412 Elements, RuntimeLang, VTableHolder,
2413 TemplateParams, Identifier));
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002414 if (!IsNotUsedInTypeRef && Identifier)
2415 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002416
2417 MetadataList.assignValue(CT, NextMetadataNo++);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002418 break;
2419 }
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002420 case bitc::METADATA_SUBROUTINE_TYPE: {
Reid Klecknerde3d8b52016-06-08 20:34:29 +00002421 if (Record.size() < 3 || Record.size() > 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002422 return error("Invalid record");
Reid Klecknerde3d8b52016-06-08 20:34:29 +00002423 bool IsOldTypeRefArray = Record[0] < 2;
2424 unsigned CC = (Record.size() > 3) ? Record[3] : 0;
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002425
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002426 IsDistinct = Record[0] & 0x1;
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002427 Metadata *Types = getMDOrNull(Record[2]);
2428 if (LLVM_UNLIKELY(IsOldTypeRefArray))
2429 Types = MetadataList.upgradeTypeRefArray(Types);
2430
Teresa Johnson61b406e2015-12-29 23:00:22 +00002431 MetadataList.assignValue(
Reid Klecknerde3d8b52016-06-08 20:34:29 +00002432 GET_OR_DISTINCT(DISubroutineType, (Context, Record[1], CC, Types)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002433 NextMetadataNo++);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002434 break;
2435 }
Adrian Prantlab1243f2015-06-29 23:03:47 +00002436
2437 case bitc::METADATA_MODULE: {
2438 if (Record.size() != 6)
2439 return error("Invalid record");
2440
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002441 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002442 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002443 GET_OR_DISTINCT(DIModule,
Adrian Prantlab1243f2015-06-29 23:03:47 +00002444 (Context, getMDOrNull(Record[1]),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002445 getMDString(Record[2]), getMDString(Record[3]),
2446 getMDString(Record[4]), getMDString(Record[5]))),
2447 NextMetadataNo++);
Adrian Prantlab1243f2015-06-29 23:03:47 +00002448 break;
2449 }
2450
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002451 case bitc::METADATA_FILE: {
2452 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002453 return error("Invalid record");
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002454
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002455 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002456 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002457 GET_OR_DISTINCT(DIFile, (Context, getMDString(Record[1]),
2458 getMDString(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002459 NextMetadataNo++);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002460 break;
2461 }
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002462 case bitc::METADATA_COMPILE_UNIT: {
Amjad Abouda9bcf162015-12-10 12:56:35 +00002463 if (Record.size() < 14 || Record.size() > 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002464 return error("Invalid record");
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002465
Amjad Abouda9bcf162015-12-10 12:56:35 +00002466 // Ignore Record[0], which indicates whether this compile unit is
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00002467 // distinct. It's always distinct.
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002468 IsDistinct = true;
Adrian Prantl75819ae2016-04-15 15:57:41 +00002469 auto *CU = DICompileUnit::getDistinct(
2470 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
2471 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
2472 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2473 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
2474 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
2475 Record.size() <= 14 ? 0 : Record[14]);
2476
2477 MetadataList.assignValue(CU, NextMetadataNo++);
2478
2479 // Move the Upgrade the list of subprograms.
Duncan P. N. Exon Smith498b4972016-04-23 04:52:47 +00002480 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
Adrian Prantl75819ae2016-04-15 15:57:41 +00002481 CUSubprograms.push_back({CU, SPs});
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002482 break;
2483 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002484 case bitc::METADATA_SUBPROGRAM: {
Peter Collingbourned4bff302015-11-05 22:03:56 +00002485 if (Record.size() != 18 && Record.size() != 19)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002486 return error("Invalid record");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002487
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002488 IsDistinct =
Adrian Prantl85338cb2016-05-06 22:53:06 +00002489 (Record[0] & 1) || Record[8]; // All definitions should be distinct.
Adrian Prantl75819ae2016-04-15 15:57:41 +00002490 // Version 1 has a Function as Record[15].
2491 // Version 2 has removed Record[15].
2492 // Version 3 has the Unit as Record[15].
Adrian Prantl85338cb2016-05-06 22:53:06 +00002493 bool HasUnit = Record[0] >= 2;
2494 if (HasUnit && Record.size() != 19)
2495 return error("Invalid record");
Adrian Prantl75819ae2016-04-15 15:57:41 +00002496 Metadata *CUorFn = getMDOrNull(Record[15]);
2497 unsigned Offset = Record.size() == 19 ? 1 : 0;
Adrian Prantl85338cb2016-05-06 22:53:06 +00002498 bool HasFn = Offset && !HasUnit;
Peter Collingbourned4bff302015-11-05 22:03:56 +00002499 DISubprogram *SP = GET_OR_DISTINCT(
2500 DISubprogram,
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002501 (Context, getDITypeRefOrNull(Record[1]), getMDString(Record[2]),
Peter Collingbourned4bff302015-11-05 22:03:56 +00002502 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2503 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002504 getDITypeRefOrNull(Record[10]), Record[11], Record[12], Record[13],
Adrian Prantl85338cb2016-05-06 22:53:06 +00002505 Record[14], HasUnit ? CUorFn : nullptr,
Adrian Prantl75819ae2016-04-15 15:57:41 +00002506 getMDOrNull(Record[15 + Offset]), getMDOrNull(Record[16 + Offset]),
2507 getMDOrNull(Record[17 + Offset])));
Teresa Johnson61b406e2015-12-29 23:00:22 +00002508 MetadataList.assignValue(SP, NextMetadataNo++);
Peter Collingbourned4bff302015-11-05 22:03:56 +00002509
2510 // Upgrade sp->function mapping to function->sp mapping.
Adrian Prantl75819ae2016-04-15 15:57:41 +00002511 if (HasFn) {
Adrian Prantl85338cb2016-05-06 22:53:06 +00002512 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
Peter Collingbourned4bff302015-11-05 22:03:56 +00002513 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2514 if (F->isMaterializable())
2515 // Defer until materialized; unmaterialized functions may not have
2516 // metadata.
2517 FunctionsWithSPs[F] = SP;
2518 else if (!F->empty())
2519 F->setSubprogram(SP);
2520 }
2521 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002522 break;
2523 }
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002524 case bitc::METADATA_LEXICAL_BLOCK: {
2525 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002526 return error("Invalid record");
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002527
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002528 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002529 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002530 GET_OR_DISTINCT(DILexicalBlock,
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002531 (Context, getMDOrNull(Record[1]),
2532 getMDOrNull(Record[2]), Record[3], Record[4])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002533 NextMetadataNo++);
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002534 break;
2535 }
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002536 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2537 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002538 return error("Invalid record");
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002539
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002540 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002541 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002542 GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002543 (Context, getMDOrNull(Record[1]),
2544 getMDOrNull(Record[2]), Record[3])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002545 NextMetadataNo++);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002546 break;
2547 }
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002548 case bitc::METADATA_NAMESPACE: {
2549 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002550 return error("Invalid record");
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002551
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002552 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002553 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002554 GET_OR_DISTINCT(DINamespace, (Context, getMDOrNull(Record[1]),
2555 getMDOrNull(Record[2]),
2556 getMDString(Record[3]), Record[4])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002557 NextMetadataNo++);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002558 break;
2559 }
Amjad Abouda9bcf162015-12-10 12:56:35 +00002560 case bitc::METADATA_MACRO: {
2561 if (Record.size() != 5)
2562 return error("Invalid record");
2563
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002564 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002565 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002566 GET_OR_DISTINCT(DIMacro,
Amjad Abouda9bcf162015-12-10 12:56:35 +00002567 (Context, Record[1], Record[2],
2568 getMDString(Record[3]), getMDString(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002569 NextMetadataNo++);
Amjad Abouda9bcf162015-12-10 12:56:35 +00002570 break;
2571 }
2572 case bitc::METADATA_MACRO_FILE: {
2573 if (Record.size() != 5)
2574 return error("Invalid record");
2575
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002576 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002577 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002578 GET_OR_DISTINCT(DIMacroFile,
Amjad Abouda9bcf162015-12-10 12:56:35 +00002579 (Context, Record[1], Record[2],
2580 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002581 NextMetadataNo++);
Amjad Abouda9bcf162015-12-10 12:56:35 +00002582 break;
2583 }
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002584 case bitc::METADATA_TEMPLATE_TYPE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002585 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002586 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002587
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002588 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002589 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
Teresa Johnson61b406e2015-12-29 23:00:22 +00002590 (Context, getMDString(Record[1]),
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002591 getDITypeRefOrNull(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002592 NextMetadataNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002593 break;
2594 }
2595 case bitc::METADATA_TEMPLATE_VALUE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002596 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002597 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002598
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002599 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002600 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002601 GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002602 (Context, Record[1], getMDString(Record[2]),
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002603 getDITypeRefOrNull(Record[3]),
2604 getMDOrNull(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002605 NextMetadataNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002606 break;
2607 }
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002608 case bitc::METADATA_GLOBAL_VAR: {
2609 if (Record.size() != 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002610 return error("Invalid record");
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002611
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002612 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002613 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002614 GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002615 (Context, getMDOrNull(Record[1]),
2616 getMDString(Record[2]), getMDString(Record[3]),
2617 getMDOrNull(Record[4]), Record[5],
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002618 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002619 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002620 NextMetadataNo++);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002621 break;
2622 }
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002623 case bitc::METADATA_LOCAL_VAR: {
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00002624 // 10th field is for the obseleted 'inlinedAt:' field.
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002625 if (Record.size() < 8 || Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002626 return error("Invalid record");
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002627
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002628 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2629 // DW_TAG_arg_variable.
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002630 IsDistinct = Record[0];
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002631 bool HasTag = Record.size() > 8;
Teresa Johnson61b406e2015-12-29 23:00:22 +00002632 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002633 GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002634 (Context, getMDOrNull(Record[1 + HasTag]),
2635 getMDString(Record[2 + HasTag]),
2636 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002637 getDITypeRefOrNull(Record[5 + HasTag]),
2638 Record[6 + HasTag], Record[7 + HasTag])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002639 NextMetadataNo++);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002640 break;
2641 }
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002642 case bitc::METADATA_EXPRESSION: {
2643 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002644 return error("Invalid record");
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002645
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002646 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002647 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002648 GET_OR_DISTINCT(DIExpression,
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002649 (Context, makeArrayRef(Record).slice(1))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002650 NextMetadataNo++);
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002651 break;
2652 }
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002653 case bitc::METADATA_OBJC_PROPERTY: {
2654 if (Record.size() != 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002655 return error("Invalid record");
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002656
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002657 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002658 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002659 GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002660 (Context, getMDString(Record[1]),
2661 getMDOrNull(Record[2]), Record[3],
2662 getMDString(Record[4]), getMDString(Record[5]),
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002663 Record[6], getDITypeRefOrNull(Record[7]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002664 NextMetadataNo++);
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002665 break;
2666 }
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002667 case bitc::METADATA_IMPORTED_ENTITY: {
2668 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002669 return error("Invalid record");
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002670
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002671 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002672 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002673 GET_OR_DISTINCT(DIImportedEntity,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002674 (Context, Record[1], getMDOrNull(Record[2]),
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002675 getDITypeRefOrNull(Record[3]), Record[4],
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002676 getMDString(Record[5]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002677 NextMetadataNo++);
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002678 break;
2679 }
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002680 case bitc::METADATA_STRING_OLD: {
Eli Bendersky5d5e18d2014-06-25 15:41:00 +00002681 std::string String(Record.begin(), Record.end());
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00002682
2683 // Test for upgrading !llvm.loop.
2684 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2685
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002686 Metadata *MD = MDString::get(Context, String);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002687 MetadataList.assignValue(MD, NextMetadataNo++);
Devang Patel7428d8a2009-07-22 17:43:22 +00002688 break;
2689 }
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002690 case bitc::METADATA_STRINGS:
2691 if (std::error_code EC =
2692 parseMetadataStrings(Record, Blob, NextMetadataNo))
2693 return EC;
2694 break;
Devang Patelaf206b82009-09-18 19:26:43 +00002695 case bitc::METADATA_KIND: {
Teresa Johnson12545072015-11-15 02:00:09 +00002696 // Support older bitcode files that had METADATA_KIND records in a
2697 // block with METADATA_BLOCK_ID.
2698 if (std::error_code EC = parseMetadataKindRecord(Record))
2699 return EC;
Devang Patelaf206b82009-09-18 19:26:43 +00002700 break;
2701 }
Devang Patel7428d8a2009-07-22 17:43:22 +00002702 }
2703 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002704#undef GET_OR_DISTINCT
Devang Patel7428d8a2009-07-22 17:43:22 +00002705}
2706
Teresa Johnson12545072015-11-15 02:00:09 +00002707/// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2708std::error_code BitcodeReader::parseMetadataKinds() {
2709 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2710 return error("Invalid record");
2711
2712 SmallVector<uint64_t, 64> Record;
2713
2714 // Read all the records.
2715 while (1) {
2716 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2717
2718 switch (Entry.Kind) {
2719 case BitstreamEntry::SubBlock: // Handled for us already.
2720 case BitstreamEntry::Error:
2721 return error("Malformed block");
2722 case BitstreamEntry::EndBlock:
2723 return std::error_code();
2724 case BitstreamEntry::Record:
2725 // The interesting case.
2726 break;
2727 }
2728
2729 // Read a record.
2730 Record.clear();
2731 unsigned Code = Stream.readRecord(Entry.ID, Record);
2732 switch (Code) {
2733 default: // Default behavior: ignore.
2734 break;
2735 case bitc::METADATA_KIND: {
2736 if (std::error_code EC = parseMetadataKindRecord(Record))
2737 return EC;
2738 break;
2739 }
2740 }
2741 }
2742}
2743
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002744/// Decode a signed value stored with the sign bit in the LSB for dense VBR
2745/// encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002746uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00002747 if ((V & 1) == 0)
2748 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002749 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00002750 return -(V >> 1);
2751 // There is no such thing as -0 with integers. "-0" really means MININT.
2752 return 1ULL << 63;
2753}
2754
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002755/// Resolve all of the initializers for global values and aliases that we can.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002756std::error_code BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00002757 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002758 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
2759 IndirectSymbolInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002760 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002761 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
David Majnemer7fddecc2015-06-17 20:52:32 +00002762 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002763
Chris Lattner44c17072007-04-26 02:46:40 +00002764 GlobalInitWorklist.swap(GlobalInits);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002765 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002766 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002767 FunctionPrologueWorklist.swap(FunctionPrologues);
David Majnemer7fddecc2015-06-17 20:52:32 +00002768 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
Chris Lattner44c17072007-04-26 02:46:40 +00002769
2770 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00002771 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002772 if (ValID >= ValueList.size()) {
2773 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00002774 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002775 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002776 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00002777 GlobalInitWorklist.back().first->setInitializer(C);
2778 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002779 return error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00002780 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002781 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002782 }
2783
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002784 while (!IndirectSymbolInitWorklist.empty()) {
2785 unsigned ValID = IndirectSymbolInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002786 if (ValID >= ValueList.size()) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002787 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002788 } else {
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002789 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2790 if (!C)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002791 return error("Expected a constant");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002792 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2793 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002794 return error("Alias and aliasee types don't match");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002795 GIS->setIndirectSymbol(C);
Chris Lattner44c17072007-04-26 02:46:40 +00002796 }
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002797 IndirectSymbolInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002798 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002799
2800 while (!FunctionPrefixWorklist.empty()) {
2801 unsigned ValID = FunctionPrefixWorklist.back().second;
2802 if (ValID >= ValueList.size()) {
2803 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2804 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002805 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002806 FunctionPrefixWorklist.back().first->setPrefixData(C);
2807 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002808 return error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002809 }
2810 FunctionPrefixWorklist.pop_back();
2811 }
2812
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002813 while (!FunctionPrologueWorklist.empty()) {
2814 unsigned ValID = FunctionPrologueWorklist.back().second;
2815 if (ValID >= ValueList.size()) {
2816 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2817 } else {
2818 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2819 FunctionPrologueWorklist.back().first->setPrologueData(C);
2820 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002821 return error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002822 }
2823 FunctionPrologueWorklist.pop_back();
2824 }
2825
David Majnemer7fddecc2015-06-17 20:52:32 +00002826 while (!FunctionPersonalityFnWorklist.empty()) {
2827 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2828 if (ValID >= ValueList.size()) {
2829 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2830 } else {
2831 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2832 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2833 else
2834 return error("Expected a constant");
2835 }
2836 FunctionPersonalityFnWorklist.pop_back();
2837 }
2838
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002839 return std::error_code();
Chris Lattner44c17072007-04-26 02:46:40 +00002840}
2841
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002842static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002843 SmallVector<uint64_t, 8> Words(Vals.size());
2844 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00002845 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002846
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002847 return APInt(TypeBits, Words);
2848}
2849
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002850std::error_code BitcodeReader::parseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002851 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002852 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002853
2854 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002855
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002856 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00002857 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00002858 unsigned NextCstNo = ValueList.size();
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002859 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002860 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002861
Chris Lattner27d38752013-01-20 02:13:19 +00002862 switch (Entry.Kind) {
2863 case BitstreamEntry::SubBlock: // Handled for us already.
2864 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002865 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002866 case BitstreamEntry::EndBlock:
2867 if (NextCstNo != ValueList.size())
George Burgess IV1030d682016-01-20 22:15:23 +00002868 return error("Invalid constant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00002869
Chris Lattner27d38752013-01-20 02:13:19 +00002870 // Once all the constants have been read, go through and resolve forward
2871 // references.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002872 ValueList.resolveConstantForwardRefs();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002873 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002874 case BitstreamEntry::Record:
2875 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00002876 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002877 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002878
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002879 // Read a record.
2880 Record.clear();
Filipe Cabecinhas2849b482016-06-05 18:43:17 +00002881 Type *VoidType = Type::getVoidTy(Context);
Craig Topper2617dcc2014-04-15 06:32:26 +00002882 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002883 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002884 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002885 default: // Default behavior: unknown constant
2886 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00002887 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002888 break;
2889 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2890 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002891 return error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00002892 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002893 return error("Invalid record");
Filipe Cabecinhas2849b482016-06-05 18:43:17 +00002894 if (TypeList[Record[0]] == VoidType)
2895 return error("Invalid constant type");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002896 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00002897 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002898 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00002899 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002900 break;
2901 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002902 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002903 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002904 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00002905 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00002906 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002907 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002908 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002909
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002910 APInt VInt =
2911 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002912 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002913
Chris Lattner08feb1e2007-04-24 04:04:35 +00002914 break;
2915 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002916 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00002917 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002918 return error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00002919 if (CurTy->isHalfTy())
Tim Northover29178a32013-01-22 09:46:31 +00002920 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2921 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00002922 else if (CurTy->isFloatTy())
Tim Northover29178a32013-01-22 09:46:31 +00002923 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2924 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002925 else if (CurTy->isDoubleTy())
Tim Northover29178a32013-01-22 09:46:31 +00002926 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2927 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002928 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00002929 // Bits are not stored the same way as a normal i80 APInt, compensate.
2930 uint64_t Rearrange[2];
2931 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2932 Rearrange[1] = Record[0] >> 48;
Tim Northover29178a32013-01-22 09:46:31 +00002933 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2934 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002935 } else if (CurTy->isFP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002936 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2937 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002938 else if (CurTy->isPPC_FP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002939 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2940 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002941 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00002942 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002943 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00002944 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002945
Chris Lattnere14cb882007-05-04 19:11:41 +00002946 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2947 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002948 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002949
Chris Lattnere14cb882007-05-04 19:11:41 +00002950 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00002951 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002952
Chris Lattner229907c2011-07-18 04:54:35 +00002953 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00002954 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002955 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00002956 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00002957 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002958 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2959 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002960 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002961 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00002962 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002963 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2964 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002965 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002966 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00002967 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00002968 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002969 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00002970 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002971 break;
2972 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002973 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00002974 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2975 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002976 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002977
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002978 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002979 V = ConstantDataArray::getString(Context, Elts,
2980 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00002981 break;
2982 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002983 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2984 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002985 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002986
Chris Lattner372dd1e2012-01-30 00:51:16 +00002987 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
Chris Lattner372dd1e2012-01-30 00:51:16 +00002988 if (EltTy->isIntegerTy(8)) {
2989 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2990 if (isa<VectorType>(CurTy))
2991 V = ConstantDataVector::get(Context, Elts);
2992 else
2993 V = ConstantDataArray::get(Context, Elts);
2994 } else if (EltTy->isIntegerTy(16)) {
2995 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2996 if (isa<VectorType>(CurTy))
2997 V = ConstantDataVector::get(Context, Elts);
2998 else
2999 V = ConstantDataArray::get(Context, Elts);
3000 } else if (EltTy->isIntegerTy(32)) {
3001 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3002 if (isa<VectorType>(CurTy))
3003 V = ConstantDataVector::get(Context, Elts);
3004 else
3005 V = ConstantDataArray::get(Context, Elts);
3006 } else if (EltTy->isIntegerTy(64)) {
3007 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3008 if (isa<VectorType>(CurTy))
3009 V = ConstantDataVector::get(Context, Elts);
3010 else
3011 V = ConstantDataArray::get(Context, Elts);
Justin Bognera43eacb2016-01-06 22:31:32 +00003012 } else if (EltTy->isHalfTy()) {
3013 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3014 if (isa<VectorType>(CurTy))
3015 V = ConstantDataVector::getFP(Context, Elts);
3016 else
3017 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00003018 } else if (EltTy->isFloatTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00003019 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00003020 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00003021 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00003022 else
Justin Bognera43eacb2016-01-06 22:31:32 +00003023 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00003024 } else if (EltTy->isDoubleTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00003025 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00003026 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00003027 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00003028 else
Justin Bognera43eacb2016-01-06 22:31:32 +00003029 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00003030 } else {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003031 return error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00003032 }
3033 break;
3034 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003035 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003036 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003037 return error("Invalid record");
3038 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00003039 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00003040 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00003041 } else {
3042 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
3043 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00003044 unsigned Flags = 0;
3045 if (Record.size() >= 4) {
3046 if (Opc == Instruction::Add ||
3047 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003048 Opc == Instruction::Mul ||
3049 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00003050 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3051 Flags |= OverflowingBinaryOperator::NoSignedWrap;
3052 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3053 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003054 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003055 Opc == Instruction::UDiv ||
3056 Opc == Instruction::LShr ||
3057 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00003058 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00003059 Flags |= SDivOperator::IsExact;
3060 }
3061 }
3062 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00003063 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003064 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003065 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003066 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003067 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003068 return error("Invalid record");
3069 int Opc = getDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00003070 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00003071 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00003072 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00003073 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003074 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003075 return error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00003076 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003077 V = UpgradeBitCastExpr(Opc, Op, CurTy);
3078 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00003079 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003080 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003081 }
Dan Gohman1639c392009-07-27 21:53:46 +00003082 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003083 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
David Blaikieb9263572015-03-13 21:03:36 +00003084 unsigned OpNum = 0;
3085 Type *PointeeType = nullptr;
3086 if (Record.size() % 2)
3087 PointeeType = getTypeByID(Record[OpNum++]);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003088 SmallVector<Constant*, 16> Elts;
David Blaikieb9263572015-03-13 21:03:36 +00003089 while (OpNum != Record.size()) {
3090 Type *ElTy = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003091 if (!ElTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003092 return error("Invalid record");
David Blaikieb9263572015-03-13 21:03:36 +00003093 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003094 }
David Blaikieb9263572015-03-13 21:03:36 +00003095
David Blaikieb9263572015-03-13 21:03:36 +00003096 if (PointeeType &&
David Blaikie4a2e73b2015-04-02 18:55:32 +00003097 PointeeType !=
3098 cast<SequentialType>(Elts[0]->getType()->getScalarType())
3099 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003100 return error("Explicit gep operator type does not match pointee type "
David Blaikie12cf5d702015-03-16 22:03:50 +00003101 "of pointer operand");
David Blaikie4a2e73b2015-04-02 18:55:32 +00003102
Filipe Cabecinhasfc2a3c92016-06-05 18:43:26 +00003103 if (Elts.size() < 1)
3104 return error("Invalid gep with no operands");
3105
David Blaikie4a2e73b2015-04-02 18:55:32 +00003106 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3107 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
3108 BitCode ==
3109 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattner890683d2007-04-24 18:15:21 +00003110 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003111 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00003112 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003113 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003114 return error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00003115
3116 Type *SelectorTy = Type::getInt1Ty(Context);
3117
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00003118 // The selector might be an i1 or an <n x i1>
3119 // Get the type from the ValueList before getting a forward ref.
Joe Abbey1a6e7702013-09-12 22:02:31 +00003120 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00003121 if (Value *V = ValueList[Record[0]])
3122 if (SelectorTy != V->getType())
3123 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
Joe Abbey1a6e7702013-09-12 22:02:31 +00003124
3125 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
3126 SelectorTy),
3127 ValueList.getConstantFwdRef(Record[1],CurTy),
3128 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003129 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00003130 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003131 case bitc::CST_CODE_CE_EXTRACTELT
3132 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003133 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003134 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003135 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003136 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00003137 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003138 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003139 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003140 Constant *Op1 = nullptr;
3141 if (Record.size() == 4) {
3142 Type *IdxTy = getTypeByID(Record[2]);
3143 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003144 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003145 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
3146 } else // TODO: Remove with llvm 4.0
3147 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
3148 if (!Op1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003149 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00003150 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003151 break;
3152 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003153 case bitc::CST_CODE_CE_INSERTELT
3154 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00003155 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00003156 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003157 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003158 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
3159 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
3160 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003161 Constant *Op2 = nullptr;
3162 if (Record.size() == 4) {
3163 Type *IdxTy = getTypeByID(Record[2]);
3164 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003165 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003166 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
3167 } else // TODO: Remove with llvm 4.0
3168 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
3169 if (!Op2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003170 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00003171 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003172 break;
3173 }
3174 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00003175 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00003176 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003177 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003178 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
3179 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00003180 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00003181 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003182 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00003183 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003184 break;
3185 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00003186 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00003187 VectorType *RTy = dyn_cast<VectorType>(CurTy);
3188 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00003189 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00003190 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003191 return error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00003192 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3193 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00003194 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00003195 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00003196 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00003197 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00003198 break;
3199 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003200 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003201 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003202 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003203 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003204 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003205 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003206 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3207 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
3208
Duncan Sands9dff9be2010-02-15 16:12:20 +00003209 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00003210 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00003211 else
Owen Anderson487375e2009-07-29 18:55:55 +00003212 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003213 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00003214 }
Chad Rosierd8c76102012-09-05 19:00:49 +00003215 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00003216 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003217 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003218 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003219 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003220 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00003221 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00003222 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003223 unsigned AsmStrSize = Record[1];
3224 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003225 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003226 unsigned ConstStrSize = Record[2+AsmStrSize];
3227 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003228 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003229
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003230 for (unsigned i = 0; i != AsmStrSize; ++i)
3231 AsmStr += (char)Record[2+i];
3232 for (unsigned i = 0; i != ConstStrSize; ++i)
3233 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00003234 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003235 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00003236 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003237 break;
3238 }
Chad Rosierd8c76102012-09-05 19:00:49 +00003239 // This version adds support for the asm dialect keywords (e.g.,
3240 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003241 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003242 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003243 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003244 std::string AsmStr, ConstrStr;
3245 bool HasSideEffects = Record[0] & 1;
3246 bool IsAlignStack = (Record[0] >> 1) & 1;
3247 unsigned AsmDialect = Record[0] >> 2;
3248 unsigned AsmStrSize = Record[1];
3249 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003250 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003251 unsigned ConstStrSize = Record[2+AsmStrSize];
3252 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003253 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003254
3255 for (unsigned i = 0; i != AsmStrSize; ++i)
3256 AsmStr += (char)Record[2+i];
3257 for (unsigned i = 0; i != ConstStrSize; ++i)
3258 ConstrStr += (char)Record[3+AsmStrSize+i];
3259 PointerType *PTy = cast<PointerType>(CurTy);
3260 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
3261 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00003262 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003263 break;
3264 }
Chris Lattner5956dc82009-10-28 05:53:48 +00003265 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00003266 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003267 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003268 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003269 if (!FnTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003270 return error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00003271 Function *Fn =
3272 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00003273 if (!Fn)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003274 return error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003275
3276 // If the function is already parsed we can insert the block address right
3277 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003278 BasicBlock *BB;
3279 unsigned BBID = Record[2];
3280 if (!BBID)
3281 // Invalid reference to entry block.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003282 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003283 if (!Fn->empty()) {
3284 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003285 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003286 if (BBI == BBE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003287 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003288 ++BBI;
3289 }
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00003290 BB = &*BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003291 } else {
3292 // Otherwise insert a placeholder and remember it so it can be inserted
3293 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00003294 auto &FwdBBs = BasicBlockFwdRefs[Fn];
3295 if (FwdBBs.empty())
3296 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003297 if (FwdBBs.size() < BBID + 1)
3298 FwdBBs.resize(BBID + 1);
3299 if (!FwdBBs[BBID])
3300 FwdBBs[BBID] = BasicBlock::Create(Context);
3301 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003302 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003303 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00003304 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003305 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003306 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003307
David Majnemer8a1c45d2015-12-12 05:38:55 +00003308 ValueList.assignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00003309 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003310 }
3311}
Chris Lattner1314b992007-04-22 06:23:29 +00003312
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003313std::error_code BitcodeReader::parseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00003314 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003315 return error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00003316
Chad Rosierca2567b2011-12-07 21:44:12 +00003317 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003318 SmallVector<uint64_t, 64> Record;
Chad Rosierca2567b2011-12-07 21:44:12 +00003319 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00003320 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003321
Chris Lattner27d38752013-01-20 02:13:19 +00003322 switch (Entry.Kind) {
3323 case BitstreamEntry::SubBlock: // Handled for us already.
3324 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003325 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003326 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003327 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003328 case BitstreamEntry::Record:
3329 // The interesting case.
3330 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003331 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003332
Chad Rosierca2567b2011-12-07 21:44:12 +00003333 // Read a use list record.
3334 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003335 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00003336 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00003337 default: // Default behavior: unknown type.
3338 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003339 case bitc::USELIST_CODE_BB:
3340 IsBB = true;
3341 // fallthrough
3342 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00003343 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003344 if (RecordLength < 3)
3345 // Records should have at least an ID and two indexes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003346 return error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003347 unsigned ID = Record.back();
3348 Record.pop_back();
3349
3350 Value *V;
3351 if (IsBB) {
3352 assert(ID < FunctionBBs.size() && "Basic block not found");
3353 V = FunctionBBs[ID];
3354 } else
3355 V = ValueList[ID];
3356 unsigned NumUses = 0;
3357 SmallDenseMap<const Use *, unsigned, 16> Order;
Rafael Espindola257a3532016-01-15 19:00:20 +00003358 for (const Use &U : V->materialized_uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00003359 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003360 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00003361 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003362 }
3363 if (Order.size() != Record.size() || NumUses > Record.size())
3364 // Mismatches can happen if the functions are being materialized lazily
3365 // (out-of-order), or a value has been upgraded.
3366 break;
3367
3368 V->sortUseList([&](const Use &L, const Use &R) {
3369 return Order.lookup(&L) < Order.lookup(&R);
3370 });
Chad Rosierca2567b2011-12-07 21:44:12 +00003371 break;
3372 }
3373 }
3374 }
3375}
3376
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003377/// When we see the block for metadata, remember where it is and then skip it.
3378/// This lets us lazily deserialize the metadata.
3379std::error_code BitcodeReader::rememberAndSkipMetadata() {
3380 // Save the current stream state.
3381 uint64_t CurBit = Stream.GetCurrentBitNo();
3382 DeferredMetadataInfo.push_back(CurBit);
3383
3384 // Skip over the block for now.
3385 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003386 return error("Invalid record");
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003387 return std::error_code();
3388}
3389
3390std::error_code BitcodeReader::materializeMetadata() {
3391 for (uint64_t BitPos : DeferredMetadataInfo) {
3392 // Move the bit stream to the saved position.
3393 Stream.JumpToBit(BitPos);
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003394 if (std::error_code EC = parseMetadata(true))
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003395 return EC;
3396 }
3397 DeferredMetadataInfo.clear();
3398 return std::error_code();
3399}
3400
Rafael Espindola468b8682015-04-01 14:44:59 +00003401void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00003402
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003403/// When we see the block for a function body, remember where it is and then
3404/// skip it. This lets us lazily deserialize the functions.
3405std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003406 // Get the function we are talking about.
3407 if (FunctionsWithBodies.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003408 return error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003409
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003410 Function *Fn = FunctionsWithBodies.back();
3411 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003412
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003413 // Save the current stream state.
3414 uint64_t CurBit = Stream.GetCurrentBitNo();
Teresa Johnson1493ad92015-10-10 14:18:36 +00003415 assert(
3416 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3417 "Mismatch between VST and scanned function offsets");
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003418 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003419
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003420 // Skip over the function block for now.
3421 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003422 return error("Invalid record");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003423 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003424}
3425
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003426std::error_code BitcodeReader::globalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003427 // Patch the initializers for globals and aliases up.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003428 resolveGlobalAndIndirectSymbolInits();
3429 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003430 return error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003431
3432 // Look for intrinsic functions which need to be upgraded at some point
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003433 for (Function &F : *TheModule) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003434 Function *NewFn;
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003435 if (UpgradeIntrinsicFunction(&F, NewFn))
Rafael Espindola4e721212015-07-02 16:22:40 +00003436 UpgradedIntrinsics[&F] = NewFn;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003437 }
3438
3439 // Look for global variables which need to be renamed.
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003440 for (GlobalVariable &GV : TheModule->globals())
3441 UpgradeGlobalVariable(&GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00003442
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003443 // Force deallocation of memory for these vectors to favor the client that
3444 // want lazy deserialization.
3445 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003446 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap(
3447 IndirectSymbolInits);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003448 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003449}
3450
Teresa Johnson1493ad92015-10-10 14:18:36 +00003451/// Support for lazy parsing of function bodies. This is required if we
3452/// either have an old bitcode file without a VST forward declaration record,
3453/// or if we have an anonymous function being materialized, since anonymous
3454/// functions do not have a name and are therefore not in the VST.
3455std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3456 Stream.JumpToBit(NextUnreadBit);
3457
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003458 if (Stream.AtEndOfStream())
3459 return error("Could not find function in stream");
Teresa Johnson1493ad92015-10-10 14:18:36 +00003460
Filipe Cabecinhas7aae2f22015-11-03 13:48:26 +00003461 if (!SeenFirstFunctionBody)
3462 return error("Trying to materialize functions before seeing function blocks");
3463
Teresa Johnson1493ad92015-10-10 14:18:36 +00003464 // An old bitcode file with the symbol table at the end would have
3465 // finished the parse greedily.
3466 assert(SeenValueSymbolTable);
3467
3468 SmallVector<uint64_t, 64> Record;
3469
3470 while (1) {
3471 BitstreamEntry Entry = Stream.advance();
3472 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003473 default:
3474 return error("Expect SubBlock");
3475 case BitstreamEntry::SubBlock:
3476 switch (Entry.ID) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003477 default:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003478 return error("Expect function block");
3479 case bitc::FUNCTION_BLOCK_ID:
3480 if (std::error_code EC = rememberAndSkipFunctionBody())
3481 return EC;
3482 NextUnreadBit = Stream.GetCurrentBitNo();
3483 return std::error_code();
3484 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00003485 }
3486 }
3487}
3488
Mehdi Amini5d303282015-10-26 18:37:00 +00003489std::error_code BitcodeReader::parseBitcodeVersion() {
3490 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3491 return error("Invalid record");
3492
3493 // Read all the records.
3494 SmallVector<uint64_t, 64> Record;
3495 while (1) {
3496 BitstreamEntry Entry = Stream.advance();
3497
3498 switch (Entry.Kind) {
3499 default:
3500 case BitstreamEntry::Error:
3501 return error("Malformed block");
3502 case BitstreamEntry::EndBlock:
3503 return std::error_code();
3504 case BitstreamEntry::Record:
3505 // The interesting case.
3506 break;
3507 }
3508
3509 // Read a record.
3510 Record.clear();
3511 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3512 switch (BitCode) {
3513 default: // Default behavior: reject
3514 return error("Invalid value");
3515 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3516 // N]
3517 convertToString(Record, 0, ProducerIdentification);
3518 break;
3519 }
3520 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3521 unsigned epoch = (unsigned)Record[0];
3522 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
Oleksiy Vyalov6c2403f2015-10-26 22:37:36 +00003523 return error(
3524 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3525 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
Mehdi Amini5d303282015-10-26 18:37:00 +00003526 }
3527 }
3528 }
3529 }
3530}
3531
Teresa Johnson1493ad92015-10-10 14:18:36 +00003532std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003533 bool ShouldLazyLoadMetadata) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003534 if (ResumeBit)
3535 Stream.JumpToBit(ResumeBit);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003536 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003537 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003538
Chris Lattner1314b992007-04-22 06:23:29 +00003539 SmallVector<uint64_t, 64> Record;
3540 std::vector<std::string> SectionTable;
Gordon Henriksend930f912008-08-17 18:44:35 +00003541 std::vector<std::string> GCTable;
Chris Lattner1314b992007-04-22 06:23:29 +00003542
3543 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00003544 while (1) {
3545 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003546
Chris Lattner27d38752013-01-20 02:13:19 +00003547 switch (Entry.Kind) {
3548 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003549 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003550 case BitstreamEntry::EndBlock:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003551 return globalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00003552
Chris Lattner27d38752013-01-20 02:13:19 +00003553 case BitstreamEntry::SubBlock:
3554 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00003555 default: // Skip unknown content.
3556 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003557 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003558 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003559 case bitc::BLOCKINFO_BLOCK_ID:
3560 if (Stream.ReadBlockInfoBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003561 return error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003562 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003563 case bitc::PARAMATTR_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003564 if (std::error_code EC = parseAttributeBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003565 return EC;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003566 break;
Bill Wendlingba629332013-02-10 23:24:25 +00003567 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003568 if (std::error_code EC = parseAttributeGroupBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003569 return EC;
Bill Wendlingba629332013-02-10 23:24:25 +00003570 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003571 case bitc::TYPE_BLOCK_ID_NEW:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003572 if (std::error_code EC = parseTypeTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003573 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00003574 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00003575 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnsonff642b92015-09-17 20:12:00 +00003576 if (!SeenValueSymbolTable) {
3577 // Either this is an old form VST without function index and an
3578 // associated VST forward declaration record (which would have caused
3579 // the VST to be jumped to and parsed before it was encountered
3580 // normally in the stream), or there were no function blocks to
3581 // trigger an earlier parsing of the VST.
3582 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3583 if (std::error_code EC = parseValueSymbolTable())
3584 return EC;
3585 SeenValueSymbolTable = true;
3586 } else {
3587 // We must have had a VST forward declaration record, which caused
3588 // the parser to jump to and parse the VST earlier.
3589 assert(VSTOffset > 0);
3590 if (Stream.SkipBlock())
3591 return error("Invalid record");
3592 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00003593 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003594 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003595 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003596 return EC;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003597 if (std::error_code EC = resolveGlobalAndIndirectSymbolInits())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003598 return EC;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003599 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00003600 case bitc::METADATA_BLOCK_ID:
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003601 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3602 if (std::error_code EC = rememberAndSkipMetadata())
3603 return EC;
3604 break;
3605 }
3606 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003607 if (std::error_code EC = parseMetadata(true))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003608 return EC;
Devang Patel7428d8a2009-07-22 17:43:22 +00003609 break;
Teresa Johnson12545072015-11-15 02:00:09 +00003610 case bitc::METADATA_KIND_BLOCK_ID:
3611 if (std::error_code EC = parseMetadataKinds())
3612 return EC;
3613 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003614 case bitc::FUNCTION_BLOCK_ID:
3615 // If this is the first function body we've seen, reverse the
3616 // FunctionsWithBodies list.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003617 if (!SeenFirstFunctionBody) {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003618 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003619 if (std::error_code EC = globalCleanup())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003620 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003621 SeenFirstFunctionBody = true;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003622 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003623
Teresa Johnsonff642b92015-09-17 20:12:00 +00003624 if (VSTOffset > 0) {
3625 // If we have a VST forward declaration record, make sure we
3626 // parse the VST now if we haven't already. It is needed to
3627 // set up the DeferredFunctionInfo vector for lazy reading.
3628 if (!SeenValueSymbolTable) {
3629 if (std::error_code EC =
3630 BitcodeReader::parseValueSymbolTable(VSTOffset))
3631 return EC;
3632 SeenValueSymbolTable = true;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003633 // Fall through so that we record the NextUnreadBit below.
3634 // This is necessary in case we have an anonymous function that
3635 // is later materialized. Since it will not have a VST entry we
3636 // need to fall back to the lazy parse to find its offset.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003637 } else {
3638 // If we have a VST forward declaration record, but have already
3639 // parsed the VST (just above, when the first function body was
3640 // encountered here), then we are resuming the parse after
Teresa Johnson1493ad92015-10-10 14:18:36 +00003641 // materializing functions. The ResumeBit points to the
3642 // start of the last function block recorded in the
3643 // DeferredFunctionInfo map. Skip it.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003644 if (Stream.SkipBlock())
3645 return error("Invalid record");
3646 continue;
3647 }
3648 }
3649
3650 // Support older bitcode files that did not have the function
Teresa Johnson1493ad92015-10-10 14:18:36 +00003651 // index in the VST, nor a VST forward declaration record, as
3652 // well as anonymous functions that do not have VST entries.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003653 // Build the DeferredFunctionInfo vector on the fly.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003654 if (std::error_code EC = rememberAndSkipFunctionBody())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003655 return EC;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003656
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003657 // Suspend parsing when we reach the function bodies. Subsequent
3658 // materialization calls will resume it when necessary. If the bitcode
3659 // file is old, the symbol table will be at the end instead and will not
3660 // have been seen yet. In this case, just finish the parse now.
3661 if (SeenValueSymbolTable) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003662 NextUnreadBit = Stream.GetCurrentBitNo();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003663 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003664 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003665 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003666 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003667 if (std::error_code EC = parseUseLists())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003668 return EC;
Chad Rosierca2567b2011-12-07 21:44:12 +00003669 break;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003670 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3671 if (std::error_code EC = parseOperandBundleTags())
3672 return EC;
3673 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003674 }
3675 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003676
Chris Lattner27d38752013-01-20 02:13:19 +00003677 case BitstreamEntry::Record:
3678 // The interesting case.
3679 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003680 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003681
Chris Lattner1314b992007-04-22 06:23:29 +00003682 // Read a record.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003683 auto BitCode = Stream.readRecord(Entry.ID, Record);
3684 switch (BitCode) {
Chris Lattner1314b992007-04-22 06:23:29 +00003685 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungafaced02012-10-11 20:20:40 +00003686 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattner1314b992007-04-22 06:23:29 +00003687 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003688 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00003689 // Only version #0 and #1 are supported so far.
3690 unsigned module_version = Record[0];
3691 switch (module_version) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003692 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003693 return error("Invalid value");
Jan Wen Voungafaced02012-10-11 20:20:40 +00003694 case 0:
3695 UseRelativeIDs = false;
3696 break;
3697 case 1:
3698 UseRelativeIDs = true;
3699 break;
3700 }
Chris Lattner1314b992007-04-22 06:23:29 +00003701 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00003702 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003703 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003704 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003705 if (convertToString(Record, 0, S))
3706 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003707 TheModule->setTargetTriple(S);
3708 break;
3709 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003710 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003711 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003712 if (convertToString(Record, 0, S))
3713 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003714 TheModule->setDataLayout(S);
3715 break;
3716 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003717 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003718 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003719 if (convertToString(Record, 0, S))
3720 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003721 TheModule->setModuleInlineAsm(S);
3722 break;
3723 }
Bill Wendling706d3d62012-11-28 08:41:48 +00003724 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3725 // FIXME: Remove in 4.0.
3726 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003727 if (convertToString(Record, 0, S))
3728 return error("Invalid record");
Bill Wendling706d3d62012-11-28 08:41:48 +00003729 // Ignore value.
3730 break;
3731 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003732 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003733 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003734 if (convertToString(Record, 0, S))
3735 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003736 SectionTable.push_back(S);
3737 break;
3738 }
Gordon Henriksend930f912008-08-17 18:44:35 +00003739 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00003740 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003741 if (convertToString(Record, 0, S))
3742 return error("Invalid record");
Gordon Henriksend930f912008-08-17 18:44:35 +00003743 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00003744 break;
3745 }
David Majnemerdad0a642014-06-27 18:19:56 +00003746 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3747 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003748 return error("Invalid record");
David Majnemerdad0a642014-06-27 18:19:56 +00003749 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3750 unsigned ComdatNameSize = Record[1];
3751 std::string ComdatName;
3752 ComdatName.reserve(ComdatNameSize);
3753 for (unsigned i = 0; i != ComdatNameSize; ++i)
3754 ComdatName += (char)Record[2 + i];
3755 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3756 C->setSelectionKind(SK);
3757 ComdatList.push_back(C);
3758 break;
3759 }
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003760 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00003761 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00003762 // unnamed_addr, externally_initialized, dllstorageclass,
3763 // comdat]
Chris Lattner1314b992007-04-22 06:23:29 +00003764 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner4b00d922007-04-23 16:04:05 +00003765 if (Record.size() < 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003766 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003767 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003768 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003769 return error("Invalid record");
David Blaikie1a848da2015-04-27 19:58:56 +00003770 bool isConstant = Record[1] & 1;
3771 bool explicitType = Record[1] & 2;
3772 unsigned AddressSpace;
3773 if (explicitType) {
3774 AddressSpace = Record[1] >> 2;
3775 } else {
3776 if (!Ty->isPointerTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003777 return error("Invalid type for value");
David Blaikie1a848da2015-04-27 19:58:56 +00003778 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3779 Ty = cast<PointerType>(Ty)->getElementType();
3780 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003781
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003782 uint64_t RawLinkage = Record[3];
3783 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
JF Bastien30bf96b2015-02-22 19:32:03 +00003784 unsigned Alignment;
3785 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3786 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00003787 std::string Section;
3788 if (Record[5]) {
3789 if (Record[5]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003790 return error("Invalid ID");
Chris Lattner1314b992007-04-22 06:23:29 +00003791 Section = SectionTable[Record[5]-1];
3792 }
Chris Lattner4b00d922007-04-23 16:04:05 +00003793 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003794 // Local linkage must have default visibility.
3795 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3796 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003797 Visibility = getDecodedVisibility(Record[6]);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00003798
3799 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner53862f72007-05-06 19:27:46 +00003800 if (Record.size() > 7)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003801 TLM = getDecodedThreadLocalMode(Record[7]);
Chris Lattner1314b992007-04-22 06:23:29 +00003802
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003803 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola45e6c192011-01-08 16:42:36 +00003804 if (Record.size() > 8)
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003805 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003806
Michael Gottesman27e7ef32013-02-05 05:57:38 +00003807 bool ExternallyInitialized = false;
3808 if (Record.size() > 9)
3809 ExternallyInitialized = Record[9];
3810
Chris Lattner1314b992007-04-22 06:23:29 +00003811 GlobalVariable *NewGV =
Craig Topper2617dcc2014-04-15 06:32:26 +00003812 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
Michael Gottesman27e7ef32013-02-05 05:57:38 +00003813 TLM, AddressSpace, ExternallyInitialized);
Chris Lattner1314b992007-04-22 06:23:29 +00003814 NewGV->setAlignment(Alignment);
3815 if (!Section.empty())
3816 NewGV->setSection(Section);
3817 NewGV->setVisibility(Visibility);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003818 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003819
Nico Rieck7157bb72014-01-14 15:22:47 +00003820 if (Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003821 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003822 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003823 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00003824
Chris Lattnerccaa4482007-04-23 21:26:05 +00003825 ValueList.push_back(NewGV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003826
Chris Lattner47d131b2007-04-24 00:18:21 +00003827 // Remember which value to use for the global initializer.
3828 if (unsigned InitID = Record[2])
3829 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
David Majnemerdad0a642014-06-27 18:19:56 +00003830
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003831 if (Record.size() > 11) {
David Majnemerdad0a642014-06-27 18:19:56 +00003832 if (unsigned ComdatID = Record[11]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00003833 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003834 return error("Invalid global variable comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00003835 NewGV->setComdat(ComdatList[ComdatID - 1]);
3836 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003837 } else if (hasImplicitComdat(RawLinkage)) {
3838 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3839 }
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003840
Chris Lattner1314b992007-04-22 06:23:29 +00003841 break;
3842 }
Peter Collingbournecceae7f2016-05-31 23:01:54 +00003843 case bitc::MODULE_CODE_GLOBALVAR_ATTACHMENT: {
3844 if (Record.size() % 2 == 0)
3845 return error("Invalid record");
3846 unsigned ValueID = Record[0];
3847 if (ValueID >= ValueList.size())
3848 return error("Invalid record");
3849 if (auto *GV = dyn_cast<GlobalVariable>(ValueList[ValueID]))
3850 parseGlobalObjectAttachment(*GV, ArrayRef<uint64_t>(Record).slice(1));
3851 break;
3852 }
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003853 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Nico Rieck7157bb72014-01-14 15:22:47 +00003854 // alignment, section, visibility, gc, unnamed_addr,
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003855 // prologuedata, dllstorageclass, comdat, prefixdata]
Chris Lattner1314b992007-04-22 06:23:29 +00003856 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003857 if (Record.size() < 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003858 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003859 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003860 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003861 return error("Invalid record");
David Blaikie561a1572015-04-17 16:28:26 +00003862 if (auto *PTy = dyn_cast<PointerType>(Ty))
3863 Ty = PTy->getElementType();
3864 auto *FTy = dyn_cast<FunctionType>(Ty);
Chris Lattner1314b992007-04-22 06:23:29 +00003865 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003866 return error("Invalid type for value");
Vedant Kumarad6d6e72015-10-27 21:17:06 +00003867 auto CC = static_cast<CallingConv::ID>(Record[1]);
3868 if (CC & ~CallingConv::MaxID)
3869 return error("Invalid calling convention ID");
Chris Lattner1314b992007-04-22 06:23:29 +00003870
Gabor Greife9ecc682008-04-06 20:25:17 +00003871 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3872 "", TheModule);
Chris Lattner1314b992007-04-22 06:23:29 +00003873
Vedant Kumarad6d6e72015-10-27 21:17:06 +00003874 Func->setCallingConv(CC);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003875 bool isProto = Record[2];
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003876 uint64_t RawLinkage = Record[3];
3877 Func->setLinkage(getDecodedLinkage(RawLinkage));
Devang Patel4c758ea2008-09-25 21:00:45 +00003878 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003879
JF Bastien30bf96b2015-02-22 19:32:03 +00003880 unsigned Alignment;
3881 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3882 return EC;
3883 Func->setAlignment(Alignment);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003884 if (Record[6]) {
3885 if (Record[6]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003886 return error("Invalid ID");
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003887 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattner1314b992007-04-22 06:23:29 +00003888 }
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003889 // Local linkage must have default visibility.
3890 if (!Func->hasLocalLinkage())
3891 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003892 Func->setVisibility(getDecodedVisibility(Record[7]));
Gordon Henriksen71183b62007-12-10 03:18:06 +00003893 if (Record.size() > 8 && Record[8]) {
Filipe Cabecinhasf8a16a92015-04-30 04:09:41 +00003894 if (Record[8]-1 >= GCTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003895 return error("Invalid ID");
Benjamin Kramer728f4442016-05-29 10:46:35 +00003896 Func->setGC(GCTable[Record[8] - 1]);
Gordon Henriksen71183b62007-12-10 03:18:06 +00003897 }
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003898 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola45e6c192011-01-08 16:42:36 +00003899 if (Record.size() > 9)
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003900 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003901 Func->setUnnamedAddr(UnnamedAddr);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003902 if (Record.size() > 10 && Record[10] != 0)
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003903 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
Nico Rieck7157bb72014-01-14 15:22:47 +00003904
3905 if (Record.size() > 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003906 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003907 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003908 upgradeDLLImportExportLinkage(Func, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00003909
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003910 if (Record.size() > 12) {
David Majnemerdad0a642014-06-27 18:19:56 +00003911 if (unsigned ComdatID = Record[12]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00003912 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003913 return error("Invalid function comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00003914 Func->setComdat(ComdatList[ComdatID - 1]);
3915 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003916 } else if (hasImplicitComdat(RawLinkage)) {
3917 Func->setComdat(reinterpret_cast<Comdat *>(1));
3918 }
David Majnemerdad0a642014-06-27 18:19:56 +00003919
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003920 if (Record.size() > 13 && Record[13] != 0)
3921 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3922
David Majnemer7fddecc2015-06-17 20:52:32 +00003923 if (Record.size() > 14 && Record[14] != 0)
3924 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3925
Chris Lattnerccaa4482007-04-23 21:26:05 +00003926 ValueList.push_back(Func);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003927
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003928 // If this is a function with a body, remember the prototype we are
3929 // creating now, so that we can match up the body with them later.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003930 if (!isProto) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00003931 Func->setIsMaterializable(true);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003932 FunctionsWithBodies.push_back(Func);
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003933 DeferredFunctionInfo[Func] = 0;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003934 }
Chris Lattner1314b992007-04-22 06:23:29 +00003935 break;
3936 }
David Blaikie6a51dbd2015-09-17 22:18:59 +00003937 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3938 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003939 // IFUNC: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3940 case bitc::MODULE_CODE_IFUNC:
David Blaikie6a51dbd2015-09-17 22:18:59 +00003941 case bitc::MODULE_CODE_ALIAS:
3942 case bitc::MODULE_CODE_ALIAS_OLD: {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003943 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
Aaron Ballman2d0f38c2015-09-18 13:31:42 +00003944 if (Record.size() < (3 + (unsigned)NewRecord))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003945 return error("Invalid record");
David Blaikie6a51dbd2015-09-17 22:18:59 +00003946 unsigned OpNum = 0;
3947 Type *Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003948 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003949 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003950
David Blaikie6a51dbd2015-09-17 22:18:59 +00003951 unsigned AddrSpace;
3952 if (!NewRecord) {
3953 auto *PTy = dyn_cast<PointerType>(Ty);
3954 if (!PTy)
3955 return error("Invalid type for value");
3956 Ty = PTy->getElementType();
3957 AddrSpace = PTy->getAddressSpace();
3958 } else {
3959 AddrSpace = Record[OpNum++];
3960 }
3961
3962 auto Val = Record[OpNum++];
3963 auto Linkage = Record[OpNum++];
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003964 GlobalIndirectSymbol *NewGA;
3965 if (BitCode == bitc::MODULE_CODE_ALIAS ||
3966 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003967 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
3968 "", TheModule);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003969 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003970 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
3971 "", nullptr, TheModule);
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00003972 // Old bitcode files didn't have visibility field.
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003973 // Local linkage must have default visibility.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003974 if (OpNum != Record.size()) {
3975 auto VisInd = OpNum++;
3976 if (!NewGA->hasLocalLinkage())
3977 // FIXME: Change to an error if non-default in 4.0.
3978 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3979 }
3980 if (OpNum != Record.size())
3981 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003982 else
David Blaikie6a51dbd2015-09-17 22:18:59 +00003983 upgradeDLLImportExportLinkage(NewGA, Linkage);
3984 if (OpNum != Record.size())
3985 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3986 if (OpNum != Record.size())
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003987 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
Chris Lattner44c17072007-04-26 02:46:40 +00003988 ValueList.push_back(NewGA);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003989 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
Chris Lattner44c17072007-04-26 02:46:40 +00003990 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003991 }
Chris Lattner831d4202007-04-26 03:27:58 +00003992 /// MODULE_CODE_PURGEVALS: [numvals]
3993 case bitc::MODULE_CODE_PURGEVALS:
3994 // Trim down the value list to the specified size.
3995 if (Record.size() < 1 || Record[0] > ValueList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003996 return error("Invalid record");
Chris Lattner831d4202007-04-26 03:27:58 +00003997 ValueList.shrinkTo(Record[0]);
3998 break;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003999 /// MODULE_CODE_VSTOFFSET: [offset]
4000 case bitc::MODULE_CODE_VSTOFFSET:
4001 if (Record.size() < 1)
4002 return error("Invalid record");
4003 VSTOffset = Record[0];
4004 break;
Teresa Johnsone1164de2016-02-10 21:55:02 +00004005 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4006 case bitc::MODULE_CODE_SOURCE_FILENAME:
4007 SmallString<128> ValueName;
4008 if (convertToString(Record, 0, ValueName))
4009 return error("Invalid record");
4010 TheModule->setSourceFileName(ValueName);
4011 break;
Chris Lattner831d4202007-04-26 03:27:58 +00004012 }
Chris Lattner1314b992007-04-22 06:23:29 +00004013 Record.clear();
4014 }
Chris Lattner1314b992007-04-22 06:23:29 +00004015}
4016
Teresa Johnson403a7872015-10-04 14:33:43 +00004017/// Helper to read the header common to all bitcode files.
4018static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
4019 // Sniff for the signature.
4020 if (Stream.Read(8) != 'B' ||
4021 Stream.Read(8) != 'C' ||
4022 Stream.Read(4) != 0x0 ||
4023 Stream.Read(4) != 0xC ||
4024 Stream.Read(4) != 0xE ||
4025 Stream.Read(4) != 0xD)
4026 return false;
4027 return true;
4028}
4029
Rafael Espindola1aabf982015-06-16 23:29:49 +00004030std::error_code
4031BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
4032 Module *M, bool ShouldLazyLoadMetadata) {
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00004033 TheModule = M;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004034
Rafael Espindola1aabf982015-06-16 23:29:49 +00004035 if (std::error_code EC = initStream(std::move(Streamer)))
Rafael Espindola48da4f42013-11-04 16:16:24 +00004036 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004037
Chris Lattner1314b992007-04-22 06:23:29 +00004038 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004039 if (!hasValidBitcodeHeader(Stream))
4040 return error("Invalid bitcode signature");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004041
Chris Lattner1314b992007-04-22 06:23:29 +00004042 // We expect a number of well-defined blocks, though we don't necessarily
4043 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00004044 while (1) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00004045 if (Stream.AtEndOfStream()) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00004046 // We didn't really read a proper Module.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004047 return error("Malformed IR file");
Filipe Cabecinhas22554272015-04-14 14:07:15 +00004048 }
Joe Abbey97b7a172013-02-06 22:14:06 +00004049
Chris Lattner27d38752013-01-20 02:13:19 +00004050 BitstreamEntry Entry =
4051 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbey97b7a172013-02-06 22:14:06 +00004052
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00004053 if (Entry.Kind != BitstreamEntry::SubBlock)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004054 return error("Malformed block");
Joe Abbey97b7a172013-02-06 22:14:06 +00004055
Mehdi Amini5d303282015-10-26 18:37:00 +00004056 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
4057 parseBitcodeVersion();
4058 continue;
4059 }
4060
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00004061 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Teresa Johnson1493ad92015-10-10 14:18:36 +00004062 return parseModule(0, ShouldLazyLoadMetadata);
Joe Abbey97b7a172013-02-06 22:14:06 +00004063
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00004064 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004065 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00004066 }
Chris Lattner1314b992007-04-22 06:23:29 +00004067}
Chris Lattner6694f602007-04-29 07:54:31 +00004068
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004069ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
Bill Wendling0198ce02010-10-06 01:22:42 +00004070 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004071 return error("Invalid record");
Bill Wendling0198ce02010-10-06 01:22:42 +00004072
4073 SmallVector<uint64_t, 64> Record;
4074
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004075 std::string Triple;
Bill Wendling0198ce02010-10-06 01:22:42 +00004076 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00004077 while (1) {
4078 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00004079
Chris Lattner27d38752013-01-20 02:13:19 +00004080 switch (Entry.Kind) {
4081 case BitstreamEntry::SubBlock: // Handled for us already.
4082 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004083 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004084 case BitstreamEntry::EndBlock:
Rafael Espindolae6107792014-07-04 20:05:56 +00004085 return Triple;
Chris Lattner27d38752013-01-20 02:13:19 +00004086 case BitstreamEntry::Record:
4087 // The interesting case.
4088 break;
Bill Wendling0198ce02010-10-06 01:22:42 +00004089 }
4090
4091 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00004092 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling0198ce02010-10-06 01:22:42 +00004093 default: break; // Default behavior, ignore unknown content.
Bill Wendling0198ce02010-10-06 01:22:42 +00004094 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004095 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004096 if (convertToString(Record, 0, S))
4097 return error("Invalid record");
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004098 Triple = S;
Bill Wendling0198ce02010-10-06 01:22:42 +00004099 break;
4100 }
4101 }
4102 Record.clear();
4103 }
Rafael Espindolae6107792014-07-04 20:05:56 +00004104 llvm_unreachable("Exit infinite loop");
Bill Wendling0198ce02010-10-06 01:22:42 +00004105}
4106
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004107ErrorOr<std::string> BitcodeReader::parseTriple() {
Rafael Espindola1aabf982015-06-16 23:29:49 +00004108 if (std::error_code EC = initStream(nullptr))
Rafael Espindola48da4f42013-11-04 16:16:24 +00004109 return EC;
Bill Wendling0198ce02010-10-06 01:22:42 +00004110
4111 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004112 if (!hasValidBitcodeHeader(Stream))
4113 return error("Invalid bitcode signature");
Bill Wendling0198ce02010-10-06 01:22:42 +00004114
4115 // We expect a number of well-defined blocks, though we don't necessarily
4116 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00004117 while (1) {
4118 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00004119
Chris Lattner27d38752013-01-20 02:13:19 +00004120 switch (Entry.Kind) {
4121 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004122 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004123 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004124 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00004125
Chris Lattner27d38752013-01-20 02:13:19 +00004126 case BitstreamEntry::SubBlock:
4127 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Rafael Espindolad346cc82014-07-04 13:52:01 +00004128 return parseModuleTriple();
Joe Abbey97b7a172013-02-06 22:14:06 +00004129
Chris Lattner27d38752013-01-20 02:13:19 +00004130 // Ignore other sub-blocks.
Rafael Espindola48da4f42013-11-04 16:16:24 +00004131 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004132 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004133 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00004134
Chris Lattner27d38752013-01-20 02:13:19 +00004135 case BitstreamEntry::Record:
4136 Stream.skipRecord(Entry.ID);
4137 continue;
Bill Wendling0198ce02010-10-06 01:22:42 +00004138 }
4139 }
Bill Wendling0198ce02010-10-06 01:22:42 +00004140}
4141
Mehdi Amini3383ccc2015-11-09 02:46:41 +00004142ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
4143 if (std::error_code EC = initStream(nullptr))
4144 return EC;
4145
4146 // Sniff for the signature.
4147 if (!hasValidBitcodeHeader(Stream))
4148 return error("Invalid bitcode signature");
4149
4150 // We expect a number of well-defined blocks, though we don't necessarily
4151 // need to understand them all.
4152 while (1) {
4153 BitstreamEntry Entry = Stream.advance();
4154 switch (Entry.Kind) {
4155 case BitstreamEntry::Error:
4156 return error("Malformed block");
4157 case BitstreamEntry::EndBlock:
4158 return std::error_code();
4159
4160 case BitstreamEntry::SubBlock:
4161 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
4162 if (std::error_code EC = parseBitcodeVersion())
4163 return EC;
4164 return ProducerIdentification;
4165 }
4166 // Ignore other sub-blocks.
4167 if (Stream.SkipBlock())
4168 return error("Malformed block");
4169 continue;
4170 case BitstreamEntry::Record:
4171 Stream.skipRecord(Entry.ID);
4172 continue;
4173 }
4174 }
4175}
4176
Peter Collingbournecceae7f2016-05-31 23:01:54 +00004177std::error_code BitcodeReader::parseGlobalObjectAttachment(
4178 GlobalObject &GO, ArrayRef<uint64_t> Record) {
4179 assert(Record.size() % 2 == 0);
4180 for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
4181 auto K = MDKindMap.find(Record[I]);
4182 if (K == MDKindMap.end())
4183 return error("Invalid ID");
4184 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
4185 if (!MD)
4186 return error("Invalid metadata attachment");
Peter Collingbourne382d81c2016-06-01 01:17:57 +00004187 GO.addMetadata(K->second, *MD);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00004188 }
4189 return std::error_code();
4190}
4191
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004192/// Parse metadata attachments.
4193std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
Devang Patelaf206b82009-09-18 19:26:43 +00004194 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004195 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004196
Devang Patelaf206b82009-09-18 19:26:43 +00004197 SmallVector<uint64_t, 64> Record;
Chris Lattner27d38752013-01-20 02:13:19 +00004198 while (1) {
4199 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00004200
Chris Lattner27d38752013-01-20 02:13:19 +00004201 switch (Entry.Kind) {
4202 case BitstreamEntry::SubBlock: // Handled for us already.
4203 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004204 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004205 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004206 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00004207 case BitstreamEntry::Record:
4208 // The interesting case.
Devang Patelaf206b82009-09-18 19:26:43 +00004209 break;
4210 }
Chris Lattner27d38752013-01-20 02:13:19 +00004211
Devang Patelaf206b82009-09-18 19:26:43 +00004212 // Read a metadata attachment record.
4213 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00004214 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patelaf206b82009-09-18 19:26:43 +00004215 default: // Default behavior: ignore.
4216 break;
Chris Lattnerb8778552011-06-17 17:50:30 +00004217 case bitc::METADATA_ATTACHMENT: {
Devang Patelaf206b82009-09-18 19:26:43 +00004218 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00004219 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004220 return error("Invalid record");
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00004221 if (RecordLength % 2 == 0) {
4222 // A function attachment.
Peter Collingbournecceae7f2016-05-31 23:01:54 +00004223 if (std::error_code EC = parseGlobalObjectAttachment(F, Record))
4224 return EC;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00004225 continue;
4226 }
4227
4228 // An instruction attachment.
Devang Patelaf206b82009-09-18 19:26:43 +00004229 Instruction *Inst = InstructionList[Record[0]];
4230 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patelb1a44772009-09-28 21:14:55 +00004231 unsigned Kind = Record[i];
Dan Gohman43aa8f02010-07-20 21:42:28 +00004232 DenseMap<unsigned, unsigned>::iterator I =
4233 MDKindMap.find(Kind);
4234 if (I == MDKindMap.end())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004235 return error("Invalid ID");
Justin Bognerae341c62016-03-17 20:12:06 +00004236 Metadata *Node = MetadataList.getMetadataFwdRef(Record[i + 1]);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004237 if (isa<LocalAsMetadata>(Node))
Duncan P. N. Exon Smith35303fd2014-12-06 02:29:44 +00004238 // Drop the attachment. This used to be legal, but there's no
4239 // upgrade path.
4240 break;
Justin Bognerae341c62016-03-17 20:12:06 +00004241 MDNode *MD = dyn_cast_or_null<MDNode>(Node);
4242 if (!MD)
4243 return error("Invalid metadata attachment");
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00004244
4245 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
4246 MD = upgradeInstructionLoopAttachment(*MD);
4247
Justin Bognerae341c62016-03-17 20:12:06 +00004248 Inst->setMetadata(I->second, MD);
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00004249 if (I->second == LLVMContext::MD_tbaa) {
Manman Ren209b17c2013-09-28 00:22:27 +00004250 InstsWithTBAATag.push_back(Inst);
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00004251 continue;
4252 }
Devang Patelaf206b82009-09-18 19:26:43 +00004253 }
4254 break;
4255 }
4256 }
4257 }
Devang Patelaf206b82009-09-18 19:26:43 +00004258}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004259
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004260static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
4261 LLVMContext &Context = PtrType->getContext();
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004262 if (!isa<PointerType>(PtrType))
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004263 return error(Context, "Load/Store operand is not a pointer type");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004264 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
4265
4266 if (ValType && ValType != ElemType)
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004267 return error(Context, "Explicit load/store type does not match pointee "
4268 "type of pointer operand");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004269 if (!PointerType::isLoadableOrStorableType(ElemType))
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004270 return error(Context, "Cannot load/store from pointer");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004271 return std::error_code();
4272}
4273
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004274/// Lazily parse the specified function body block.
4275std::error_code BitcodeReader::parseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00004276 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004277 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004278
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00004279 // Unexpected unresolved metadata when parsing function.
4280 if (MetadataList.hasFwdRefs())
4281 return error("Invalid function metadata: incoming forward references");
4282
Nick Lewyckya72e1af2010-02-25 08:30:17 +00004283 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00004284 unsigned ModuleValueListSize = ValueList.size();
Teresa Johnson61b406e2015-12-29 23:00:22 +00004285 unsigned ModuleMetadataListSize = MetadataList.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004286
Chris Lattner85b7b402007-05-01 05:52:21 +00004287 // Add all the function arguments to the value table.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00004288 for (Argument &I : F->args())
4289 ValueList.push_back(&I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004290
Chris Lattner83930552007-05-01 07:01:57 +00004291 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00004292 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00004293 unsigned CurBBNo = 0;
4294
Chris Lattner07d09ed2010-04-03 02:17:50 +00004295 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004296 auto getLastInstruction = [&]() -> Instruction * {
4297 if (CurBB && !CurBB->empty())
4298 return &CurBB->back();
4299 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4300 !FunctionBBs[CurBBNo - 1]->empty())
4301 return &FunctionBBs[CurBBNo - 1]->back();
4302 return nullptr;
4303 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004304
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004305 std::vector<OperandBundleDef> OperandBundles;
4306
Chris Lattner85b7b402007-05-01 05:52:21 +00004307 // Read all the records.
4308 SmallVector<uint64_t, 64> Record;
4309 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00004310 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00004311
Chris Lattner27d38752013-01-20 02:13:19 +00004312 switch (Entry.Kind) {
4313 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004314 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004315 case BitstreamEntry::EndBlock:
4316 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00004317
Chris Lattner27d38752013-01-20 02:13:19 +00004318 case BitstreamEntry::SubBlock:
4319 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00004320 default: // Skip unknown content.
4321 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004322 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00004323 break;
4324 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004325 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004326 return EC;
Chris Lattner83930552007-05-01 07:01:57 +00004327 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00004328 break;
4329 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004330 if (std::error_code EC = parseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004331 return EC;
Chris Lattner85b7b402007-05-01 05:52:21 +00004332 break;
Devang Patelaf206b82009-09-18 19:26:43 +00004333 case bitc::METADATA_ATTACHMENT_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004334 if (std::error_code EC = parseMetadataAttachment(*F))
Rafael Espindola48da4f42013-11-04 16:16:24 +00004335 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004336 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00004337 case bitc::METADATA_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004338 if (std::error_code EC = parseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004339 return EC;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00004340 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004341 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004342 if (std::error_code EC = parseUseLists())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004343 return EC;
4344 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00004345 }
4346 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00004347
Chris Lattner27d38752013-01-20 02:13:19 +00004348 case BitstreamEntry::Record:
4349 // The interesting case.
4350 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00004351 }
Joe Abbey97b7a172013-02-06 22:14:06 +00004352
Chris Lattner85b7b402007-05-01 05:52:21 +00004353 // Read a record.
4354 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00004355 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00004356 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00004357 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00004358 default: // Default behavior: reject
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004359 return error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004360 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00004361 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004362 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00004363 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00004364 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004365
4366 // See if anything took the address of blocks in this function.
4367 auto BBFRI = BasicBlockFwdRefs.find(F);
4368 if (BBFRI == BasicBlockFwdRefs.end()) {
4369 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4370 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
4371 } else {
4372 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00004373 // Check for invalid basic block references.
4374 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004375 return error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00004376 assert(!BBRefs.empty() && "Unexpected empty array");
4377 assert(!BBRefs.front() && "Invalid reference to entry block");
4378 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4379 ++I)
4380 if (I < RE && BBRefs[I]) {
4381 BBRefs[I]->insertInto(F);
4382 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004383 } else {
4384 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4385 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004386
4387 // Erase from the table.
4388 BasicBlockFwdRefs.erase(BBFRI);
4389 }
4390
Chris Lattner83930552007-05-01 07:01:57 +00004391 CurBB = FunctionBBs[0];
4392 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004393 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004394
Chris Lattner07d09ed2010-04-03 02:17:50 +00004395 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4396 // This record indicates that the last instruction is at the same
4397 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004398 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004399
Craig Topper2617dcc2014-04-15 06:32:26 +00004400 if (!I)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004401 return error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00004402 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004403 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004404 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004405
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00004406 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004407 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00004408 if (!I || Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004409 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004410
Chris Lattner07d09ed2010-04-03 02:17:50 +00004411 unsigned Line = Record[0], Col = Record[1];
4412 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004413
Craig Topper2617dcc2014-04-15 06:32:26 +00004414 MDNode *Scope = nullptr, *IA = nullptr;
Justin Bognerae341c62016-03-17 20:12:06 +00004415 if (ScopeID) {
4416 Scope = MetadataList.getMDNodeFwdRefOrNull(ScopeID - 1);
4417 if (!Scope)
4418 return error("Invalid record");
4419 }
4420 if (IAID) {
4421 IA = MetadataList.getMDNodeFwdRefOrNull(IAID - 1);
4422 if (!IA)
4423 return error("Invalid record");
4424 }
Chris Lattner07d09ed2010-04-03 02:17:50 +00004425 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4426 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004427 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004428 continue;
4429 }
4430
Chris Lattnere9759c22007-05-06 00:21:25 +00004431 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4432 unsigned OpNum = 0;
4433 Value *LHS, *RHS;
4434 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004435 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00004436 OpNum+1 > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004437 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004438
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004439 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00004440 if (Opc == -1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004441 return error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004442 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00004443 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00004444 if (OpNum < Record.size()) {
4445 if (Opc == Instruction::Add ||
4446 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00004447 Opc == Instruction::Mul ||
4448 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00004449 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00004450 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00004451 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00004452 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00004453 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00004454 Opc == Instruction::UDiv ||
4455 Opc == Instruction::LShr ||
4456 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00004457 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00004458 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004459 } else if (isa<FPMathOperator>(I)) {
James Molloy88eb5352015-07-10 12:52:00 +00004460 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004461 if (FMF.any())
4462 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00004463 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004464
Dan Gohman1b849082009-09-07 23:54:19 +00004465 }
Chris Lattner85b7b402007-05-01 05:52:21 +00004466 break;
4467 }
Chris Lattnere9759c22007-05-06 00:21:25 +00004468 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4469 unsigned OpNum = 0;
4470 Value *Op;
4471 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4472 OpNum+2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004473 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004474
Chris Lattner229907c2011-07-18 04:54:35 +00004475 Type *ResTy = getTypeByID(Record[OpNum]);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004476 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004477 if (Opc == -1 || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004478 return error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00004479 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004480 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4481 if (Temp) {
4482 InstructionList.push_back(Temp);
4483 CurBB->getInstList().push_back(Temp);
4484 }
4485 } else {
Filipe Cabecinhasb70fd872015-10-06 12:37:54 +00004486 auto CastOp = (Instruction::CastOps)Opc;
4487 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4488 return error("Invalid cast");
4489 I = CastInst::Create(CastOp, Op, ResTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004490 }
Devang Patelaf206b82009-09-18 19:26:43 +00004491 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004492 break;
4493 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00004494 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4495 case bitc::FUNC_CODE_INST_GEP_OLD:
4496 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004497 unsigned OpNum = 0;
David Blaikieb5b5efd2015-02-25 01:08:52 +00004498
4499 Type *Ty;
4500 bool InBounds;
4501
4502 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4503 InBounds = Record[OpNum++];
4504 Ty = getTypeByID(Record[OpNum++]);
4505 } else {
4506 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4507 Ty = nullptr;
4508 }
4509
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004510 Value *BasePtr;
4511 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004512 return error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00004513
David Blaikie60310f22015-05-08 00:42:26 +00004514 if (!Ty)
4515 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4516 ->getElementType();
4517 else if (Ty !=
4518 cast<SequentialType>(BasePtr->getType()->getScalarType())
4519 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004520 return error(
David Blaikie675e8cb2015-03-16 21:35:48 +00004521 "Explicit gep type does not match pointee type of pointer operand");
4522
Chris Lattner5285b5e2007-05-02 05:46:45 +00004523 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004524 while (OpNum != Record.size()) {
4525 Value *Op;
4526 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004527 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004528 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004529 }
4530
David Blaikie096b1da2015-03-14 19:53:33 +00004531 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
David Blaikie675e8cb2015-03-16 21:35:48 +00004532
Devang Patelaf206b82009-09-18 19:26:43 +00004533 InstructionList.push_back(I);
David Blaikieb5b5efd2015-02-25 01:08:52 +00004534 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004535 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004536 break;
4537 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004538
Dan Gohman1ecaf452008-05-31 00:58:22 +00004539 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4540 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00004541 unsigned OpNum = 0;
4542 Value *Agg;
4543 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004544 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004545
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004546 unsigned RecSize = Record.size();
4547 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004548 return error("EXTRACTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004549
Dan Gohman1ecaf452008-05-31 00:58:22 +00004550 SmallVector<unsigned, 4> EXTRACTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004551 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004552 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004553 bool IsArray = CurTy->isArrayTy();
4554 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00004555 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004556
4557 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004558 return error("EXTRACTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004559 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004560 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004561 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004562 return error("EXTRACTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004563 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004564 return error("EXTRACTVAL: Invalid array index");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004565 EXTRACTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004566
4567 if (IsStruct)
4568 CurTy = CurTy->subtypes()[Index];
4569 else
4570 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00004571 }
4572
Jay Foad57aa6362011-07-13 10:26:04 +00004573 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00004574 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00004575 break;
4576 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004577
Dan Gohman1ecaf452008-05-31 00:58:22 +00004578 case bitc::FUNC_CODE_INST_INSERTVAL: {
4579 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00004580 unsigned OpNum = 0;
4581 Value *Agg;
4582 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004583 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004584 Value *Val;
4585 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004586 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004587
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004588 unsigned RecSize = Record.size();
4589 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004590 return error("INSERTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004591
Dan Gohman1ecaf452008-05-31 00:58:22 +00004592 SmallVector<unsigned, 4> INSERTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004593 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004594 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004595 bool IsArray = CurTy->isArrayTy();
4596 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00004597 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004598
4599 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004600 return error("INSERTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004601 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004602 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004603 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004604 return error("INSERTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004605 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004606 return error("INSERTVAL: Invalid array index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004607
Dan Gohman1ecaf452008-05-31 00:58:22 +00004608 INSERTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004609 if (IsStruct)
4610 CurTy = CurTy->subtypes()[Index];
4611 else
4612 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00004613 }
4614
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00004615 if (CurTy != Val->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004616 return error("Inserted value type doesn't match aggregate type");
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00004617
Jay Foad57aa6362011-07-13 10:26:04 +00004618 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00004619 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00004620 break;
4621 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004622
Chris Lattnere9759c22007-05-06 00:21:25 +00004623 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00004624 // obsolete form of select
4625 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00004626 unsigned OpNum = 0;
4627 Value *TrueVal, *FalseVal, *Cond;
4628 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004629 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4630 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004631 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004632
Dan Gohmanc5d28922008-09-16 01:01:33 +00004633 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00004634 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00004635 break;
4636 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004637
Dan Gohmanc5d28922008-09-16 01:01:33 +00004638 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4639 // new form of select
4640 // handles select i1 or select [N x i1]
4641 unsigned OpNum = 0;
4642 Value *TrueVal, *FalseVal, *Cond;
4643 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004644 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00004645 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004646 return error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00004647
4648 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00004649 if (VectorType* vector_type =
4650 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00004651 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004652 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004653 return error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00004654 } else {
4655 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004656 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004657 return error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004658 }
4659
Gabor Greife9ecc682008-04-06 20:25:17 +00004660 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00004661 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004662 break;
4663 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004664
Chris Lattner1fc27f02007-05-02 05:16:49 +00004665 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00004666 unsigned OpNum = 0;
4667 Value *Vec, *Idx;
4668 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00004669 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004670 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004671 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004672 return error("Invalid type for value");
Eric Christopherc9742252009-07-25 02:28:41 +00004673 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00004674 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004675 break;
4676 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004677
Chris Lattner1fc27f02007-05-02 05:16:49 +00004678 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00004679 unsigned OpNum = 0;
4680 Value *Vec, *Elt, *Idx;
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004681 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004682 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004683 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004684 return error("Invalid type for value");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004685 if (popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00004686 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00004687 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004688 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00004689 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00004690 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004691 break;
4692 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004693
Chris Lattnere9759c22007-05-06 00:21:25 +00004694 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4695 unsigned OpNum = 0;
4696 Value *Vec1, *Vec2, *Mask;
4697 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004698 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004699 return error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00004700
Mon P Wang25f01062008-11-10 04:46:22 +00004701 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004702 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004703 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004704 return error("Invalid type for value");
Chris Lattner1fc27f02007-05-02 05:16:49 +00004705 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00004706 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004707 break;
4708 }
Mon P Wang25f01062008-11-10 04:46:22 +00004709
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004710 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4711 // Old form of ICmp/FCmp returning bool
4712 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4713 // both legal on vectors but had different behaviour.
4714 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4715 // FCmp/ICmp returning bool or vector of bool
4716
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004717 unsigned OpNum = 0;
4718 Value *LHS, *RHS;
4719 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
James Molloy88eb5352015-07-10 12:52:00 +00004720 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4721 return error("Invalid record");
4722
4723 unsigned PredVal = Record[OpNum];
4724 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4725 FastMathFlags FMF;
4726 if (IsFP && Record.size() > OpNum+1)
4727 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4728
4729 if (OpNum+1 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004730 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004731
Duncan Sands9dff9be2010-02-15 16:12:20 +00004732 if (LHS->getType()->isFPOrFPVectorTy())
James Molloy88eb5352015-07-10 12:52:00 +00004733 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004734 else
James Molloy88eb5352015-07-10 12:52:00 +00004735 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4736
4737 if (FMF.any())
4738 I->setFastMathFlags(FMF);
Devang Patelaf206b82009-09-18 19:26:43 +00004739 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00004740 break;
4741 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004742
Chris Lattnere53603e2007-05-02 04:27:25 +00004743 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00004744 {
4745 unsigned Size = Record.size();
4746 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00004747 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004748 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00004749 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004750 }
Devang Patelbbfd8742008-02-26 01:29:32 +00004751
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004752 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004753 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00004754 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004755 return error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00004756 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004757 return error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004758
Chris Lattnerf1c87102011-06-17 18:09:11 +00004759 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004760 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004761 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00004762 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004763 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00004764 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004765 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004766 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004767 if (!TrueDest)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004768 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004769
Devang Patelaf206b82009-09-18 19:26:43 +00004770 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00004771 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004772 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00004773 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004774 else {
4775 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004776 Value *Cond = getValue(Record, 2, NextValueNo,
4777 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00004778 if (!FalseDest || !Cond)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004779 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00004780 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004781 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004782 }
4783 break;
4784 }
David Majnemerb01aa9f2015-08-23 19:22:31 +00004785 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004786 if (Record.size() != 1 && Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00004787 return error("Invalid record");
4788 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004789 Value *CleanupPad =
4790 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004791 if (!CleanupPad)
David Majnemer654e1302015-07-31 17:58:14 +00004792 return error("Invalid record");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004793 BasicBlock *UnwindDest = nullptr;
4794 if (Record.size() == 2) {
David Majnemer654e1302015-07-31 17:58:14 +00004795 UnwindDest = getBasicBlock(Record[Idx++]);
4796 if (!UnwindDest)
4797 return error("Invalid record");
4798 }
4799
David Majnemer8a1c45d2015-12-12 05:38:55 +00004800 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
David Majnemer654e1302015-07-31 17:58:14 +00004801 InstructionList.push_back(I);
4802 break;
4803 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004804 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4805 if (Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00004806 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004807 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004808 Value *CatchPad =
4809 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004810 if (!CatchPad)
4811 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004812 BasicBlock *BB = getBasicBlock(Record[Idx++]);
David Majnemer654e1302015-07-31 17:58:14 +00004813 if (!BB)
4814 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004815
David Majnemer8a1c45d2015-12-12 05:38:55 +00004816 I = CatchReturnInst::Create(CatchPad, BB);
David Majnemer654e1302015-07-31 17:58:14 +00004817 InstructionList.push_back(I);
4818 break;
4819 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004820 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4821 // We must have, at minimum, the outer scope and the number of arguments.
4822 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00004823 return error("Invalid record");
4824
David Majnemer654e1302015-07-31 17:58:14 +00004825 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004826
4827 Value *ParentPad =
4828 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4829
4830 unsigned NumHandlers = Record[Idx++];
4831
4832 SmallVector<BasicBlock *, 2> Handlers;
4833 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4834 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4835 if (!BB)
David Majnemer654e1302015-07-31 17:58:14 +00004836 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004837 Handlers.push_back(BB);
4838 }
4839
4840 BasicBlock *UnwindDest = nullptr;
4841 if (Idx + 1 == Record.size()) {
David Majnemer654e1302015-07-31 17:58:14 +00004842 UnwindDest = getBasicBlock(Record[Idx++]);
4843 if (!UnwindDest)
4844 return error("Invalid record");
4845 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004846
4847 if (Record.size() != Idx)
4848 return error("Invalid record");
4849
4850 auto *CatchSwitch =
4851 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4852 for (BasicBlock *Handler : Handlers)
4853 CatchSwitch->addHandler(Handler);
4854 I = CatchSwitch;
4855 InstructionList.push_back(I);
4856 break;
4857 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004858 case bitc::FUNC_CODE_INST_CATCHPAD:
4859 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4860 // We must have, at minimum, the outer scope and the number of arguments.
4861 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00004862 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004863
David Majnemer654e1302015-07-31 17:58:14 +00004864 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004865
4866 Value *ParentPad =
4867 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4868
David Majnemer654e1302015-07-31 17:58:14 +00004869 unsigned NumArgOperands = Record[Idx++];
David Majnemer8a1c45d2015-12-12 05:38:55 +00004870
David Majnemer654e1302015-07-31 17:58:14 +00004871 SmallVector<Value *, 2> Args;
4872 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4873 Value *Val;
4874 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4875 return error("Invalid record");
4876 Args.push_back(Val);
4877 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004878
David Majnemer654e1302015-07-31 17:58:14 +00004879 if (Record.size() != Idx)
4880 return error("Invalid record");
4881
David Majnemer8a1c45d2015-12-12 05:38:55 +00004882 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4883 I = CleanupPadInst::Create(ParentPad, Args);
4884 else
4885 I = CatchPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00004886 InstructionList.push_back(I);
4887 break;
4888 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00004889 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004890 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004891 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00004892 // "New" SwitchInst format with case ranges. The changes to write this
4893 // format were reverted but we still recognize bitcode that uses it.
4894 // Hopefully someday we will have support for case ranges and can use
4895 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004896
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004897 Type *OpTy = getTypeByID(Record[1]);
4898 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4899
Jan Wen Voungafaced02012-10-11 20:20:40 +00004900 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004901 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004902 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004903 return error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004904
4905 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004906
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004907 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4908 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004909
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004910 unsigned CurIdx = 5;
4911 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00004912 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004913 unsigned NumItems = Record[CurIdx++];
4914 for (unsigned ci = 0; ci != NumItems; ++ci) {
4915 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004916
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004917 APInt Low;
4918 unsigned ActiveWords = 1;
4919 if (ValueBitWidth > 64)
4920 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004921 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
Benjamin Kramer9704ed02012-05-28 14:10:31 +00004922 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004923 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00004924
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004925 if (!isSingleNumber) {
4926 ActiveWords = 1;
4927 if (ValueBitWidth > 64)
4928 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004929 APInt High = readWideAPInt(
4930 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004931 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00004932
4933 // FIXME: It is not clear whether values in the range should be
4934 // compared as signed or unsigned values. The partially
4935 // implemented changes that used this format in the past used
4936 // unsigned comparisons.
4937 for ( ; Low.ule(High); ++Low)
4938 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004939 } else
Bob Wilsone4077362013-09-09 19:14:35 +00004940 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004941 }
4942 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00004943 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4944 cve = CaseVals.end(); cvi != cve; ++cvi)
4945 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004946 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004947 I = SI;
4948 break;
4949 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004950
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004951 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004952
Chris Lattner5285b5e2007-05-02 05:46:45 +00004953 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004954 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004955 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004956 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004957 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004958 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004959 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004960 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00004961 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00004962 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004963 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004964 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00004965 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4966 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004967 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00004968 delete SI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004969 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004970 }
4971 SI->addCase(CaseVal, DestBB);
4972 }
4973 I = SI;
4974 break;
4975 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004976 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00004977 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004978 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004979 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004980 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00004981 if (!OpTy || !Address)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004982 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004983 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004984 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00004985 InstructionList.push_back(IBI);
4986 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4987 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4988 IBI->addDestination(DestBB);
4989 } else {
4990 delete IBI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004991 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004992 }
4993 }
4994 I = IBI;
4995 break;
4996 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004997
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004998 case bitc::FUNC_CODE_INST_INVOKE: {
4999 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00005000 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005001 return error("Invalid record");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005002 unsigned OpNum = 0;
5003 AttributeSet PAL = getAttributes(Record[OpNum++]);
5004 unsigned CCInfo = Record[OpNum++];
5005 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5006 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005007
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005008 FunctionType *FTy = nullptr;
5009 if (CCInfo >> 13 & 1 &&
5010 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005011 return error("Explicit invoke type is not a function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005012
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005013 Value *Callee;
5014 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005015 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005016
Chris Lattner229907c2011-07-18 04:54:35 +00005017 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005018 if (!CalleeTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005019 return error("Callee is not a pointer");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005020 if (!FTy) {
5021 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
5022 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005023 return error("Callee is not of pointer to function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005024 } else if (CalleeTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005025 return error("Explicit invoke type does not match pointee type of "
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005026 "callee operand");
5027 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005028 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005029
Chris Lattner5285b5e2007-05-02 05:46:45 +00005030 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005031 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00005032 Ops.push_back(getValue(Record, OpNum, NextValueNo,
5033 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00005034 if (!Ops.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005035 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00005036 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005037
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005038 if (!FTy->isVarArg()) {
5039 if (Record.size() != OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005040 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00005041 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005042 // Read type/value pairs for varargs params.
5043 while (OpNum != Record.size()) {
5044 Value *Op;
5045 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005046 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005047 Ops.push_back(Op);
5048 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00005049 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005050
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005051 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
5052 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00005053 InstructionList.push_back(I);
Vedant Kumarad6d6e72015-10-27 21:17:06 +00005054 cast<InvokeInst>(I)->setCallingConv(
5055 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00005056 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00005057 break;
5058 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00005059 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
5060 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005061 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005062 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005063 return error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00005064 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00005065 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005066 break;
5067 }
Chris Lattnere53603e2007-05-02 04:27:25 +00005068 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00005069 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00005070 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00005071 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00005072 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00005073 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005074 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00005075 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005076 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005077 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005078
Jay Foad52131342011-03-30 11:28:46 +00005079 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00005080 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005081
Chris Lattnere14cb882007-05-04 19:11:41 +00005082 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00005083 Value *V;
5084 // With the new function encoding, it is possible that operands have
5085 // negative IDs (for forward references). Use a signed VBR
5086 // representation to keep the encoding small.
5087 if (UseRelativeIDs)
5088 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
5089 else
5090 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00005091 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005092 if (!V || !BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005093 return error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00005094 PN->addIncoming(V, BB);
5095 }
5096 I = PN;
5097 break;
5098 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005099
David Majnemer7fddecc2015-06-17 20:52:32 +00005100 case bitc::FUNC_CODE_INST_LANDINGPAD:
5101 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
Bill Wendlingfae14752011-08-12 20:24:12 +00005102 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
5103 unsigned Idx = 0;
David Majnemer7fddecc2015-06-17 20:52:32 +00005104 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
5105 if (Record.size() < 3)
5106 return error("Invalid record");
5107 } else {
5108 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
5109 if (Record.size() < 4)
5110 return error("Invalid record");
5111 }
Bill Wendlingfae14752011-08-12 20:24:12 +00005112 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005113 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005114 return error("Invalid record");
David Majnemer7fddecc2015-06-17 20:52:32 +00005115 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
5116 Value *PersFn = nullptr;
5117 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
5118 return error("Invalid record");
5119
5120 if (!F->hasPersonalityFn())
5121 F->setPersonalityFn(cast<Constant>(PersFn));
5122 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
5123 return error("Personality function mismatch");
5124 }
Bill Wendlingfae14752011-08-12 20:24:12 +00005125
5126 bool IsCleanup = !!Record[Idx++];
5127 unsigned NumClauses = Record[Idx++];
David Majnemer7fddecc2015-06-17 20:52:32 +00005128 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
Bill Wendlingfae14752011-08-12 20:24:12 +00005129 LP->setCleanup(IsCleanup);
5130 for (unsigned J = 0; J != NumClauses; ++J) {
5131 LandingPadInst::ClauseType CT =
5132 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
5133 Value *Val;
5134
5135 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
5136 delete LP;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005137 return error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00005138 }
5139
5140 assert((CT != LandingPadInst::Catch ||
5141 !isa<ArrayType>(Val->getType())) &&
5142 "Catch clause has a invalid type!");
5143 assert((CT != LandingPadInst::Filter ||
5144 isa<ArrayType>(Val->getType())) &&
5145 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005146 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00005147 }
5148
5149 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00005150 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00005151 break;
5152 }
5153
Chris Lattnerf1c87102011-06-17 18:09:11 +00005154 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
5155 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005156 return error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00005157 uint64_t AlignRecord = Record[3];
5158 const uint64_t InAllocaMask = uint64_t(1) << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00005159 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00005160 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
5161 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
5162 SwiftErrorMask;
JF Bastien30bf96b2015-02-22 19:32:03 +00005163 bool InAlloca = AlignRecord & InAllocaMask;
Manman Ren9bfd0d02016-04-01 21:41:15 +00005164 bool SwiftError = AlignRecord & SwiftErrorMask;
David Blaikiebdb49102015-04-28 16:51:01 +00005165 Type *Ty = getTypeByID(Record[0]);
5166 if ((AlignRecord & ExplicitTypeMask) == 0) {
5167 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
5168 if (!PTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005169 return error("Old-style alloca with a non-pointer type");
David Blaikiebdb49102015-04-28 16:51:01 +00005170 Ty = PTy->getElementType();
5171 }
5172 Type *OpTy = getTypeByID(Record[1]);
5173 Value *Size = getFnValueByID(Record[2], OpTy);
JF Bastien30bf96b2015-02-22 19:32:03 +00005174 unsigned Align;
5175 if (std::error_code EC =
David Blaikiebdb49102015-04-28 16:51:01 +00005176 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
JF Bastien30bf96b2015-02-22 19:32:03 +00005177 return EC;
5178 }
Rafael Espindola48da4f42013-11-04 16:16:24 +00005179 if (!Ty || !Size)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005180 return error("Invalid record");
David Blaikiebdb49102015-04-28 16:51:01 +00005181 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00005182 AI->setUsedWithInAlloca(InAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005183 AI->setSwiftError(SwiftError);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00005184 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00005185 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00005186 break;
5187 }
Chris Lattner9f600c52007-05-03 22:04:19 +00005188 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005189 unsigned OpNum = 0;
5190 Value *Op;
5191 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00005192 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005193 return error("Invalid record");
David Blaikie85035652015-02-25 01:07:20 +00005194
5195 Type *Ty = nullptr;
5196 if (OpNum + 3 == Record.size())
5197 Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005198 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005199 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00005200 if (!Ty)
5201 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00005202
JF Bastien30bf96b2015-02-22 19:32:03 +00005203 unsigned Align;
5204 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5205 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00005206 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
David Blaikie85035652015-02-25 01:07:20 +00005207
Devang Patelaf206b82009-09-18 19:26:43 +00005208 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00005209 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00005210 }
Eli Friedman59b66882011-08-09 23:02:53 +00005211 case bitc::FUNC_CODE_INST_LOADATOMIC: {
5212 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
5213 unsigned OpNum = 0;
5214 Value *Op;
5215 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00005216 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005217 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00005218
David Blaikie85035652015-02-25 01:07:20 +00005219 Type *Ty = nullptr;
5220 if (OpNum + 5 == Record.size())
5221 Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005222 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005223 return EC;
5224 if (!Ty)
5225 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00005226
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005227 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00005228 if (Ordering == AtomicOrdering::NotAtomic ||
5229 Ordering == AtomicOrdering::Release ||
5230 Ordering == AtomicOrdering::AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005231 return error("Invalid record");
JF Bastien800f87a2016-04-06 21:19:33 +00005232 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005233 return error("Invalid record");
5234 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00005235
JF Bastien30bf96b2015-02-22 19:32:03 +00005236 unsigned Align;
5237 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5238 return EC;
5239 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
David Blaikie85035652015-02-25 01:07:20 +00005240
Eli Friedman59b66882011-08-09 23:02:53 +00005241 InstructionList.push_back(I);
5242 break;
5243 }
David Blaikie612ddbf2015-04-22 04:14:42 +00005244 case bitc::FUNC_CODE_INST_STORE:
5245 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00005246 unsigned OpNum = 0;
5247 Value *Val, *Ptr;
5248 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie612ddbf2015-04-22 04:14:42 +00005249 (BitCode == bitc::FUNC_CODE_INST_STORE
5250 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5251 : popValue(Record, OpNum, NextValueNo,
5252 cast<PointerType>(Ptr->getType())->getElementType(),
5253 Val)) ||
5254 OpNum + 2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005255 return error("Invalid record");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005256
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005257 if (std::error_code EC =
5258 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005259 return EC;
JF Bastien30bf96b2015-02-22 19:32:03 +00005260 unsigned Align;
5261 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5262 return EC;
5263 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
Devang Patelaf206b82009-09-18 19:26:43 +00005264 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00005265 break;
5266 }
David Blaikie50a06152015-04-22 04:14:46 +00005267 case bitc::FUNC_CODE_INST_STOREATOMIC:
5268 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
Eli Friedman59b66882011-08-09 23:02:53 +00005269 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
5270 unsigned OpNum = 0;
5271 Value *Val, *Ptr;
5272 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Filipe Cabecinhas036e73c2016-06-05 18:43:33 +00005273 !isa<PointerType>(Ptr->getType()) ||
David Blaikie50a06152015-04-22 04:14:46 +00005274 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
5275 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5276 : popValue(Record, OpNum, NextValueNo,
5277 cast<PointerType>(Ptr->getType())->getElementType(),
5278 Val)) ||
5279 OpNum + 4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005280 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00005281
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005282 if (std::error_code EC =
5283 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005284 return EC;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005285 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00005286 if (Ordering == AtomicOrdering::NotAtomic ||
5287 Ordering == AtomicOrdering::Acquire ||
5288 Ordering == AtomicOrdering::AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005289 return error("Invalid record");
5290 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
JF Bastien800f87a2016-04-06 21:19:33 +00005291 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005292 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00005293
JF Bastien30bf96b2015-02-22 19:32:03 +00005294 unsigned Align;
5295 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5296 return EC;
5297 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
Eli Friedman59b66882011-08-09 23:02:53 +00005298 InstructionList.push_back(I);
5299 break;
5300 }
David Blaikie2a661cd2015-04-28 04:30:29 +00005301 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005302 case bitc::FUNC_CODE_INST_CMPXCHG: {
Tim Northovere94a5182014-03-11 10:48:52 +00005303 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
Tim Northover420a2162014-06-13 14:24:07 +00005304 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005305 unsigned OpNum = 0;
5306 Value *Ptr, *Cmp, *New;
5307 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie2a661cd2015-04-28 04:30:29 +00005308 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
5309 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
5310 : popValue(Record, OpNum, NextValueNo,
5311 cast<PointerType>(Ptr->getType())->getElementType(),
5312 Cmp)) ||
5313 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
5314 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005315 return error("Invalid record");
5316 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
JF Bastien800f87a2016-04-06 21:19:33 +00005317 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
5318 SuccessOrdering == AtomicOrdering::Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005319 return error("Invalid record");
5320 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
Tim Northovere94a5182014-03-11 10:48:52 +00005321
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005322 if (std::error_code EC =
5323 typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005324 return EC;
Tim Northovere94a5182014-03-11 10:48:52 +00005325 AtomicOrdering FailureOrdering;
5326 if (Record.size() < 7)
5327 FailureOrdering =
5328 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
5329 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005330 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
Tim Northovere94a5182014-03-11 10:48:52 +00005331
5332 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
5333 SynchScope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005334 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00005335
5336 if (Record.size() < 8) {
5337 // Before weak cmpxchgs existed, the instruction simply returned the
5338 // value loaded from memory, so bitcode files from that era will be
5339 // expecting the first component of a modern cmpxchg.
5340 CurBB->getInstList().push_back(I);
5341 I = ExtractValueInst::Create(I, 0);
5342 } else {
5343 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
5344 }
5345
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005346 InstructionList.push_back(I);
5347 break;
5348 }
5349 case bitc::FUNC_CODE_INST_ATOMICRMW: {
5350 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
5351 unsigned OpNum = 0;
5352 Value *Ptr, *Val;
5353 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Filipe Cabecinhas6328f8e2016-06-05 18:43:40 +00005354 !isa<PointerType>(Ptr->getType()) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00005355 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005356 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
5357 OpNum+4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005358 return error("Invalid record");
5359 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005360 if (Operation < AtomicRMWInst::FIRST_BINOP ||
5361 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005362 return error("Invalid record");
5363 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00005364 if (Ordering == AtomicOrdering::NotAtomic ||
5365 Ordering == AtomicOrdering::Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005366 return error("Invalid record");
5367 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005368 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
5369 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
5370 InstructionList.push_back(I);
5371 break;
5372 }
Eli Friedmanfee02c62011-07-25 23:16:38 +00005373 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
5374 if (2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005375 return error("Invalid record");
5376 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
JF Bastien800f87a2016-04-06 21:19:33 +00005377 if (Ordering == AtomicOrdering::NotAtomic ||
5378 Ordering == AtomicOrdering::Unordered ||
5379 Ordering == AtomicOrdering::Monotonic)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005380 return error("Invalid record");
5381 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005382 I = new FenceInst(Context, Ordering, SynchScope);
5383 InstructionList.push_back(I);
5384 break;
5385 }
Chris Lattnerc44070802011-06-17 18:17:37 +00005386 case bitc::FUNC_CODE_INST_CALL: {
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005387 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00005388 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005389 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005390
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005391 unsigned OpNum = 0;
5392 AttributeSet PAL = getAttributes(Record[OpNum++]);
5393 unsigned CCInfo = Record[OpNum++];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005394
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005395 FastMathFlags FMF;
5396 if ((CCInfo >> bitc::CALL_FMF) & 1) {
5397 FMF = getDecodedFastMathFlags(Record[OpNum++]);
5398 if (!FMF.any())
5399 return error("Fast math flags indicator set for call with no FMF");
5400 }
5401
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005402 FunctionType *FTy = nullptr;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005403 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005404 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005405 return error("Explicit call type is not a function type");
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005406
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005407 Value *Callee;
5408 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005409 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005410
Chris Lattner229907c2011-07-18 04:54:35 +00005411 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005412 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005413 return error("Callee is not a pointer type");
David Blaikie348de692015-04-23 21:36:23 +00005414 if (!FTy) {
5415 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5416 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005417 return error("Callee is not of pointer to function type");
David Blaikie348de692015-04-23 21:36:23 +00005418 } else if (OpTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005419 return error("Explicit call type does not match pointee type of "
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005420 "callee operand");
5421 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005422 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005423
Chris Lattner9f600c52007-05-03 22:04:19 +00005424 SmallVector<Value*, 16> Args;
5425 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005426 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005427 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00005428 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00005429 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00005430 Args.push_back(getValue(Record, OpNum, NextValueNo,
5431 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00005432 if (!Args.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005433 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005434 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005435
Chris Lattner9f600c52007-05-03 22:04:19 +00005436 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00005437 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005438 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005439 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005440 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005441 while (OpNum != Record.size()) {
5442 Value *Op;
5443 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005444 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005445 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00005446 }
5447 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005448
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005449 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5450 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00005451 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00005452 cast<CallInst>(I)->setCallingConv(
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005453 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
Reid Kleckner5772b772014-04-24 20:14:34 +00005454 CallInst::TailCallKind TCK = CallInst::TCK_None;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005455 if (CCInfo & 1 << bitc::CALL_TAIL)
Reid Kleckner5772b772014-04-24 20:14:34 +00005456 TCK = CallInst::TCK_Tail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005457 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
Reid Kleckner5772b772014-04-24 20:14:34 +00005458 TCK = CallInst::TCK_MustTail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005459 if (CCInfo & (1 << bitc::CALL_NOTAIL))
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005460 TCK = CallInst::TCK_NoTail;
Reid Kleckner5772b772014-04-24 20:14:34 +00005461 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00005462 cast<CallInst>(I)->setAttributes(PAL);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005463 if (FMF.any()) {
5464 if (!isa<FPMathOperator>(I))
5465 return error("Fast-math-flags specified for call without "
5466 "floating-point scalar or vector return type");
5467 I->setFastMathFlags(FMF);
5468 }
Chris Lattner9f600c52007-05-03 22:04:19 +00005469 break;
5470 }
5471 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5472 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005473 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00005474 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00005475 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00005476 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00005477 if (!OpTy || !Op || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005478 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005479 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00005480 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00005481 break;
5482 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005483
5484 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5485 // A call or an invoke can be optionally prefixed with some variable
5486 // number of operand bundle blocks. These blocks are read into
5487 // OperandBundles and consumed at the next call or invoke instruction.
5488
5489 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5490 return error("Invalid record");
5491
Sanjoy Dasf79d3442015-11-18 08:30:07 +00005492 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005493
5494 unsigned OpNum = 1;
5495 while (OpNum != Record.size()) {
5496 Value *Op;
5497 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5498 return error("Invalid record");
5499 Inputs.push_back(Op);
5500 }
5501
Sanjoy Dasf79d3442015-11-18 08:30:07 +00005502 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005503 continue;
5504 }
Chris Lattner83930552007-05-01 07:01:57 +00005505 }
5506
5507 // Add instruction to end of current BB. If there is no current BB, reject
5508 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00005509 if (!CurBB) {
Chris Lattner83930552007-05-01 07:01:57 +00005510 delete I;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005511 return error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00005512 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005513 if (!OperandBundles.empty()) {
5514 delete I;
5515 return error("Operand bundles found with no consumer");
5516 }
Chris Lattner83930552007-05-01 07:01:57 +00005517 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005518
Chris Lattner83930552007-05-01 07:01:57 +00005519 // If this was a terminator instruction, move to the next block.
5520 if (isa<TerminatorInst>(I)) {
5521 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00005522 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00005523 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005524
Chris Lattner83930552007-05-01 07:01:57 +00005525 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00005526 if (I && !I->getType()->isVoidTy())
David Majnemer8a1c45d2015-12-12 05:38:55 +00005527 ValueList.assignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00005528 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005529
Chris Lattner27d38752013-01-20 02:13:19 +00005530OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00005531
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005532 if (!OperandBundles.empty())
5533 return error("Operand bundles found with no consumer");
5534
Chris Lattner83930552007-05-01 07:01:57 +00005535 // Check the function list for unresolved values.
5536 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005537 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00005538 // We found at least one unresolved value. Nuke them all to avoid leaks.
5539 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00005540 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00005541 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00005542 delete A;
5543 }
5544 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005545 return error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00005546 }
Chris Lattner83930552007-05-01 07:01:57 +00005547 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005548
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00005549 // Unexpected unresolved metadata about to be dropped.
5550 if (MetadataList.hasFwdRefs())
5551 return error("Invalid function metadata: outgoing forward refs");
Dan Gohman9b9ff462010-08-25 20:23:38 +00005552
Chris Lattner85b7b402007-05-01 05:52:21 +00005553 // Trim the value list down to the size it was before we parsed this function.
5554 ValueList.shrinkTo(ModuleValueListSize);
Teresa Johnson61b406e2015-12-29 23:00:22 +00005555 MetadataList.shrinkTo(ModuleMetadataListSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00005556 std::vector<BasicBlock*>().swap(FunctionBBs);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005557 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00005558}
5559
Rafael Espindola7d712032013-11-05 17:16:08 +00005560/// Find the function body in the bitcode stream
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005561std::error_code BitcodeReader::findFunctionInStream(
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005562 Function *F,
5563 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005564 while (DeferredFunctionInfoIterator->second == 0) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00005565 // This is the fallback handling for the old format bitcode that
Teresa Johnson1493ad92015-10-10 14:18:36 +00005566 // didn't contain the function index in the VST, or when we have
5567 // an anonymous function which would not have a VST entry.
5568 // Assert that we have one of those two cases.
5569 assert(VSTOffset == 0 || !F->hasName());
5570 // Parse the next body in the stream and set its position in the
5571 // DeferredFunctionInfo map.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005572 if (std::error_code EC = rememberAndSkipFunctionBodies())
5573 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005574 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005575 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005576}
5577
Chris Lattner9eeada92007-05-18 04:02:46 +00005578//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005579// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00005580//===----------------------------------------------------------------------===//
5581
Rafael Espindolac3f9b5a2014-06-23 21:53:12 +00005582void BitcodeReader::releaseBuffer() { Buffer.release(); }
Chris Lattner9eeada92007-05-18 04:02:46 +00005583
Rafael Espindola5a52e6d2014-10-24 22:50:48 +00005584std::error_code BitcodeReader::materialize(GlobalValue *GV) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005585 Function *F = dyn_cast<Function>(GV);
5586 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005587 if (!F || !F->isMaterializable())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005588 return std::error_code();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005589
5590 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00005591 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005592 // If its position is recorded as 0, its body is somewhere in the stream
5593 // but we haven't seen it yet.
Rafael Espindola1c863ca2015-06-22 18:06:15 +00005594 if (DFII->second == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005595 if (std::error_code EC = findFunctionInStream(F, DFII))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005596 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005597
Duncan P. N. Exon Smith03a04a52016-04-24 15:04:28 +00005598 // Materialize metadata before parsing any function bodies.
5599 if (std::error_code EC = materializeMetadata())
5600 return EC;
5601
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005602 // Move the bit stream to the saved position of the deferred function body.
5603 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005604
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005605 if (std::error_code EC = parseFunctionBody(F))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005606 return EC;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00005607 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00005608
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00005609 if (StripDebugInfo)
5610 stripDebugInfo(*F);
5611
Chandler Carruth7132e002007-08-04 01:51:18 +00005612 // Upgrade any old intrinsic calls in the function.
Rafael Espindola86e33402015-07-02 15:55:09 +00005613 for (auto &I : UpgradedIntrinsics) {
Rafael Espindola257a3532016-01-15 19:00:20 +00005614 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5615 UI != UE;) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005616 User *U = *UI;
5617 ++UI;
5618 if (CallInst *CI = dyn_cast<CallInst>(U))
5619 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00005620 }
5621 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005622
Peter Collingbourned4bff302015-11-05 22:03:56 +00005623 // Finish fn->subprogram upgrade for materialized functions.
5624 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5625 F->setSubprogram(SP);
5626
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005627 // Bring in any functions that this function forward-referenced via
5628 // blockaddresses.
5629 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00005630}
5631
Rafael Espindola79753a02015-12-18 21:18:57 +00005632std::error_code BitcodeReader::materializeModule() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00005633 if (std::error_code EC = materializeMetadata())
5634 return EC;
5635
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005636 // Promise to materialize all forward references.
5637 WillMaterializeAllForwardRefs = true;
5638
Chris Lattner06310bf2009-06-16 05:15:21 +00005639 // Iterate over the module, deserializing any functions that are still on
5640 // disk.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00005641 for (Function &F : *TheModule) {
5642 if (std::error_code EC = materialize(&F))
Rafael Espindola246c4fb2014-11-01 16:46:18 +00005643 return EC;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005644 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00005645 // At this point, if there are any function bodies, parse the rest of
5646 // the bits in the module past the last function block we have recorded
5647 // through either lazy scanning or the VST.
5648 if (LastFunctionBlockBit || NextUnreadBit)
5649 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5650 : NextUnreadBit);
Derek Schuff92ef9752012-02-29 00:07:09 +00005651
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005652 // Check that all block address forward references got resolved (as we
5653 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00005654 if (!BasicBlockFwdRefs.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005655 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005656
Chris Bieneman671d0dd2016-03-16 23:17:54 +00005657 // Upgrading intrinsic calls before TBAA can cause TBAA metadata to be lost,
5658 // to prevent this instructions with TBAA tags should be upgraded first.
5659 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5660 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5661
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005662 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5663 // delete the old functions to clean up. We can't do this unless the entire
5664 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00005665 // with calls to the old function.
Rafael Espindola86e33402015-07-02 15:55:09 +00005666 for (auto &I : UpgradedIntrinsics) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005667 for (auto *U : I.first->users()) {
5668 if (CallInst *CI = dyn_cast<CallInst>(U))
5669 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00005670 }
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005671 if (!I.first->use_empty())
5672 I.first->replaceAllUsesWith(I.second);
5673 I.first->eraseFromParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00005674 }
Rafael Espindola4e721212015-07-02 16:22:40 +00005675 UpgradedIntrinsics.clear();
Devang Patel80ae3492009-08-28 23:24:31 +00005676
Rafael Espindola79753a02015-12-18 21:18:57 +00005677 UpgradeDebugInfo(*TheModule);
Manman Renb5d7ff42016-05-25 23:14:48 +00005678
5679 UpgradeModuleFlags(*TheModule);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005680 return std::error_code();
Chris Lattner9eeada92007-05-18 04:02:46 +00005681}
5682
Rafael Espindola2fa1e432014-12-03 07:18:23 +00005683std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5684 return IdentifiedStructTypes;
5685}
5686
Rafael Espindola1aabf982015-06-16 23:29:49 +00005687std::error_code
5688BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
Rafael Espindola4223a1f2015-06-15 20:08:17 +00005689 if (Streamer)
Rafael Espindola1aabf982015-06-16 23:29:49 +00005690 return initLazyStream(std::move(Streamer));
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005691 return initStreamFromBuffer();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005692}
5693
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005694std::error_code BitcodeReader::initStreamFromBuffer() {
Roman Divacky4717a8d2012-09-06 15:42:13 +00005695 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005696 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5697
Rafael Espindola27435252014-07-29 21:01:24 +00005698 if (Buffer->getBufferSize() & 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005699 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005700
5701 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5702 // The magic number is 0x0B17C0DE stored in little endian.
5703 if (isBitcodeWrapper(BufPtr, BufEnd))
5704 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005705 return error("Invalid bitcode wrapper header");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005706
5707 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00005708 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005709
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005710 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005711}
5712
Rafael Espindola1aabf982015-06-16 23:29:49 +00005713std::error_code
5714BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005715 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5716 // see it.
Rafael Espindola1aabf982015-06-16 23:29:49 +00005717 auto OwnedBytes =
5718 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
Rafael Espindola7d727b52014-12-18 05:08:43 +00005719 StreamingMemoryObject &Bytes = *OwnedBytes;
Yaron Keren06d69302014-12-18 10:03:35 +00005720 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00005721 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005722
5723 unsigned char buf[16];
Rafael Espindola7d727b52014-12-18 05:08:43 +00005724 if (Bytes.readBytes(buf, 16, 0) != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005725 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005726
5727 if (!isBitcode(buf, buf + 16))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005728 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005729
5730 if (isBitcodeWrapper(buf, buf + 4)) {
5731 const unsigned char *bitcodeStart = buf;
5732 const unsigned char *bitcodeEnd = buf + 16;
5733 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
Rafael Espindola7d727b52014-12-18 05:08:43 +00005734 Bytes.dropLeadingBytes(bitcodeStart - buf);
5735 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005736 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005737 return std::error_code();
Rafael Espindola48da4f42013-11-04 16:16:24 +00005738}
5739
Teresa Johnson26ab5772016-03-15 00:04:37 +00005740std::error_code ModuleSummaryIndexBitcodeReader::error(BitcodeError E,
5741 const Twine &Message) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005742 return ::error(DiagnosticHandler, make_error_code(E), Message);
5743}
5744
Teresa Johnson26ab5772016-03-15 00:04:37 +00005745std::error_code ModuleSummaryIndexBitcodeReader::error(const Twine &Message) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005746 return ::error(DiagnosticHandler,
5747 make_error_code(BitcodeError::CorruptedBitcode), Message);
5748}
5749
Teresa Johnson26ab5772016-03-15 00:04:37 +00005750std::error_code ModuleSummaryIndexBitcodeReader::error(BitcodeError E) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005751 return ::error(DiagnosticHandler, make_error_code(E));
5752}
5753
Teresa Johnson26ab5772016-03-15 00:04:37 +00005754ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
Mehdi Amini354f5202015-11-19 05:52:29 +00005755 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson6fb3f192016-04-22 01:52:00 +00005756 bool CheckGlobalValSummaryPresenceOnly)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00005757 : DiagnosticHandler(std::move(DiagnosticHandler)), Buffer(Buffer),
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005758 CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
Teresa Johnson403a7872015-10-04 14:33:43 +00005759
Teresa Johnson26ab5772016-03-15 00:04:37 +00005760ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
Teresa Johnson6fb3f192016-04-22 01:52:00 +00005761 DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005762 bool CheckGlobalValSummaryPresenceOnly)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00005763 : DiagnosticHandler(std::move(DiagnosticHandler)), Buffer(nullptr),
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005764 CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
Teresa Johnson403a7872015-10-04 14:33:43 +00005765
Teresa Johnson26ab5772016-03-15 00:04:37 +00005766void ModuleSummaryIndexBitcodeReader::freeState() { Buffer = nullptr; }
Teresa Johnson403a7872015-10-04 14:33:43 +00005767
Teresa Johnson26ab5772016-03-15 00:04:37 +00005768void ModuleSummaryIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
Teresa Johnson403a7872015-10-04 14:33:43 +00005769
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005770std::pair<GlobalValue::GUID, GlobalValue::GUID>
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005771ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005772 auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId);
5773 assert(VGI != ValueIdToCallGraphGUIDMap.end());
5774 return VGI->second;
5775}
5776
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005777// Specialized value symbol table parser used when reading module index
Teresa Johnson28e457b2016-04-24 14:57:11 +00005778// blocks where we don't actually create global values. The parsed information
5779// is saved in the bitcode reader for use when later parsing summaries.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005780std::error_code ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005781 uint64_t Offset,
5782 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
5783 assert(Offset > 0 && "Expected non-zero VST offset");
5784 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
5785
Teresa Johnson403a7872015-10-04 14:33:43 +00005786 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5787 return error("Invalid record");
5788
5789 SmallVector<uint64_t, 64> Record;
5790
5791 // Read all the records for this value table.
5792 SmallString<128> ValueName;
5793 while (1) {
5794 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5795
5796 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005797 case BitstreamEntry::SubBlock: // Handled for us already.
5798 case BitstreamEntry::Error:
5799 return error("Malformed block");
5800 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005801 // Done parsing VST, jump back to wherever we came from.
5802 Stream.JumpToBit(CurrentBit);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005803 return std::error_code();
5804 case BitstreamEntry::Record:
5805 // The interesting case.
5806 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005807 }
5808
5809 // Read a record.
5810 Record.clear();
5811 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005812 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5813 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005814 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
5815 if (convertToString(Record, 1, ValueName))
5816 return error("Invalid record");
5817 unsigned ValueID = Record[0];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005818 assert(!SourceFileName.empty());
5819 auto VLI = ValueIdToLinkageMap.find(ValueID);
5820 assert(VLI != ValueIdToLinkageMap.end() &&
5821 "No linkage found for VST entry?");
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005822 auto Linkage = VLI->second;
5823 std::string GlobalId =
5824 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
Teresa Johnson916495d2016-04-04 18:52:58 +00005825 auto ValueGUID = GlobalValue::getGUID(GlobalId);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005826 auto OriginalNameID = ValueGUID;
5827 if (GlobalValue::isLocalLinkage(Linkage))
5828 OriginalNameID = GlobalValue::getGUID(ValueName);
Teresa Johnson916495d2016-04-04 18:52:58 +00005829 if (PrintSummaryGUIDs)
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005830 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
5831 << ValueName << "\n";
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005832 ValueIdToCallGraphGUIDMap[ValueID] =
5833 std::make_pair(ValueGUID, OriginalNameID);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005834 ValueName.clear();
5835 break;
5836 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005837 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00005838 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005839 if (convertToString(Record, 2, ValueName))
5840 return error("Invalid record");
5841 unsigned ValueID = Record[0];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005842 assert(!SourceFileName.empty());
5843 auto VLI = ValueIdToLinkageMap.find(ValueID);
5844 assert(VLI != ValueIdToLinkageMap.end() &&
5845 "No linkage found for VST entry?");
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005846 auto Linkage = VLI->second;
Teresa Johnsonb43027d2016-03-15 02:13:19 +00005847 std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier(
5848 ValueName, VLI->second, SourceFileName);
Teresa Johnson916495d2016-04-04 18:52:58 +00005849 auto FunctionGUID = GlobalValue::getGUID(FunctionGlobalId);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005850 auto OriginalNameID = FunctionGUID;
5851 if (GlobalValue::isLocalLinkage(Linkage))
5852 OriginalNameID = GlobalValue::getGUID(ValueName);
Teresa Johnson916495d2016-04-04 18:52:58 +00005853 if (PrintSummaryGUIDs)
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005854 dbgs() << "GUID " << FunctionGUID << "(" << OriginalNameID << ") is "
5855 << ValueName << "\n";
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005856 ValueIdToCallGraphGUIDMap[ValueID] =
5857 std::make_pair(FunctionGUID, OriginalNameID);
Teresa Johnson403a7872015-10-04 14:33:43 +00005858
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005859 ValueName.clear();
5860 break;
5861 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005862 case bitc::VST_CODE_COMBINED_ENTRY: {
5863 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
5864 unsigned ValueID = Record[0];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005865 GlobalValue::GUID RefGUID = Record[1];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005866 // The "original name", which is the second value of the pair will be
5867 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
5868 ValueIdToCallGraphGUIDMap[ValueID] = std::make_pair(RefGUID, RefGUID);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005869 break;
5870 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005871 }
5872 }
5873}
5874
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005875// Parse just the blocks needed for building the index out of the module.
5876// At the end of this routine the module Index is populated with a map
Teresa Johnson28e457b2016-04-24 14:57:11 +00005877// from global value id to GlobalValueSummary objects.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005878std::error_code ModuleSummaryIndexBitcodeReader::parseModule() {
Teresa Johnson403a7872015-10-04 14:33:43 +00005879 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5880 return error("Invalid record");
5881
Teresa Johnsone1164de2016-02-10 21:55:02 +00005882 SmallVector<uint64_t, 64> Record;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005883 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
5884 unsigned ValueId = 0;
Teresa Johnsone1164de2016-02-10 21:55:02 +00005885
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005886 // Read the index for this module.
Teresa Johnson403a7872015-10-04 14:33:43 +00005887 while (1) {
5888 BitstreamEntry Entry = Stream.advance();
5889
5890 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005891 case BitstreamEntry::Error:
5892 return error("Malformed block");
5893 case BitstreamEntry::EndBlock:
5894 return std::error_code();
5895
5896 case BitstreamEntry::SubBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005897 if (CheckGlobalValSummaryPresenceOnly) {
5898 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
5899 SeenGlobalValSummary = true;
Teresa Johnson6290dbc2015-11-21 21:55:48 +00005900 // No need to parse the rest since we found the summary.
5901 return std::error_code();
5902 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005903 if (Stream.SkipBlock())
5904 return error("Invalid record");
Teresa Johnson6290dbc2015-11-21 21:55:48 +00005905 continue;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005906 }
5907 switch (Entry.ID) {
5908 default: // Skip unknown content.
5909 if (Stream.SkipBlock())
5910 return error("Invalid record");
5911 break;
5912 case bitc::BLOCKINFO_BLOCK_ID:
5913 // Need to parse these to get abbrev ids (e.g. for VST)
5914 if (Stream.ReadBlockInfoBlock())
5915 return error("Malformed block");
5916 break;
5917 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005918 // Should have been parsed earlier via VSTOffset, unless there
5919 // is no summary section.
5920 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
5921 !SeenGlobalValSummary) &&
5922 "Expected early VST parse via VSTOffset record");
5923 if (Stream.SkipBlock())
5924 return error("Invalid record");
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005925 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005926 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
5927 assert(VSTOffset > 0 && "Expected non-zero VST offset");
5928 assert(!SeenValueSymbolTable &&
5929 "Already read VST when parsing summary block?");
5930 if (std::error_code EC =
5931 parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
5932 return EC;
5933 SeenValueSymbolTable = true;
5934 SeenGlobalValSummary = true;
Teresa Johnson6fb3f192016-04-22 01:52:00 +00005935 if (std::error_code EC = parseEntireSummary())
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005936 return EC;
5937 break;
5938 case bitc::MODULE_STRTAB_BLOCK_ID:
5939 if (std::error_code EC = parseModuleStringTable())
5940 return EC;
5941 break;
5942 }
5943 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00005944
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005945 case BitstreamEntry::Record: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00005946 Record.clear();
5947 auto BitCode = Stream.readRecord(Entry.ID, Record);
5948 switch (BitCode) {
5949 default:
5950 break; // Default behavior, ignore unknown content.
5951 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005952 case bitc::MODULE_CODE_SOURCE_FILENAME: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00005953 SmallString<128> ValueName;
5954 if (convertToString(Record, 0, ValueName))
5955 return error("Invalid record");
5956 SourceFileName = ValueName.c_str();
5957 break;
5958 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005959 /// MODULE_CODE_HASH: [5*i32]
5960 case bitc::MODULE_CODE_HASH: {
5961 if (Record.size() != 5)
5962 return error("Invalid hash length " + Twine(Record.size()).str());
5963 if (!TheIndex)
5964 break;
5965 if (TheIndex->modulePaths().empty())
5966 // Does not have any summary emitted.
5967 break;
5968 if (TheIndex->modulePaths().size() != 1)
5969 return error("Don't expect multiple modules defined?");
5970 auto &Hash = TheIndex->modulePaths().begin()->second.second;
5971 int Pos = 0;
5972 for (auto &Val : Record) {
5973 assert(!(Val >> 32) && "Unexpected high bits set");
5974 Hash[Pos++] = Val;
5975 }
5976 break;
5977 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005978 /// MODULE_CODE_VSTOFFSET: [offset]
5979 case bitc::MODULE_CODE_VSTOFFSET:
5980 if (Record.size() < 1)
5981 return error("Invalid record");
5982 VSTOffset = Record[0];
5983 break;
5984 // GLOBALVAR: [pointer type, isconst, initid,
5985 // linkage, alignment, section, visibility, threadlocal,
5986 // unnamed_addr, externally_initialized, dllstorageclass,
5987 // comdat]
5988 case bitc::MODULE_CODE_GLOBALVAR: {
5989 if (Record.size() < 6)
5990 return error("Invalid record");
5991 uint64_t RawLinkage = Record[3];
5992 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5993 ValueIdToLinkageMap[ValueId++] = Linkage;
5994 break;
5995 }
5996 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
5997 // alignment, section, visibility, gc, unnamed_addr,
5998 // prologuedata, dllstorageclass, comdat, prefixdata]
5999 case bitc::MODULE_CODE_FUNCTION: {
6000 if (Record.size() < 8)
6001 return error("Invalid record");
6002 uint64_t RawLinkage = Record[3];
6003 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6004 ValueIdToLinkageMap[ValueId++] = Linkage;
6005 break;
6006 }
6007 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
6008 // dllstorageclass]
6009 case bitc::MODULE_CODE_ALIAS: {
6010 if (Record.size() < 6)
6011 return error("Invalid record");
6012 uint64_t RawLinkage = Record[3];
6013 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6014 ValueIdToLinkageMap[ValueId++] = Linkage;
6015 break;
6016 }
6017 }
Teresa Johnsone1164de2016-02-10 21:55:02 +00006018 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006019 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00006020 }
6021 }
6022}
6023
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006024// Eagerly parse the entire summary block. This populates the GlobalValueSummary
6025// objects in the index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006026std::error_code ModuleSummaryIndexBitcodeReader::parseEntireSummary() {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006027 if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID))
Teresa Johnson403a7872015-10-04 14:33:43 +00006028 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00006029 SmallVector<uint64_t, 64> Record;
Mehdi Amini8fe69362016-04-24 03:18:11 +00006030
6031 // Parse version
6032 {
6033 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6034 if (Entry.Kind != BitstreamEntry::Record)
6035 return error("Invalid Summary Block: record for version expected");
6036 if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
6037 return error("Invalid Summary Block: version expected");
6038 }
6039 const uint64_t Version = Record[0];
6040 if (Version != 1)
6041 return error("Invalid summary version " + Twine(Version) + ", 1 expected");
6042 Record.clear();
6043
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006044 // Keep around the last seen summary to be used when we see an optional
6045 // "OriginalName" attachement.
6046 GlobalValueSummary *LastSeenSummary = nullptr;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006047 bool Combined = false;
Teresa Johnson403a7872015-10-04 14:33:43 +00006048 while (1) {
6049 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6050
6051 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006052 case BitstreamEntry::SubBlock: // Handled for us already.
6053 case BitstreamEntry::Error:
6054 return error("Malformed block");
6055 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006056 // For a per-module index, remove any entries that still have empty
6057 // summaries. The VST parsing creates entries eagerly for all symbols,
6058 // but not all have associated summaries (e.g. it doesn't know how to
6059 // distinguish between VST_CODE_ENTRY for function declarations vs global
6060 // variables with initializers that end up with a summary). Remove those
6061 // entries now so that we don't need to rely on the combined index merger
6062 // to clean them up (especially since that may not run for the first
6063 // module's index if we merge into that).
6064 if (!Combined)
6065 TheIndex->removeEmptySummaryEntries();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006066 return std::error_code();
6067 case BitstreamEntry::Record:
6068 // The interesting case.
6069 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00006070 }
6071
6072 // Read a record. The record format depends on whether this
6073 // is a per-module index or a combined index file. In the per-module
6074 // case the records contain the associated value's ID for correlation
6075 // with VST entries. In the combined index the correlation is done
6076 // via the bitcode offset of the summary records (which were saved
6077 // in the combined index VST entries). The records also contain
6078 // information used for ThinLTO renaming and importing.
6079 Record.clear();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006080 auto BitCode = Stream.readRecord(Entry.ID, Record);
6081 switch (BitCode) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006082 default: // Default behavior: ignore.
6083 break;
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006084 // FS_PERMODULE: [valueid, flags, instcount, numrefs, numrefs x valueid,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006085 // n x (valueid, callsitecount)]
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006086 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, numrefs,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006087 // numrefs x valueid,
6088 // n x (valueid, callsitecount, profilecount)]
6089 case bitc::FS_PERMODULE:
6090 case bitc::FS_PERMODULE_PROFILE: {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006091 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006092 uint64_t RawFlags = Record[1];
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006093 unsigned InstCount = Record[2];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006094 unsigned NumRefs = Record[3];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006095 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6096 std::unique_ptr<FunctionSummary> FS =
6097 llvm::make_unique<FunctionSummary>(Flags, InstCount);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006098 // The module path string ref set in the summary must be owned by the
6099 // index's module string table. Since we don't have a module path
6100 // string table section in the per-module index, we create a single
6101 // module path string table entry with an empty (0) ID to take
6102 // ownership.
6103 FS->setModulePath(
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006104 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006105 static int RefListStartIndex = 4;
6106 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6107 assert(Record.size() >= RefListStartIndex + NumRefs &&
6108 "Record size inconsistent with number of references");
6109 for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) {
6110 unsigned RefValueId = Record[I];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006111 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006112 FS->addRefEdge(RefGUID);
6113 }
6114 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
6115 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
6116 ++I) {
6117 unsigned CalleeValueId = Record[I];
6118 unsigned CallsiteCount = Record[++I];
6119 uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006120 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006121 FS->addCallGraphEdge(CalleeGUID,
6122 CalleeInfo(CallsiteCount, ProfileCount));
6123 }
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006124 auto GUID = getGUIDFromValueId(ValueID);
6125 FS->setOriginalName(GUID.second);
Teresa Johnson28e457b2016-04-24 14:57:11 +00006126 TheIndex->addGlobalValueSummary(GUID.first, std::move(FS));
Teresa Johnsonbbe05452016-02-24 17:57:28 +00006127 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006128 }
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006129 // FS_ALIAS: [valueid, flags, valueid]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006130 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
6131 // they expect all aliasee summaries to be available.
6132 case bitc::FS_ALIAS: {
6133 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006134 uint64_t RawFlags = Record[1];
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006135 unsigned AliaseeID = Record[2];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006136 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6137 std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006138 // The module path string ref set in the summary must be owned by the
6139 // index's module string table. Since we don't have a module path
6140 // string table section in the per-module index, we create a single
6141 // module path string table entry with an empty (0) ID to take
6142 // ownership.
6143 AS->setModulePath(
6144 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
6145
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006146 GlobalValue::GUID AliaseeGUID = getGUIDFromValueId(AliaseeID).first;
Teresa Johnson28e457b2016-04-24 14:57:11 +00006147 auto *AliaseeSummary = TheIndex->getGlobalValueSummary(AliaseeGUID);
6148 if (!AliaseeSummary)
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006149 return error("Alias expects aliasee summary to be parsed");
Teresa Johnson28e457b2016-04-24 14:57:11 +00006150 AS->setAliasee(AliaseeSummary);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006151
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006152 auto GUID = getGUIDFromValueId(ValueID);
6153 AS->setOriginalName(GUID.second);
Teresa Johnson28e457b2016-04-24 14:57:11 +00006154 TheIndex->addGlobalValueSummary(GUID.first, std::move(AS));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006155 break;
6156 }
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006157 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006158 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
6159 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006160 uint64_t RawFlags = Record[1];
6161 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006162 std::unique_ptr<GlobalVarSummary> FS =
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006163 llvm::make_unique<GlobalVarSummary>(Flags);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006164 FS->setModulePath(
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006165 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006166 for (unsigned I = 2, E = Record.size(); I != E; ++I) {
6167 unsigned RefValueId = Record[I];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006168 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006169 FS->addRefEdge(RefGUID);
6170 }
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006171 auto GUID = getGUIDFromValueId(ValueID);
6172 FS->setOriginalName(GUID.second);
Teresa Johnson28e457b2016-04-24 14:57:11 +00006173 TheIndex->addGlobalValueSummary(GUID.first, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006174 break;
6175 }
Teresa Johnson02e98332016-04-27 13:28:35 +00006176 // FS_COMBINED: [valueid, modid, flags, instcount, numrefs,
6177 // numrefs x valueid, n x (valueid, callsitecount)]
6178 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, numrefs,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006179 // numrefs x valueid,
6180 // n x (valueid, callsitecount, profilecount)]
6181 case bitc::FS_COMBINED:
6182 case bitc::FS_COMBINED_PROFILE: {
Teresa Johnson02e98332016-04-27 13:28:35 +00006183 unsigned ValueID = Record[0];
6184 uint64_t ModuleId = Record[1];
6185 uint64_t RawFlags = Record[2];
6186 unsigned InstCount = Record[3];
6187 unsigned NumRefs = Record[4];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006188 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6189 std::unique_ptr<FunctionSummary> FS =
6190 llvm::make_unique<FunctionSummary>(Flags, InstCount);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006191 LastSeenSummary = FS.get();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006192 FS->setModulePath(ModuleIdMap[ModuleId]);
Teresa Johnson02e98332016-04-27 13:28:35 +00006193 static int RefListStartIndex = 5;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006194 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6195 assert(Record.size() >= RefListStartIndex + NumRefs &&
6196 "Record size inconsistent with number of references");
Teresa Johnson02e98332016-04-27 13:28:35 +00006197 for (unsigned I = RefListStartIndex, E = CallGraphEdgeStartIndex; I != E;
6198 ++I) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006199 unsigned RefValueId = Record[I];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006200 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006201 FS->addRefEdge(RefGUID);
6202 }
6203 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
6204 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
6205 ++I) {
6206 unsigned CalleeValueId = Record[I];
6207 unsigned CallsiteCount = Record[++I];
6208 uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006209 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006210 FS->addCallGraphEdge(CalleeGUID,
6211 CalleeInfo(CallsiteCount, ProfileCount));
6212 }
Teresa Johnson02e98332016-04-27 13:28:35 +00006213 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
Teresa Johnson28e457b2016-04-24 14:57:11 +00006214 TheIndex->addGlobalValueSummary(GUID, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006215 Combined = true;
6216 break;
6217 }
Teresa Johnson02e98332016-04-27 13:28:35 +00006218 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006219 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
6220 // they expect all aliasee summaries to be available.
6221 case bitc::FS_COMBINED_ALIAS: {
Teresa Johnson02e98332016-04-27 13:28:35 +00006222 unsigned ValueID = Record[0];
6223 uint64_t ModuleId = Record[1];
6224 uint64_t RawFlags = Record[2];
6225 unsigned AliaseeValueId = Record[3];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006226 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6227 std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006228 LastSeenSummary = AS.get();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006229 AS->setModulePath(ModuleIdMap[ModuleId]);
6230
Teresa Johnson02e98332016-04-27 13:28:35 +00006231 auto AliaseeGUID = getGUIDFromValueId(AliaseeValueId).first;
6232 auto AliaseeInModule =
6233 TheIndex->findSummaryInModule(AliaseeGUID, AS->modulePath());
6234 if (!AliaseeInModule)
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006235 return error("Alias expects aliasee summary to be parsed");
Teresa Johnson02e98332016-04-27 13:28:35 +00006236 AS->setAliasee(AliaseeInModule);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006237
Teresa Johnson02e98332016-04-27 13:28:35 +00006238 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
Teresa Johnson28e457b2016-04-24 14:57:11 +00006239 TheIndex->addGlobalValueSummary(GUID, std::move(AS));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006240 Combined = true;
6241 break;
6242 }
Teresa Johnson02e98332016-04-27 13:28:35 +00006243 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006244 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
Teresa Johnson02e98332016-04-27 13:28:35 +00006245 unsigned ValueID = Record[0];
6246 uint64_t ModuleId = Record[1];
6247 uint64_t RawFlags = Record[2];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006248 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006249 std::unique_ptr<GlobalVarSummary> FS =
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006250 llvm::make_unique<GlobalVarSummary>(Flags);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006251 LastSeenSummary = FS.get();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006252 FS->setModulePath(ModuleIdMap[ModuleId]);
Teresa Johnson02e98332016-04-27 13:28:35 +00006253 for (unsigned I = 3, E = Record.size(); I != E; ++I) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006254 unsigned RefValueId = Record[I];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006255 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006256 FS->addRefEdge(RefGUID);
6257 }
Teresa Johnson02e98332016-04-27 13:28:35 +00006258 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
Teresa Johnson28e457b2016-04-24 14:57:11 +00006259 TheIndex->addGlobalValueSummary(GUID, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006260 Combined = true;
Teresa Johnsonbbe05452016-02-24 17:57:28 +00006261 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006262 }
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006263 // FS_COMBINED_ORIGINAL_NAME: [original_name]
6264 case bitc::FS_COMBINED_ORIGINAL_NAME: {
6265 uint64_t OriginalName = Record[0];
6266 if (!LastSeenSummary)
6267 return error("Name attachment that does not follow a combined record");
6268 LastSeenSummary->setOriginalName(OriginalName);
6269 // Reset the LastSeenSummary
6270 LastSeenSummary = nullptr;
6271 }
Teresa Johnson403a7872015-10-04 14:33:43 +00006272 }
6273 }
6274 llvm_unreachable("Exit infinite loop");
6275}
6276
6277// Parse the module string table block into the Index.
6278// This populates the ModulePathStringTable map in the index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006279std::error_code ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
Teresa Johnson403a7872015-10-04 14:33:43 +00006280 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
6281 return error("Invalid record");
6282
6283 SmallVector<uint64_t, 64> Record;
6284
6285 SmallString<128> ModulePath;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006286 ModulePathStringTableTy::iterator LastSeenModulePath;
Teresa Johnson403a7872015-10-04 14:33:43 +00006287 while (1) {
6288 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6289
6290 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006291 case BitstreamEntry::SubBlock: // Handled for us already.
6292 case BitstreamEntry::Error:
6293 return error("Malformed block");
6294 case BitstreamEntry::EndBlock:
6295 return std::error_code();
6296 case BitstreamEntry::Record:
6297 // The interesting case.
6298 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00006299 }
6300
6301 Record.clear();
6302 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006303 default: // Default behavior: ignore.
6304 break;
6305 case bitc::MST_CODE_ENTRY: {
6306 // MST_ENTRY: [modid, namechar x N]
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006307 uint64_t ModuleId = Record[0];
6308
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006309 if (convertToString(Record, 1, ModulePath))
6310 return error("Invalid record");
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006311
6312 LastSeenModulePath = TheIndex->addModulePath(ModulePath, ModuleId);
6313 ModuleIdMap[ModuleId] = LastSeenModulePath->first();
6314
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006315 ModulePath.clear();
6316 break;
6317 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006318 /// MST_CODE_HASH: [5*i32]
6319 case bitc::MST_CODE_HASH: {
6320 if (Record.size() != 5)
6321 return error("Invalid hash length " + Twine(Record.size()).str());
6322 if (LastSeenModulePath == TheIndex->modulePaths().end())
6323 return error("Invalid hash that does not follow a module path");
6324 int Pos = 0;
6325 for (auto &Val : Record) {
6326 assert(!(Val >> 32) && "Unexpected high bits set");
6327 LastSeenModulePath->second.second[Pos++] = Val;
6328 }
6329 // Reset LastSeenModulePath to avoid overriding the hash unexpectedly.
6330 LastSeenModulePath = TheIndex->modulePaths().end();
6331 break;
6332 }
Teresa Johnson403a7872015-10-04 14:33:43 +00006333 }
6334 }
6335 llvm_unreachable("Exit infinite loop");
6336}
6337
6338// Parse the function info index from the bitcode streamer into the given index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006339std::error_code ModuleSummaryIndexBitcodeReader::parseSummaryIndexInto(
6340 std::unique_ptr<DataStreamer> Streamer, ModuleSummaryIndex *I) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006341 TheIndex = I;
6342
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006343 if (std::error_code EC = initStream(std::move(Streamer)))
6344 return EC;
Teresa Johnson403a7872015-10-04 14:33:43 +00006345
6346 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006347 if (!hasValidBitcodeHeader(Stream))
6348 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006349
6350 // We expect a number of well-defined blocks, though we don't necessarily
6351 // need to understand them all.
6352 while (1) {
6353 if (Stream.AtEndOfStream()) {
6354 // We didn't really read a proper Module block.
6355 return error("Malformed block");
6356 }
6357
6358 BitstreamEntry Entry =
6359 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
6360
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006361 if (Entry.Kind != BitstreamEntry::SubBlock)
6362 return error("Malformed block");
Teresa Johnson403a7872015-10-04 14:33:43 +00006363
6364 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
6365 // building the function summary index.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006366 if (Entry.ID == bitc::MODULE_BLOCK_ID)
6367 return parseModule();
Teresa Johnson403a7872015-10-04 14:33:43 +00006368
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006369 if (Stream.SkipBlock())
6370 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00006371 }
6372}
6373
Teresa Johnson26ab5772016-03-15 00:04:37 +00006374std::error_code ModuleSummaryIndexBitcodeReader::initStream(
6375 std::unique_ptr<DataStreamer> Streamer) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006376 if (Streamer)
6377 return initLazyStream(std::move(Streamer));
Teresa Johnson403a7872015-10-04 14:33:43 +00006378 return initStreamFromBuffer();
6379}
6380
Teresa Johnson26ab5772016-03-15 00:04:37 +00006381std::error_code ModuleSummaryIndexBitcodeReader::initStreamFromBuffer() {
Teresa Johnson403a7872015-10-04 14:33:43 +00006382 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
6383 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
6384
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006385 if (Buffer->getBufferSize() & 3)
6386 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006387
6388 // If we have a wrapper header, parse it and ignore the non-bc file contents.
6389 // The magic number is 0x0B17C0DE stored in little endian.
6390 if (isBitcodeWrapper(BufPtr, BufEnd))
6391 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
6392 return error("Invalid bitcode wrapper header");
6393
6394 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
6395 Stream.init(&*StreamFile);
6396
6397 return std::error_code();
6398}
6399
Teresa Johnson26ab5772016-03-15 00:04:37 +00006400std::error_code ModuleSummaryIndexBitcodeReader::initLazyStream(
Teresa Johnson403a7872015-10-04 14:33:43 +00006401 std::unique_ptr<DataStreamer> Streamer) {
6402 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
6403 // see it.
6404 auto OwnedBytes =
6405 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
6406 StreamingMemoryObject &Bytes = *OwnedBytes;
6407 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
6408 Stream.init(&*StreamFile);
6409
6410 unsigned char buf[16];
6411 if (Bytes.readBytes(buf, 16, 0) != 16)
6412 return error("Invalid bitcode signature");
6413
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006414 if (!isBitcode(buf, buf + 16))
6415 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006416
6417 if (isBitcodeWrapper(buf, buf + 4)) {
6418 const unsigned char *bitcodeStart = buf;
6419 const unsigned char *bitcodeEnd = buf + 16;
6420 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
6421 Bytes.dropLeadingBytes(bitcodeStart - buf);
6422 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
6423 }
6424 return std::error_code();
6425}
6426
Rafael Espindola48da4f42013-11-04 16:16:24 +00006427namespace {
Peter Collingbourne4718f8b2016-05-24 20:13:46 +00006428// FIXME: This class is only here to support the transition to llvm::Error. It
6429// will be removed once this transition is complete. Clients should prefer to
6430// deal with the Error value directly, rather than converting to error_code.
Rafael Espindola25188c92014-06-12 01:45:43 +00006431class BitcodeErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +00006432 const char *name() const LLVM_NOEXCEPT override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00006433 return "llvm.bitcode";
6434 }
Craig Topper73156022014-03-02 09:09:27 +00006435 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006436 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00006437 switch (E) {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006438 case BitcodeError::InvalidBitcodeSignature:
Rafael Espindola48da4f42013-11-04 16:16:24 +00006439 return "Invalid bitcode signature";
Rafael Espindolad0b23be2015-01-10 00:07:30 +00006440 case BitcodeError::CorruptedBitcode:
6441 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00006442 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00006443 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00006444 }
6445};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00006446} // end anonymous namespace
Rafael Espindola48da4f42013-11-04 16:16:24 +00006447
Chris Bieneman770163e2014-09-19 20:29:02 +00006448static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
6449
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006450const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00006451 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006452}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00006453
Chris Lattner6694f602007-04-29 07:54:31 +00006454//===----------------------------------------------------------------------===//
6455// External interface
6456//===----------------------------------------------------------------------===//
6457
Rafael Espindola456baad2015-06-17 01:15:47 +00006458static ErrorOr<std::unique_ptr<Module>>
6459getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
6460 BitcodeReader *R, LLVMContext &Context,
6461 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
6462 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
6463 M->setMaterializer(R);
6464
6465 auto cleanupOnError = [&](std::error_code EC) {
6466 R->releaseBuffer(); // Never take ownership on error.
6467 return EC;
6468 };
6469
6470 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
6471 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
6472 ShouldLazyLoadMetadata))
6473 return cleanupOnError(EC);
6474
6475 if (MaterializeAll) {
6476 // Read in the entire module, and destroy the BitcodeReader.
Rafael Espindolac4a03482015-12-18 20:13:39 +00006477 if (std::error_code EC = M->materializeAll())
Rafael Espindola456baad2015-06-17 01:15:47 +00006478 return cleanupOnError(EC);
6479 } else {
6480 // Resolve forward references from blockaddresses.
6481 if (std::error_code EC = R->materializeForwardReferencedFunctions())
6482 return cleanupOnError(EC);
6483 }
6484 return std::move(M);
6485}
6486
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006487/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00006488///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006489/// This isn't always used in a lazy context. In particular, it's also used by
6490/// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
6491/// in forward-referenced functions from block address references.
6492///
Rafael Espindola728074b2015-06-17 00:40:56 +00006493/// \param[in] MaterializeAll Set to \c true if we should materialize
6494/// everything.
Rafael Espindoladcd1dca2015-06-16 22:27:55 +00006495static ErrorOr<std::unique_ptr<Module>>
Rafael Espindola68812152014-09-03 17:31:46 +00006496getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindola728074b2015-06-17 00:40:56 +00006497 LLVMContext &Context, bool MaterializeAll,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00006498 bool ShouldLazyLoadMetadata = false) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006499 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00006500
Rafael Espindola456baad2015-06-17 01:15:47 +00006501 ErrorOr<std::unique_ptr<Module>> Ret =
6502 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
6503 MaterializeAll, ShouldLazyLoadMetadata);
6504 if (!Ret)
6505 return Ret;
Rafael Espindolab7993462012-01-02 07:49:53 +00006506
Rafael Espindolae2c1d772014-08-26 22:00:09 +00006507 Buffer.release(); // The BitcodeReader owns it now.
Rafael Espindola456baad2015-06-17 01:15:47 +00006508 return Ret;
Chris Lattner6694f602007-04-29 07:54:31 +00006509}
6510
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006511ErrorOr<std::unique_ptr<Module>>
6512llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
6513 LLVMContext &Context, bool ShouldLazyLoadMetadata) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00006514 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006515 ShouldLazyLoadMetadata);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006516}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006517
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006518ErrorOr<std::unique_ptr<Module>>
6519llvm::getStreamedBitcodeModule(StringRef Name,
6520 std::unique_ptr<DataStreamer> Streamer,
6521 LLVMContext &Context) {
Rafael Espindola7d727b52014-12-18 05:08:43 +00006522 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006523 BitcodeReader *R = new BitcodeReader(Context);
Rafael Espindola456baad2015-06-17 01:15:47 +00006524
6525 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
6526 false);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006527}
6528
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006529ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
6530 LLVMContext &Context) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00006531 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006532 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
Chad Rosierca2567b2011-12-07 21:44:12 +00006533 // TODO: Restore the use-lists to the in-memory state when the bitcode was
6534 // written. We must defer until the Module has been fully materialized.
Chris Lattner6694f602007-04-29 07:54:31 +00006535}
Bill Wendling0198ce02010-10-06 01:22:42 +00006536
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006537std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
6538 LLVMContext &Context) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00006539 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006540 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00006541 ErrorOr<std::string> Triple = R->parseTriple();
Rafael Espindolad346cc82014-07-04 13:52:01 +00006542 if (Triple.getError())
6543 return "";
6544 return Triple.get();
Bill Wendling0198ce02010-10-06 01:22:42 +00006545}
Teresa Johnson403a7872015-10-04 14:33:43 +00006546
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006547std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
6548 LLVMContext &Context) {
Mehdi Amini3383ccc2015-11-09 02:46:41 +00006549 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006550 BitcodeReader R(Buf.release(), Context);
Mehdi Amini3383ccc2015-11-09 02:46:41 +00006551 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
6552 if (ProducerString.getError())
6553 return "";
6554 return ProducerString.get();
6555}
6556
Teresa Johnson403a7872015-10-04 14:33:43 +00006557// Parse the specified bitcode buffer, returning the function info index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006558ErrorOr<std::unique_ptr<ModuleSummaryIndex>>
6559llvm::getModuleSummaryIndex(MemoryBufferRef Buffer,
Teresa Johnson6fb3f192016-04-22 01:52:00 +00006560 DiagnosticHandlerFunction DiagnosticHandler) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006561 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Teresa Johnson6fb3f192016-04-22 01:52:00 +00006562 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler);
Teresa Johnson403a7872015-10-04 14:33:43 +00006563
Teresa Johnson26ab5772016-03-15 00:04:37 +00006564 auto Index = llvm::make_unique<ModuleSummaryIndex>();
Teresa Johnson403a7872015-10-04 14:33:43 +00006565
6566 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006567 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00006568 return EC;
6569 };
6570
6571 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
6572 return cleanupOnError(EC);
6573
Teresa Johnson26ab5772016-03-15 00:04:37 +00006574 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
Teresa Johnson403a7872015-10-04 14:33:43 +00006575 return std::move(Index);
6576}
6577
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006578// Check if the given bitcode buffer contains a global value summary block.
6579bool llvm::hasGlobalValueSummary(MemoryBufferRef Buffer,
6580 DiagnosticHandlerFunction DiagnosticHandler) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006581 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Teresa Johnson6fb3f192016-04-22 01:52:00 +00006582 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler, true);
Teresa Johnson403a7872015-10-04 14:33:43 +00006583
6584 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006585 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00006586 return false;
6587 };
6588
6589 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
6590 return cleanupOnError(EC);
6591
Teresa Johnson26ab5772016-03-15 00:04:37 +00006592 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006593 return R.foundGlobalValSummary();
Teresa Johnson403a7872015-10-04 14:33:43 +00006594}