blob: 658c08f3646c61e0b613a97e39b35cb5c1f0488c [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
Chris Lattner6694f602007-04-29 07:54:31 +000010#include "llvm/Bitcode/ReaderWriter.h"
Benjamin Kramer0a446fd2015-03-01 21:28:53 +000011#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000012#include "llvm/ADT/SmallString.h"
13#include "llvm/ADT/SmallVector.h"
David Majnemer3087b222015-01-20 05:58:07 +000014#include "llvm/ADT/Triple.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000015#include "llvm/Bitcode/BitstreamReader.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000016#include "llvm/Bitcode/LLVMBitCodes.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"
28#include "llvm/IR/OperandTraits.h"
29#include "llvm/IR/Operator.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000030#include "llvm/IR/ValueHandle.h"
Derek Schuff8b2dcad2012-02-06 22:30:29 +000031#include "llvm/Support/DataStream.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000032#include "llvm/Support/ManagedStatic.h"
Chris Lattner08feb1e2007-04-24 04:04:35 +000033#include "llvm/Support/MathExtras.h"
Chris Lattner6694f602007-04-29 07:54:31 +000034#include "llvm/Support/MemoryBuffer.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000035#include "llvm/Support/raw_ostream.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000036#include <deque>
Chris Lattner1314b992007-04-22 06:23:29 +000037using namespace llvm;
38
Benjamin Kramercced8be2015-03-17 20:40:24 +000039namespace {
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +000040enum {
41 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
42};
43
Benjamin Kramercced8be2015-03-17 20:40:24 +000044class BitcodeReaderValueList {
45 std::vector<WeakVH> ValuePtrs;
46
Rafael Espindolacbdcb502015-06-15 20:55:37 +000047 /// As we resolve forward-referenced constants, we add information about them
48 /// to this vector. This allows us to resolve them in bulk instead of
49 /// resolving each reference at a time. See the code in
Benjamin Kramercced8be2015-03-17 20:40:24 +000050 /// ResolveConstantForwardRefs for more information about this.
51 ///
52 /// The key of this vector is the placeholder constant, the value is the slot
53 /// number that holds the resolved value.
54 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
55 ResolveConstantsTy ResolveConstants;
56 LLVMContext &Context;
57public:
58 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
59 ~BitcodeReaderValueList() {
60 assert(ResolveConstants.empty() && "Constants not resolved?");
61 }
62
63 // vector compatibility methods
64 unsigned size() const { return ValuePtrs.size(); }
65 void resize(unsigned N) { ValuePtrs.resize(N); }
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +000066 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
Benjamin Kramercced8be2015-03-17 20:40:24 +000067
68 void clear() {
69 assert(ResolveConstants.empty() && "Constants not resolved?");
70 ValuePtrs.clear();
71 }
72
73 Value *operator[](unsigned i) const {
74 assert(i < ValuePtrs.size());
75 return ValuePtrs[i];
76 }
77
78 Value *back() const { return ValuePtrs.back(); }
79 void pop_back() { ValuePtrs.pop_back(); }
80 bool empty() const { return ValuePtrs.empty(); }
81 void shrinkTo(unsigned N) {
82 assert(N <= size() && "Invalid shrinkTo request!");
83 ValuePtrs.resize(N);
84 }
85
86 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
87 Value *getValueFwdRef(unsigned Idx, Type *Ty);
88
Rafael Espindolacbdcb502015-06-15 20:55:37 +000089 void assignValue(Value *V, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +000090
Rafael Espindolacbdcb502015-06-15 20:55:37 +000091 /// Once all constants are read, this method bulk resolves any forward
92 /// references.
93 void resolveConstantForwardRefs();
Benjamin Kramercced8be2015-03-17 20:40:24 +000094};
95
96class BitcodeReaderMDValueList {
97 unsigned NumFwdRefs;
98 bool AnyFwdRefs;
99 unsigned MinFwdRef;
100 unsigned MaxFwdRef;
101 std::vector<TrackingMDRef> MDValuePtrs;
102
103 LLVMContext &Context;
104public:
105 BitcodeReaderMDValueList(LLVMContext &C)
106 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
107
108 // vector compatibility methods
109 unsigned size() const { return MDValuePtrs.size(); }
110 void resize(unsigned N) { MDValuePtrs.resize(N); }
111 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
112 void clear() { MDValuePtrs.clear(); }
113 Metadata *back() const { return MDValuePtrs.back(); }
114 void pop_back() { MDValuePtrs.pop_back(); }
115 bool empty() const { return MDValuePtrs.empty(); }
116
117 Metadata *operator[](unsigned i) const {
118 assert(i < MDValuePtrs.size());
119 return MDValuePtrs[i];
120 }
121
122 void shrinkTo(unsigned N) {
123 assert(N <= size() && "Invalid shrinkTo request!");
124 MDValuePtrs.resize(N);
125 }
126
127 Metadata *getValueFwdRef(unsigned Idx);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000128 void assignValue(Metadata *MD, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000129 void tryToResolveCycles();
130};
131
132class BitcodeReader : public GVMaterializer {
133 LLVMContext &Context;
134 DiagnosticHandlerFunction DiagnosticHandler;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000135 Module *TheModule = nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000136 std::unique_ptr<MemoryBuffer> Buffer;
137 std::unique_ptr<BitstreamReader> StreamFile;
138 BitstreamCursor Stream;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000139 uint64_t NextUnreadBit = 0;
140 bool SeenValueSymbolTable = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000141
142 std::vector<Type*> TypeList;
143 BitcodeReaderValueList ValueList;
144 BitcodeReaderMDValueList MDValueList;
145 std::vector<Comdat *> ComdatList;
146 SmallVector<Instruction *, 64> InstructionList;
147
148 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
149 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
150 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
151 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
David Majnemer7fddecc2015-06-17 20:52:32 +0000152 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000153
154 SmallVector<Instruction*, 64> InstsWithTBAATag;
155
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000156 /// The set of attributes by index. Index zero in the file is for null, and
157 /// is thus not represented here. As such all indices are off by one.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000158 std::vector<AttributeSet> MAttributes;
159
160 /// \brief The set of attribute groups.
161 std::map<unsigned, AttributeSet> MAttributeGroups;
162
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000163 /// While parsing a function body, this is a list of the basic blocks for the
164 /// function.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000165 std::vector<BasicBlock*> FunctionBBs;
166
167 // When reading the module header, this list is populated with functions that
168 // have bodies later in the file.
169 std::vector<Function*> FunctionsWithBodies;
170
171 // When intrinsic functions are encountered which require upgrading they are
172 // stored here with their replacement function.
Rafael Espindola4e721212015-07-02 16:22:40 +0000173 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000174 UpgradedIntrinsicMap UpgradedIntrinsics;
175
176 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
177 DenseMap<unsigned, unsigned> MDKindMap;
178
179 // Several operations happen after the module header has been read, but
180 // before function bodies are processed. This keeps track of whether
181 // we've done this yet.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000182 bool SeenFirstFunctionBody = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000183
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000184 /// When function bodies are initially scanned, this map contains info about
185 /// where to find deferred function body in the stream.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000186 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
187
188 /// When Metadata block is initially scanned when parsing the module, we may
189 /// choose to defer parsing of the metadata. This vector contains info about
190 /// which Metadata blocks are deferred.
191 std::vector<uint64_t> DeferredMetadataInfo;
192
193 /// These are basic blocks forward-referenced by block addresses. They are
194 /// inserted lazily into functions when they're loaded. The basic block ID is
195 /// its index into the vector.
196 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
197 std::deque<Function *> BasicBlockFwdRefQueue;
198
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000199 /// Indicates that we are using a new encoding for instruction operands where
200 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
201 /// instruction number, for a more compact encoding. Some instruction
202 /// operands are not relative to the instruction ID: basic block numbers, and
203 /// types. Once the old style function blocks have been phased out, we would
Benjamin Kramercced8be2015-03-17 20:40:24 +0000204 /// not need this flag.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000205 bool UseRelativeIDs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000206
207 /// True if all functions will be materialized, negating the need to process
208 /// (e.g.) blockaddress forward references.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000209 bool WillMaterializeAllForwardRefs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000210
211 /// Functions that have block addresses taken. This is usually empty.
212 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
213
214 /// True if any Metadata block has been materialized.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000215 bool IsMetadataMaterialized = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000216
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000217 bool StripDebugInfo = false;
218
Benjamin Kramercced8be2015-03-17 20:40:24 +0000219public:
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000220 std::error_code error(BitcodeError E, const Twine &Message);
221 std::error_code error(BitcodeError E);
222 std::error_code error(const Twine &Message);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000223
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000224 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
225 DiagnosticHandlerFunction DiagnosticHandler);
Rafael Espindola1aabf982015-06-16 23:29:49 +0000226 BitcodeReader(LLVMContext &Context,
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000227 DiagnosticHandlerFunction DiagnosticHandler);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000228 ~BitcodeReader() override { freeState(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000229
230 std::error_code materializeForwardReferencedFunctions();
231
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000232 void freeState();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000233
234 void releaseBuffer();
235
236 bool isDematerializable(const GlobalValue *GV) const override;
237 std::error_code materialize(GlobalValue *GV) override;
Eric Christopher97cb5652015-05-15 18:20:14 +0000238 std::error_code materializeModule(Module *M) override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000239 std::vector<StructType *> getIdentifiedStructTypes() const override;
Eric Christopher97cb5652015-05-15 18:20:14 +0000240 void dematerialize(GlobalValue *GV) override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000241
Rafael Espindola6ace6852015-06-15 21:02:49 +0000242 /// \brief Main interface to parsing a bitcode buffer.
243 /// \returns true if an error occurred.
Rafael Espindola1aabf982015-06-16 23:29:49 +0000244 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
245 Module *M,
Benjamin Kramercced8be2015-03-17 20:40:24 +0000246 bool ShouldLazyLoadMetadata = false);
247
Rafael Espindola6ace6852015-06-15 21:02:49 +0000248 /// \brief Cheap mechanism to just extract module triple
249 /// \returns true if an error occurred.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000250 ErrorOr<std::string> parseTriple();
251
252 static uint64_t decodeSignRotatedValue(uint64_t V);
253
254 /// Materialize any deferred Metadata block.
255 std::error_code materializeMetadata() override;
256
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000257 void setStripDebugInfo() override;
258
Benjamin Kramercced8be2015-03-17 20:40:24 +0000259private:
260 std::vector<StructType *> IdentifiedStructTypes;
261 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
262 StructType *createIdentifiedStructType(LLVMContext &Context);
263
264 Type *getTypeByID(unsigned ID);
265 Value *getFnValueByID(unsigned ID, Type *Ty) {
266 if (Ty && Ty->isMetadataTy())
267 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
268 return ValueList.getValueFwdRef(ID, Ty);
269 }
270 Metadata *getFnMetadataByID(unsigned ID) {
271 return MDValueList.getValueFwdRef(ID);
272 }
273 BasicBlock *getBasicBlock(unsigned ID) const {
274 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
275 return FunctionBBs[ID];
276 }
277 AttributeSet getAttributes(unsigned i) const {
278 if (i-1 < MAttributes.size())
279 return MAttributes[i-1];
280 return AttributeSet();
281 }
282
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000283 /// Read a value/type pair out of the specified record from slot 'Slot'.
284 /// Increment Slot past the number of slots used in the record. Return true on
285 /// failure.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000286 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
287 unsigned InstNum, Value *&ResVal) {
288 if (Slot == Record.size()) return true;
289 unsigned ValNo = (unsigned)Record[Slot++];
290 // Adjust the ValNo, if it was encoded relative to the InstNum.
291 if (UseRelativeIDs)
292 ValNo = InstNum - ValNo;
293 if (ValNo < InstNum) {
294 // If this is not a forward reference, just return the value we already
295 // have.
296 ResVal = getFnValueByID(ValNo, nullptr);
297 return ResVal == nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000298 }
David Blaikiedbe6e0f2015-04-17 06:40:14 +0000299 if (Slot == Record.size())
300 return true;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000301
302 unsigned TypeNo = (unsigned)Record[Slot++];
303 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
304 return ResVal == nullptr;
305 }
306
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000307 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
308 /// past the number of slots used by the value in the record. Return true if
309 /// there is an error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000310 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
311 unsigned InstNum, Type *Ty, Value *&ResVal) {
312 if (getValue(Record, Slot, InstNum, Ty, ResVal))
313 return true;
314 // All values currently take a single record slot.
315 ++Slot;
316 return false;
317 }
318
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000319 /// Like popValue, but does not increment the Slot number.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000320 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
321 unsigned InstNum, Type *Ty, Value *&ResVal) {
322 ResVal = getValue(Record, Slot, InstNum, Ty);
323 return ResVal == nullptr;
324 }
325
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000326 /// Version of getValue that returns ResVal directly, or 0 if there is an
327 /// error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000328 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
329 unsigned InstNum, Type *Ty) {
330 if (Slot == Record.size()) return nullptr;
331 unsigned ValNo = (unsigned)Record[Slot];
332 // Adjust the ValNo, if it was encoded relative to the InstNum.
333 if (UseRelativeIDs)
334 ValNo = InstNum - ValNo;
335 return getFnValueByID(ValNo, Ty);
336 }
337
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000338 /// Like getValue, but decodes signed VBRs.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000339 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
340 unsigned InstNum, Type *Ty) {
341 if (Slot == Record.size()) return nullptr;
342 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
343 // Adjust the ValNo, if it was encoded relative to the InstNum.
344 if (UseRelativeIDs)
345 ValNo = InstNum - ValNo;
346 return getFnValueByID(ValNo, Ty);
347 }
348
349 /// Converts alignment exponent (i.e. power of two (or zero)) to the
350 /// corresponding alignment to use. If alignment is too large, returns
351 /// a corresponding error code.
352 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000353 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
354 std::error_code parseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
355 std::error_code parseAttributeBlock();
356 std::error_code parseAttributeGroupBlock();
357 std::error_code parseTypeTable();
358 std::error_code parseTypeTableBody();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000359
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000360 std::error_code parseValueSymbolTable();
361 std::error_code parseConstants();
362 std::error_code rememberAndSkipFunctionBody();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000363 /// Save the positions of the Metadata blocks and skip parsing the blocks.
364 std::error_code rememberAndSkipMetadata();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000365 std::error_code parseFunctionBody(Function *F);
366 std::error_code globalCleanup();
367 std::error_code resolveGlobalAndAliasInits();
368 std::error_code parseMetadata();
369 std::error_code parseMetadataAttachment(Function &F);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000370 ErrorOr<std::string> parseModuleTriple();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000371 std::error_code parseUseLists();
Rafael Espindola1aabf982015-06-16 23:29:49 +0000372 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000373 std::error_code initStreamFromBuffer();
Rafael Espindola1aabf982015-06-16 23:29:49 +0000374 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000375 std::error_code findFunctionInStream(
Benjamin Kramercced8be2015-03-17 20:40:24 +0000376 Function *F,
377 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
378};
379} // namespace
380
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000381BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
382 DiagnosticSeverity Severity,
383 const Twine &Msg)
384 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
385
386void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
387
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000388static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000389 std::error_code EC, const Twine &Message) {
390 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
391 DiagnosticHandler(DI);
392 return EC;
393}
394
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000395static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000396 std::error_code EC) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000397 return error(DiagnosticHandler, EC, EC.message());
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000398}
399
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000400static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000401 const Twine &Message) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000402 return error(DiagnosticHandler,
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000403 make_error_code(BitcodeError::CorruptedBitcode), Message);
404}
405
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000406std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
407 return ::error(DiagnosticHandler, make_error_code(E), Message);
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000408}
409
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000410std::error_code BitcodeReader::error(const Twine &Message) {
411 return ::error(DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000412 make_error_code(BitcodeError::CorruptedBitcode), Message);
413}
414
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000415std::error_code BitcodeReader::error(BitcodeError E) {
416 return ::error(DiagnosticHandler, make_error_code(E));
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000417}
418
419static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
420 LLVMContext &C) {
421 if (F)
422 return F;
423 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
424}
425
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000426BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000427 DiagnosticHandlerFunction DiagnosticHandler)
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000428 : Context(Context),
429 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
Rafael Espindola1c863ca2015-06-22 18:06:15 +0000430 Buffer(Buffer), ValueList(Context), MDValueList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000431
Rafael Espindola1aabf982015-06-16 23:29:49 +0000432BitcodeReader::BitcodeReader(LLVMContext &Context,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000433 DiagnosticHandlerFunction DiagnosticHandler)
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000434 : Context(Context),
435 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
Rafael Espindola1c863ca2015-06-22 18:06:15 +0000436 Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000437
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000438std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
439 if (WillMaterializeAllForwardRefs)
440 return std::error_code();
441
442 // Prevent recursion.
443 WillMaterializeAllForwardRefs = true;
444
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000445 while (!BasicBlockFwdRefQueue.empty()) {
446 Function *F = BasicBlockFwdRefQueue.front();
447 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000448 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000449 if (!BasicBlockFwdRefs.count(F))
450 // Already materialized.
451 continue;
452
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000453 // Check for a function that isn't materializable to prevent an infinite
454 // loop. When parsing a blockaddress stored in a global variable, there
455 // isn't a trivial way to check if a function will have a body without a
456 // linear search through FunctionsWithBodies, so just check it here.
457 if (!F->isMaterializable())
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000458 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000459
460 // Try to materialize F.
Rafael Espindola5a52e6d2014-10-24 22:50:48 +0000461 if (std::error_code EC = materialize(F))
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000462 return EC;
Rafael Espindolab7993462012-01-02 07:49:53 +0000463 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000464 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000465
466 // Reset state.
467 WillMaterializeAllForwardRefs = false;
468 return std::error_code();
Rafael Espindolab7993462012-01-02 07:49:53 +0000469}
470
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000471void BitcodeReader::freeState() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000472 Buffer = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000473 std::vector<Type*>().swap(TypeList);
Chris Lattner9eeada92007-05-18 04:02:46 +0000474 ValueList.clear();
Devang Patel05eb6172009-08-04 06:00:18 +0000475 MDValueList.clear();
David Majnemerdad0a642014-06-27 18:19:56 +0000476 std::vector<Comdat *>().swap(ComdatList);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000477
Bill Wendlinge94d8432012-12-07 23:16:57 +0000478 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattner9eeada92007-05-18 04:02:46 +0000479 std::vector<BasicBlock*>().swap(FunctionBBs);
480 std::vector<Function*>().swap(FunctionsWithBodies);
481 DeferredFunctionInfo.clear();
Manman Ren4a9b0eb2015-03-13 19:24:30 +0000482 DeferredMetadataInfo.clear();
Dan Gohman43aa8f02010-07-20 21:42:28 +0000483 MDKindMap.clear();
Benjamin Kramer736a4fc2012-09-21 14:34:31 +0000484
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +0000485 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000486 BasicBlockFwdRefQueue.clear();
Chris Lattner6694f602007-04-29 07:54:31 +0000487}
488
Chris Lattnerfee5a372007-05-04 03:30:17 +0000489//===----------------------------------------------------------------------===//
490// Helper functions to implement forward reference resolution, etc.
491//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +0000492
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000493/// Convert a string from a record into an std::string, return true on failure.
494template <typename StrTy>
495static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattnerccaa4482007-04-23 21:26:05 +0000496 StrTy &Result) {
Chris Lattnere14cb882007-05-04 19:11:41 +0000497 if (Idx > Record.size())
Chris Lattner1314b992007-04-22 06:23:29 +0000498 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000499
Chris Lattnere14cb882007-05-04 19:11:41 +0000500 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
501 Result += (char)Record[i];
Chris Lattner1314b992007-04-22 06:23:29 +0000502 return false;
503}
504
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000505static bool hasImplicitComdat(size_t Val) {
506 switch (Val) {
507 default:
508 return false;
509 case 1: // Old WeakAnyLinkage
510 case 4: // Old LinkOnceAnyLinkage
511 case 10: // Old WeakODRLinkage
512 case 11: // Old LinkOnceODRLinkage
513 return true;
514 }
515}
516
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000517static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000518 switch (Val) {
519 default: // Map unknown/new linkages to external
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000520 case 0:
521 return GlobalValue::ExternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000522 case 2:
523 return GlobalValue::AppendingLinkage;
524 case 3:
525 return GlobalValue::InternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000526 case 5:
527 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
528 case 6:
529 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
530 case 7:
531 return GlobalValue::ExternalWeakLinkage;
532 case 8:
533 return GlobalValue::CommonLinkage;
534 case 9:
535 return GlobalValue::PrivateLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000536 case 12:
537 return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000538 case 13:
539 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
540 case 14:
541 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Rafael Espindolabec6af62015-01-08 15:39:50 +0000542 case 15:
543 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000544 case 1: // Old value with implicit comdat.
545 case 16:
546 return GlobalValue::WeakAnyLinkage;
547 case 10: // Old value with implicit comdat.
548 case 17:
549 return GlobalValue::WeakODRLinkage;
550 case 4: // Old value with implicit comdat.
551 case 18:
552 return GlobalValue::LinkOnceAnyLinkage;
553 case 11: // Old value with implicit comdat.
554 case 19:
555 return GlobalValue::LinkOnceODRLinkage;
Chris Lattner1314b992007-04-22 06:23:29 +0000556 }
557}
558
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000559static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000560 switch (Val) {
561 default: // Map unknown visibilities to default.
562 case 0: return GlobalValue::DefaultVisibility;
563 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000564 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000565 }
566}
567
Nico Rieck7157bb72014-01-14 15:22:47 +0000568static GlobalValue::DLLStorageClassTypes
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000569getDecodedDLLStorageClass(unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000570 switch (Val) {
571 default: // Map unknown values to default.
572 case 0: return GlobalValue::DefaultStorageClass;
573 case 1: return GlobalValue::DLLImportStorageClass;
574 case 2: return GlobalValue::DLLExportStorageClass;
575 }
576}
577
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000578static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000579 switch (Val) {
580 case 0: return GlobalVariable::NotThreadLocal;
581 default: // Map unknown non-zero value to general dynamic.
582 case 1: return GlobalVariable::GeneralDynamicTLSModel;
583 case 2: return GlobalVariable::LocalDynamicTLSModel;
584 case 3: return GlobalVariable::InitialExecTLSModel;
585 case 4: return GlobalVariable::LocalExecTLSModel;
586 }
587}
588
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000589static int getDecodedCastOpcode(unsigned Val) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000590 switch (Val) {
591 default: return -1;
592 case bitc::CAST_TRUNC : return Instruction::Trunc;
593 case bitc::CAST_ZEXT : return Instruction::ZExt;
594 case bitc::CAST_SEXT : return Instruction::SExt;
595 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
596 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
597 case bitc::CAST_UITOFP : return Instruction::UIToFP;
598 case bitc::CAST_SITOFP : return Instruction::SIToFP;
599 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
600 case bitc::CAST_FPEXT : return Instruction::FPExt;
601 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
602 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
603 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000604 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000605 }
606}
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000607
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000608static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000609 bool IsFP = Ty->isFPOrFPVectorTy();
610 // BinOps are only valid for int/fp or vector of int/fp types
611 if (!IsFP && !Ty->isIntOrIntVectorTy())
612 return -1;
613
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000614 switch (Val) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000615 default:
616 return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000617 case bitc::BINOP_ADD:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000618 return IsFP ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000619 case bitc::BINOP_SUB:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000620 return IsFP ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000621 case bitc::BINOP_MUL:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000622 return IsFP ? Instruction::FMul : Instruction::Mul;
623 case bitc::BINOP_UDIV:
624 return IsFP ? -1 : Instruction::UDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000625 case bitc::BINOP_SDIV:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000626 return IsFP ? Instruction::FDiv : Instruction::SDiv;
627 case bitc::BINOP_UREM:
628 return IsFP ? -1 : Instruction::URem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000629 case bitc::BINOP_SREM:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000630 return IsFP ? Instruction::FRem : Instruction::SRem;
631 case bitc::BINOP_SHL:
632 return IsFP ? -1 : Instruction::Shl;
633 case bitc::BINOP_LSHR:
634 return IsFP ? -1 : Instruction::LShr;
635 case bitc::BINOP_ASHR:
636 return IsFP ? -1 : Instruction::AShr;
637 case bitc::BINOP_AND:
638 return IsFP ? -1 : Instruction::And;
639 case bitc::BINOP_OR:
640 return IsFP ? -1 : Instruction::Or;
641 case bitc::BINOP_XOR:
642 return IsFP ? -1 : Instruction::Xor;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000643 }
644}
645
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000646static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000647 switch (Val) {
648 default: return AtomicRMWInst::BAD_BINOP;
649 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
650 case bitc::RMW_ADD: return AtomicRMWInst::Add;
651 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
652 case bitc::RMW_AND: return AtomicRMWInst::And;
653 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
654 case bitc::RMW_OR: return AtomicRMWInst::Or;
655 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
656 case bitc::RMW_MAX: return AtomicRMWInst::Max;
657 case bitc::RMW_MIN: return AtomicRMWInst::Min;
658 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
659 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
660 }
661}
662
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000663static AtomicOrdering getDecodedOrdering(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000664 switch (Val) {
665 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
666 case bitc::ORDERING_UNORDERED: return Unordered;
667 case bitc::ORDERING_MONOTONIC: return Monotonic;
668 case bitc::ORDERING_ACQUIRE: return Acquire;
669 case bitc::ORDERING_RELEASE: return Release;
670 case bitc::ORDERING_ACQREL: return AcquireRelease;
671 default: // Map unknown orderings to sequentially-consistent.
672 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
673 }
674}
675
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000676static SynchronizationScope getDecodedSynchScope(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000677 switch (Val) {
678 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
679 default: // Map unknown scopes to cross-thread.
680 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
681 }
682}
683
David Majnemerdad0a642014-06-27 18:19:56 +0000684static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
685 switch (Val) {
686 default: // Map unknown selection kinds to any.
687 case bitc::COMDAT_SELECTION_KIND_ANY:
688 return Comdat::Any;
689 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
690 return Comdat::ExactMatch;
691 case bitc::COMDAT_SELECTION_KIND_LARGEST:
692 return Comdat::Largest;
693 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
694 return Comdat::NoDuplicates;
695 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
696 return Comdat::SameSize;
697 }
698}
699
James Molloy88eb5352015-07-10 12:52:00 +0000700static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
701 FastMathFlags FMF;
702 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
703 FMF.setUnsafeAlgebra();
704 if (0 != (Val & FastMathFlags::NoNaNs))
705 FMF.setNoNaNs();
706 if (0 != (Val & FastMathFlags::NoInfs))
707 FMF.setNoInfs();
708 if (0 != (Val & FastMathFlags::NoSignedZeros))
709 FMF.setNoSignedZeros();
710 if (0 != (Val & FastMathFlags::AllowReciprocal))
711 FMF.setAllowReciprocal();
712 return FMF;
713}
714
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000715static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000716 switch (Val) {
717 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
718 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
719 }
720}
721
Gabor Greiff6caff662008-05-10 08:32:32 +0000722namespace llvm {
Chris Lattner1663cca2007-04-24 05:48:56 +0000723namespace {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000724/// \brief A class for maintaining the slot number definition
725/// as a placeholder for the actual definition for forward constants defs.
726class ConstantPlaceHolder : public ConstantExpr {
727 void operator=(const ConstantPlaceHolder &) = delete;
728
729public:
730 // allocate space for exactly one operand
731 void *operator new(size_t s) { return User::operator new(s, 1); }
732 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
Gabor Greiff6caff662008-05-10 08:32:32 +0000733 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000734 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
735 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000736
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000737 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
738 static bool classof(const Value *V) {
739 return isa<ConstantExpr>(V) &&
740 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
741 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000742
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000743 /// Provide fast operand accessors
744 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
745};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000746}
Chris Lattner1663cca2007-04-24 05:48:56 +0000747
Chris Lattner2d8cd802009-03-31 22:55:09 +0000748// FIXME: can we inherit this from ConstantExpr?
Gabor Greiff6caff662008-05-10 08:32:32 +0000749template <>
Jay Foadc8adf5f2011-01-11 15:07:38 +0000750struct OperandTraits<ConstantPlaceHolder> :
751 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greiff6caff662008-05-10 08:32:32 +0000752};
Richard Trieue3d126c2014-11-21 02:42:08 +0000753DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000754}
Gabor Greiff6caff662008-05-10 08:32:32 +0000755
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000756void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000757 if (Idx == size()) {
758 push_back(V);
759 return;
760 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000761
Chris Lattner2d8cd802009-03-31 22:55:09 +0000762 if (Idx >= size())
763 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000764
Chris Lattner2d8cd802009-03-31 22:55:09 +0000765 WeakVH &OldV = ValuePtrs[Idx];
Craig Topper2617dcc2014-04-15 06:32:26 +0000766 if (!OldV) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000767 OldV = V;
768 return;
769 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000770
Chris Lattner2d8cd802009-03-31 22:55:09 +0000771 // Handle constants and non-constants (e.g. instrs) differently for
772 // efficiency.
773 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
774 ResolveConstants.push_back(std::make_pair(PHC, Idx));
775 OldV = V;
776 } else {
777 // If there was a forward reference to this value, replace it.
778 Value *PrevVal = OldV;
779 OldV->replaceAllUsesWith(V);
780 delete PrevVal;
Gabor Greiff6caff662008-05-10 08:32:32 +0000781 }
782}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000783
Gabor Greiff6caff662008-05-10 08:32:32 +0000784
Chris Lattner1663cca2007-04-24 05:48:56 +0000785Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattner229907c2011-07-18 04:54:35 +0000786 Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000787 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000788 resize(Idx + 1);
Chris Lattner1663cca2007-04-24 05:48:56 +0000789
Chris Lattner2d8cd802009-03-31 22:55:09 +0000790 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhas6a92a3f2015-05-27 01:05:40 +0000791 if (Ty != V->getType())
792 report_fatal_error("Type mismatch in constant table!");
Chris Lattner83930552007-05-01 07:01:57 +0000793 return cast<Constant>(V);
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000794 }
Chris Lattner1663cca2007-04-24 05:48:56 +0000795
796 // Create and return a placeholder, which will later be RAUW'd.
Owen Andersone9f98042009-07-07 20:18:58 +0000797 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000798 ValuePtrs[Idx] = C;
Chris Lattner1663cca2007-04-24 05:48:56 +0000799 return C;
800}
801
Chris Lattner229907c2011-07-18 04:54:35 +0000802Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Filipe Cabecinhasbad07792015-04-30 00:52:42 +0000803 // Bail out for a clearly invalid value. This would make us call resize(0)
804 if (Idx == UINT_MAX)
805 return nullptr;
806
Chris Lattner2d8cd802009-03-31 22:55:09 +0000807 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000808 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000809
Chris Lattner2d8cd802009-03-31 22:55:09 +0000810 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhasb435d0f2015-04-28 20:18:47 +0000811 // If the types don't match, it's invalid.
812 if (Ty && Ty != V->getType())
813 return nullptr;
Chris Lattner83930552007-05-01 07:01:57 +0000814 return V;
815 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000816
Chris Lattner1fc27f02007-05-02 05:16:49 +0000817 // No type specified, must be invalid reference.
Craig Topper2617dcc2014-04-15 06:32:26 +0000818 if (!Ty) return nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000819
Chris Lattner83930552007-05-01 07:01:57 +0000820 // Create and return a placeholder, which will later be RAUW'd.
821 Value *V = new Argument(Ty);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000822 ValuePtrs[Idx] = V;
Chris Lattner83930552007-05-01 07:01:57 +0000823 return V;
824}
825
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000826/// Once all constants are read, this method bulk resolves any forward
827/// references. The idea behind this is that we sometimes get constants (such
828/// as large arrays) which reference *many* forward ref constants. Replacing
829/// each of these causes a lot of thrashing when building/reuniquing the
830/// constant. Instead of doing this, we look at all the uses and rewrite all
831/// the place holders at once for any constant that uses a placeholder.
832void BitcodeReaderValueList::resolveConstantForwardRefs() {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000833 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattner74429932008-08-21 02:34:16 +0000834 // binary search.
835 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000836
Chris Lattner74429932008-08-21 02:34:16 +0000837 SmallVector<Constant*, 64> NewOps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000838
Chris Lattner74429932008-08-21 02:34:16 +0000839 while (!ResolveConstants.empty()) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000840 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattner74429932008-08-21 02:34:16 +0000841 Constant *Placeholder = ResolveConstants.back().first;
842 ResolveConstants.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000843
Chris Lattner74429932008-08-21 02:34:16 +0000844 // Loop over all users of the placeholder, updating them to reference the
845 // new value. If they reference more than one placeholder, update them all
846 // at once.
847 while (!Placeholder->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000848 auto UI = Placeholder->user_begin();
Gabor Greif2c0ab482010-07-09 16:01:21 +0000849 User *U = *UI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000850
Chris Lattner74429932008-08-21 02:34:16 +0000851 // If the using object isn't uniqued, just update the operands. This
852 // handles instructions and initializers for global variables.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000853 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattner479c5d92008-08-21 17:31:45 +0000854 UI.getUse().set(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +0000855 continue;
856 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000857
Chris Lattner74429932008-08-21 02:34:16 +0000858 // Otherwise, we have a constant that uses the placeholder. Replace that
859 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000860 Constant *UserC = cast<Constant>(U);
Chris Lattner74429932008-08-21 02:34:16 +0000861 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
862 I != E; ++I) {
863 Value *NewOp;
864 if (!isa<ConstantPlaceHolder>(*I)) {
865 // Not a placeholder reference.
866 NewOp = *I;
867 } else if (*I == Placeholder) {
868 // Common case is that it just references this one placeholder.
869 NewOp = RealVal;
870 } else {
871 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000872 ResolveConstantsTy::iterator It =
873 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattner74429932008-08-21 02:34:16 +0000874 std::pair<Constant*, unsigned>(cast<Constant>(*I),
875 0));
876 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000877 NewOp = operator[](It->second);
Chris Lattner74429932008-08-21 02:34:16 +0000878 }
879
880 NewOps.push_back(cast<Constant>(NewOp));
881 }
882
883 // Make the new constant.
884 Constant *NewC;
885 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad83be3612011-06-22 09:24:39 +0000886 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000887 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnercc19efa2011-06-20 04:01:31 +0000888 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000889 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner69229312011-02-15 00:14:00 +0000890 NewC = ConstantVector::get(NewOps);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000891 } else {
892 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foad5c984e562011-04-13 13:46:01 +0000893 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000894 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000895
Chris Lattner74429932008-08-21 02:34:16 +0000896 UserC->replaceAllUsesWith(NewC);
897 UserC->destroyConstant();
898 NewOps.clear();
899 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000900
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000901 // Update all ValueHandles, they should be the only users at this point.
902 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +0000903 delete Placeholder;
904 }
905}
906
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000907void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +0000908 if (Idx == size()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000909 push_back(MD);
Devang Patel05eb6172009-08-04 06:00:18 +0000910 return;
911 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000912
Devang Patel05eb6172009-08-04 06:00:18 +0000913 if (Idx >= size())
914 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000915
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000916 TrackingMDRef &OldMD = MDValuePtrs[Idx];
917 if (!OldMD) {
918 OldMD.reset(MD);
Devang Patel05eb6172009-08-04 06:00:18 +0000919 return;
920 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000921
Devang Patel05eb6172009-08-04 06:00:18 +0000922 // If there was a forward reference to this value, replace it.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000923 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000924 PrevMD->replaceAllUsesWith(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000925 --NumFwdRefs;
Devang Patel05eb6172009-08-04 06:00:18 +0000926}
927
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000928Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +0000929 if (Idx >= size())
930 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000931
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000932 if (Metadata *MD = MDValuePtrs[Idx])
933 return MD;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000934
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +0000935 // Track forward refs to be resolved later.
936 if (AnyFwdRefs) {
937 MinFwdRef = std::min(MinFwdRef, Idx);
938 MaxFwdRef = std::max(MaxFwdRef, Idx);
939 } else {
940 AnyFwdRefs = true;
941 MinFwdRef = MaxFwdRef = Idx;
942 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000943 ++NumFwdRefs;
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +0000944
945 // Create and return a placeholder, which will later be RAUW'd.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000946 Metadata *MD = MDNode::getTemporary(Context, None).release();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000947 MDValuePtrs[Idx].reset(MD);
948 return MD;
949}
950
951void BitcodeReaderMDValueList::tryToResolveCycles() {
952 if (!AnyFwdRefs)
953 // Nothing to do.
954 return;
955
956 if (NumFwdRefs)
957 // Still forward references... can't resolve cycles.
958 return;
959
960 // Resolve any cycles.
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +0000961 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
962 auto &MD = MDValuePtrs[I];
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000963 auto *N = dyn_cast_or_null<MDNode>(MD);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000964 if (!N)
965 continue;
966
967 assert(!N->isTemporary() && "Unexpected forward reference");
968 N->resolveCycles();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000969 }
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +0000970
971 // Make sure we return early again until there's another forward ref.
972 AnyFwdRefs = false;
Devang Patel05eb6172009-08-04 06:00:18 +0000973}
Chris Lattner1314b992007-04-22 06:23:29 +0000974
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000975Type *BitcodeReader::getTypeByID(unsigned ID) {
976 // The type table size is always specified correctly.
977 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +0000978 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +0000979
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000980 if (Type *Ty = TypeList[ID])
981 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000982
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000983 // If we have a forward reference, the only possible case is when it is to a
984 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +0000985 return TypeList[ID] = createIdentifiedStructType(Context);
986}
987
988StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
989 StringRef Name) {
990 auto *Ret = StructType::create(Context, Name);
991 IdentifiedStructTypes.push_back(Ret);
992 return Ret;
993}
994
995StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
996 auto *Ret = StructType::create(Context);
997 IdentifiedStructTypes.push_back(Ret);
998 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +0000999}
1000
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001001
Chris Lattnerfee5a372007-05-04 03:30:17 +00001002//===----------------------------------------------------------------------===//
1003// Functions for parsing blocks from the bitcode file
1004//===----------------------------------------------------------------------===//
1005
Bill Wendling56aeccc2013-02-04 23:32:23 +00001006
1007/// \brief This fills an AttrBuilder object with the LLVM attributes that have
1008/// been decoded from the given integer. This function must stay in sync with
1009/// 'encodeLLVMAttributesForBitcode'.
1010static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1011 uint64_t EncodedAttrs) {
1012 // FIXME: Remove in 4.0.
1013
1014 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1015 // the bits above 31 down by 11 bits.
1016 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1017 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1018 "Alignment must be a power of two.");
1019
1020 if (Alignment)
1021 B.addAlignmentAttr(Alignment);
Kostya Serebryanyd688bab2013-02-11 08:13:54 +00001022 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
Bill Wendling56aeccc2013-02-04 23:32:23 +00001023 (EncodedAttrs & 0xffff));
1024}
1025
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001026std::error_code BitcodeReader::parseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001027 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001028 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001029
Devang Patela05633e2008-09-26 22:53:05 +00001030 if (!MAttributes.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001031 return error("Invalid multiple blocks");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001032
Chris Lattnerfee5a372007-05-04 03:30:17 +00001033 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001034
Bill Wendling71173cb2013-01-27 00:36:48 +00001035 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001036
Chris Lattnerfee5a372007-05-04 03:30:17 +00001037 // Read all the records.
1038 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001039 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001040
Chris Lattner27d38752013-01-20 02:13:19 +00001041 switch (Entry.Kind) {
1042 case BitstreamEntry::SubBlock: // Handled for us already.
1043 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001044 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001045 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001046 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001047 case BitstreamEntry::Record:
1048 // The interesting case.
1049 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001050 }
Joe Abbey97b7a172013-02-06 22:14:06 +00001051
Chris Lattnerfee5a372007-05-04 03:30:17 +00001052 // Read a record.
1053 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001054 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +00001055 default: // Default behavior: ignore.
1056 break;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001057 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1058 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +00001059 if (Record.size() & 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001060 return error("Invalid record");
Chris Lattnerfee5a372007-05-04 03:30:17 +00001061
Chris Lattnerfee5a372007-05-04 03:30:17 +00001062 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +00001063 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001064 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling60011b82013-01-29 01:43:29 +00001065 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +00001066 }
Devang Patela05633e2008-09-26 22:53:05 +00001067
Bill Wendlinge94d8432012-12-07 23:16:57 +00001068 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +00001069 Attrs.clear();
1070 break;
1071 }
Bill Wendling0dc08912013-02-12 08:13:50 +00001072 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1073 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1074 Attrs.push_back(MAttributeGroups[Record[i]]);
1075
1076 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1077 Attrs.clear();
1078 break;
1079 }
Duncan Sands04eb67e2007-11-20 14:09:29 +00001080 }
Chris Lattnerfee5a372007-05-04 03:30:17 +00001081 }
1082}
1083
Reid Klecknere9f36af2013-11-12 01:31:00 +00001084// Returns Attribute::None on unrecognized codes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001085static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
Reid Klecknere9f36af2013-11-12 01:31:00 +00001086 switch (Code) {
1087 default:
1088 return Attribute::None;
1089 case bitc::ATTR_KIND_ALIGNMENT:
1090 return Attribute::Alignment;
1091 case bitc::ATTR_KIND_ALWAYS_INLINE:
1092 return Attribute::AlwaysInline;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001093 case bitc::ATTR_KIND_ARGMEMONLY:
1094 return Attribute::ArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001095 case bitc::ATTR_KIND_BUILTIN:
1096 return Attribute::Builtin;
1097 case bitc::ATTR_KIND_BY_VAL:
1098 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +00001099 case bitc::ATTR_KIND_IN_ALLOCA:
1100 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001101 case bitc::ATTR_KIND_COLD:
1102 return Attribute::Cold;
Owen Anderson85fa7d52015-05-26 23:48:40 +00001103 case bitc::ATTR_KIND_CONVERGENT:
1104 return Attribute::Convergent;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001105 case bitc::ATTR_KIND_INLINE_HINT:
1106 return Attribute::InlineHint;
1107 case bitc::ATTR_KIND_IN_REG:
1108 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +00001109 case bitc::ATTR_KIND_JUMP_TABLE:
1110 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001111 case bitc::ATTR_KIND_MIN_SIZE:
1112 return Attribute::MinSize;
1113 case bitc::ATTR_KIND_NAKED:
1114 return Attribute::Naked;
1115 case bitc::ATTR_KIND_NEST:
1116 return Attribute::Nest;
1117 case bitc::ATTR_KIND_NO_ALIAS:
1118 return Attribute::NoAlias;
1119 case bitc::ATTR_KIND_NO_BUILTIN:
1120 return Attribute::NoBuiltin;
1121 case bitc::ATTR_KIND_NO_CAPTURE:
1122 return Attribute::NoCapture;
1123 case bitc::ATTR_KIND_NO_DUPLICATE:
1124 return Attribute::NoDuplicate;
1125 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1126 return Attribute::NoImplicitFloat;
1127 case bitc::ATTR_KIND_NO_INLINE:
1128 return Attribute::NoInline;
1129 case bitc::ATTR_KIND_NON_LAZY_BIND:
1130 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001131 case bitc::ATTR_KIND_NON_NULL:
1132 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001133 case bitc::ATTR_KIND_DEREFERENCEABLE:
1134 return Attribute::Dereferenceable;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001135 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1136 return Attribute::DereferenceableOrNull;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001137 case bitc::ATTR_KIND_NO_RED_ZONE:
1138 return Attribute::NoRedZone;
1139 case bitc::ATTR_KIND_NO_RETURN:
1140 return Attribute::NoReturn;
1141 case bitc::ATTR_KIND_NO_UNWIND:
1142 return Attribute::NoUnwind;
1143 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1144 return Attribute::OptimizeForSize;
1145 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1146 return Attribute::OptimizeNone;
1147 case bitc::ATTR_KIND_READ_NONE:
1148 return Attribute::ReadNone;
1149 case bitc::ATTR_KIND_READ_ONLY:
1150 return Attribute::ReadOnly;
1151 case bitc::ATTR_KIND_RETURNED:
1152 return Attribute::Returned;
1153 case bitc::ATTR_KIND_RETURNS_TWICE:
1154 return Attribute::ReturnsTwice;
1155 case bitc::ATTR_KIND_S_EXT:
1156 return Attribute::SExt;
1157 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1158 return Attribute::StackAlignment;
1159 case bitc::ATTR_KIND_STACK_PROTECT:
1160 return Attribute::StackProtect;
1161 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1162 return Attribute::StackProtectReq;
1163 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1164 return Attribute::StackProtectStrong;
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001165 case bitc::ATTR_KIND_SAFESTACK:
1166 return Attribute::SafeStack;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001167 case bitc::ATTR_KIND_STRUCT_RET:
1168 return Attribute::StructRet;
1169 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1170 return Attribute::SanitizeAddress;
1171 case bitc::ATTR_KIND_SANITIZE_THREAD:
1172 return Attribute::SanitizeThread;
1173 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1174 return Attribute::SanitizeMemory;
1175 case bitc::ATTR_KIND_UW_TABLE:
1176 return Attribute::UWTable;
1177 case bitc::ATTR_KIND_Z_EXT:
1178 return Attribute::ZExt;
1179 }
1180}
1181
JF Bastien30bf96b2015-02-22 19:32:03 +00001182std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1183 unsigned &Alignment) {
1184 // Note: Alignment in bitcode files is incremented by 1, so that zero
1185 // can be used for default alignment.
1186 if (Exponent > Value::MaxAlignmentExponent + 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001187 return error("Invalid alignment value");
JF Bastien30bf96b2015-02-22 19:32:03 +00001188 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1189 return std::error_code();
1190}
1191
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001192std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001193 Attribute::AttrKind *Kind) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001194 *Kind = getAttrFromCode(Code);
Reid Klecknere9f36af2013-11-12 01:31:00 +00001195 if (*Kind == Attribute::None)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001196 return error(BitcodeError::CorruptedBitcode,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001197 "Unknown attribute kind (" + Twine(Code) + ")");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001198 return std::error_code();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001199}
1200
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001201std::error_code BitcodeReader::parseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +00001202 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001203 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001204
1205 if (!MAttributeGroups.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001206 return error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +00001207
1208 SmallVector<uint64_t, 64> Record;
1209
1210 // Read all the records.
1211 while (1) {
1212 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1213
1214 switch (Entry.Kind) {
1215 case BitstreamEntry::SubBlock: // Handled for us already.
1216 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001217 return error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +00001218 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001219 return std::error_code();
Bill Wendlingba629332013-02-10 23:24:25 +00001220 case BitstreamEntry::Record:
1221 // The interesting case.
1222 break;
1223 }
1224
1225 // Read a record.
1226 Record.clear();
1227 switch (Stream.readRecord(Entry.ID, Record)) {
1228 default: // Default behavior: ignore.
1229 break;
1230 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1231 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001232 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001233
Bill Wendlinge46707e2013-02-11 22:32:29 +00001234 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +00001235 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1236
1237 AttrBuilder B;
1238 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1239 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001240 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001241 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001242 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001243
1244 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +00001245 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001246 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001247 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001248 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001249 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001250 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001251 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001252 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001253 else if (Kind == Attribute::Dereferenceable)
1254 B.addDereferenceableAttr(Record[++i]);
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001255 else if (Kind == Attribute::DereferenceableOrNull)
1256 B.addDereferenceableOrNullAttr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +00001257 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +00001258 assert((Record[i] == 3 || Record[i] == 4) &&
1259 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +00001260 bool HasValue = (Record[i++] == 4);
1261 SmallString<64> KindStr;
1262 SmallString<64> ValStr;
1263
1264 while (Record[i] != 0 && i != e)
1265 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001266 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001267
1268 if (HasValue) {
1269 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +00001270 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +00001271 while (Record[i] != 0 && i != e)
1272 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001273 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001274 }
1275
1276 B.addAttribute(KindStr.str(), ValStr.str());
1277 }
1278 }
1279
Bill Wendlinge46707e2013-02-11 22:32:29 +00001280 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +00001281 break;
1282 }
1283 }
1284 }
1285}
1286
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001287std::error_code BitcodeReader::parseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001288 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001289 return error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +00001290
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001291 return parseTypeTableBody();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001292}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001293
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001294std::error_code BitcodeReader::parseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +00001295 if (!TypeList.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001296 return error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +00001297
1298 SmallVector<uint64_t, 64> Record;
1299 unsigned NumRecords = 0;
1300
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001301 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +00001302
Chris Lattner1314b992007-04-22 06:23:29 +00001303 // Read all the records for this type table.
1304 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001305 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001306
Chris Lattner27d38752013-01-20 02:13:19 +00001307 switch (Entry.Kind) {
1308 case BitstreamEntry::SubBlock: // Handled for us already.
1309 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001310 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001311 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +00001312 if (NumRecords != TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001313 return error("Malformed block");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001314 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001315 case BitstreamEntry::Record:
1316 // The interesting case.
1317 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001318 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001319
Chris Lattner1314b992007-04-22 06:23:29 +00001320 // Read a record.
1321 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001322 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001323 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001324 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001325 return error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +00001326 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1327 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1328 // type list. This allows us to reserve space.
1329 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001330 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001331 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001332 continue;
Chris Lattner1314b992007-04-22 06:23:29 +00001333 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +00001334 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001335 break;
Dan Gohman518cda42011-12-17 00:04:22 +00001336 case bitc::TYPE_CODE_HALF: // HALF
1337 ResultTy = Type::getHalfTy(Context);
1338 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001339 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +00001340 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001341 break;
1342 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +00001343 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001344 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001345 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +00001346 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001347 break;
1348 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001349 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001350 break;
1351 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001352 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001353 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001354 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +00001355 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001356 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001357 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +00001358 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001359 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +00001360 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1361 ResultTy = Type::getX86_MMXTy(Context);
1362 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001363 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
Chris Lattner1314b992007-04-22 06:23:29 +00001364 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001365 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001366
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001367 uint64_t NumBits = Record[0];
1368 if (NumBits < IntegerType::MIN_INT_BITS ||
1369 NumBits > IntegerType::MAX_INT_BITS)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001370 return error("Bitwidth for integer type out of range");
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001371 ResultTy = IntegerType::get(Context, NumBits);
Chris Lattner1314b992007-04-22 06:23:29 +00001372 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001373 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001374 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001375 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +00001376 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001377 return error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001378 unsigned AddressSpace = 0;
1379 if (Record.size() == 2)
1380 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001381 ResultTy = getTypeByID(Record[0]);
Filipe Cabecinhasd8a1bcd2015-04-29 02:27:28 +00001382 if (!ResultTy ||
1383 !PointerType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001384 return error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001385 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +00001386 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001387 }
Nuno Lopes561dae02012-05-23 15:19:39 +00001388 case bitc::TYPE_CODE_FUNCTION_OLD: {
1389 // FIXME: attrid is dead, remove it in LLVM 4.0
1390 // FUNCTION: [vararg, attrid, retty, paramty x N]
1391 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001392 return error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +00001393 SmallVector<Type*, 8> ArgTys;
1394 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1395 if (Type *T = getTypeByID(Record[i]))
1396 ArgTys.push_back(T);
1397 else
1398 break;
1399 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001400
Nuno Lopes561dae02012-05-23 15:19:39 +00001401 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001402 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001403 return error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +00001404
1405 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1406 break;
1407 }
Chad Rosier95898722011-11-03 00:14:01 +00001408 case bitc::TYPE_CODE_FUNCTION: {
1409 // FUNCTION: [vararg, retty, paramty x N]
1410 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001411 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001412 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +00001413 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001414 if (Type *T = getTypeByID(Record[i])) {
1415 if (!FunctionType::isValidArgumentType(T))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001416 return error("Invalid function argument type");
Chad Rosier95898722011-11-03 00:14:01 +00001417 ArgTys.push_back(T);
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001418 }
Chad Rosier95898722011-11-03 00:14:01 +00001419 else
1420 break;
1421 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001422
Chad Rosier95898722011-11-03 00:14:01 +00001423 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001424 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001425 return error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +00001426
1427 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1428 break;
1429 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001430 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +00001431 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001432 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001433 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001434 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1435 if (Type *T = getTypeByID(Record[i]))
1436 EltTys.push_back(T);
1437 else
1438 break;
1439 }
1440 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001441 return error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001442 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001443 break;
1444 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001445 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001446 if (convertToString(Record, 0, TypeName))
1447 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001448 continue;
1449
1450 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1451 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001452 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001453
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001454 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001455 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001456
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001457 // Check to see if this was forward referenced, if so fill in the temp.
1458 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1459 if (Res) {
1460 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001461 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001462 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001463 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001464 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001465
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001466 SmallVector<Type*, 8> EltTys;
1467 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1468 if (Type *T = getTypeByID(Record[i]))
1469 EltTys.push_back(T);
1470 else
1471 break;
1472 }
1473 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001474 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001475 Res->setBody(EltTys, Record[0]);
1476 ResultTy = Res;
1477 break;
1478 }
1479 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1480 if (Record.size() != 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001481 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001482
1483 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001484 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001485
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001486 // Check to see if this was forward referenced, if so fill in the temp.
1487 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1488 if (Res) {
1489 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001490 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001491 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001492 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001493 TypeName.clear();
1494 ResultTy = Res;
1495 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001496 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001497 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1498 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001499 return error("Invalid record");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001500 ResultTy = getTypeByID(Record[1]);
1501 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001502 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001503 ResultTy = ArrayType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001504 break;
1505 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1506 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001507 return error("Invalid record");
Filipe Cabecinhas8e421902015-06-03 00:05:30 +00001508 if (Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001509 return error("Invalid vector length");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001510 ResultTy = getTypeByID(Record[1]);
1511 if (!ResultTy || !StructType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001512 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001513 ResultTy = VectorType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001514 break;
1515 }
1516
1517 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001518 return error("Invalid TYPE table");
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001519 if (TypeList[NumRecords])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001520 return error(
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001521 "Invalid TYPE table: Only named structs can be forward referenced");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001522 assert(ResultTy && "Didn't read a type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001523 TypeList[NumRecords++] = ResultTy;
1524 }
1525}
1526
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001527std::error_code BitcodeReader::parseValueSymbolTable() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001528 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001529 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001530
1531 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001532
David Majnemer3087b222015-01-20 05:58:07 +00001533 Triple TT(TheModule->getTargetTriple());
1534
Chris Lattnerccaa4482007-04-23 21:26:05 +00001535 // Read all the records for this value table.
1536 SmallString<128> ValueName;
1537 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001538 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001539
Chris Lattner27d38752013-01-20 02:13:19 +00001540 switch (Entry.Kind) {
1541 case BitstreamEntry::SubBlock: // Handled for us already.
1542 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001543 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001544 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001545 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001546 case BitstreamEntry::Record:
1547 // The interesting case.
1548 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001549 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001550
Chris Lattnerccaa4482007-04-23 21:26:05 +00001551 // Read a record.
1552 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001553 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001554 default: // Default behavior: unknown type.
1555 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00001556 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001557 if (convertToString(Record, 1, ValueName))
1558 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001559 unsigned ValueID = Record[0];
Karthik Bhat82540e92014-03-27 12:08:23 +00001560 if (ValueID >= ValueList.size() || !ValueList[ValueID])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001561 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001562 Value *V = ValueList[ValueID];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001563
Daniel Dunbard786b512009-07-26 00:34:27 +00001564 V->setName(StringRef(ValueName.data(), ValueName.size()));
Rafael Espindola12ca34f2015-01-19 15:16:06 +00001565 if (auto *GO = dyn_cast<GlobalObject>(V)) {
David Majnemer3087b222015-01-20 05:58:07 +00001566 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1567 if (TT.isOSBinFormatMachO())
1568 GO->setComdat(nullptr);
1569 else
1570 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1571 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00001572 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001573 ValueName.clear();
1574 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00001575 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00001576 case bitc::VST_CODE_BBENTRY: {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001577 if (convertToString(Record, 1, ValueName))
1578 return error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00001579 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001580 if (!BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001581 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001582
Daniel Dunbard786b512009-07-26 00:34:27 +00001583 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00001584 ValueName.clear();
1585 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001586 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00001587 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001588 }
1589}
1590
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001591static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1592
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001593std::error_code BitcodeReader::parseMetadata() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00001594 IsMetadataMaterialized = true;
Devang Patel89923232010-01-11 18:52:33 +00001595 unsigned NextMDValueNo = MDValueList.size();
Devang Patel7428d8a2009-07-22 17:43:22 +00001596
1597 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001598 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001599
Devang Patel7428d8a2009-07-22 17:43:22 +00001600 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001601
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001602 auto getMD =
1603 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1604 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1605 if (ID)
1606 return getMD(ID - 1);
1607 return nullptr;
1608 };
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001609 auto getMDString = [&](unsigned ID) -> MDString *{
1610 // This requires that the ID is not really a forward reference. In
1611 // particular, the MDString must already have been resolved.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001612 return cast_or_null<MDString>(getMDOrNull(ID));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001613 };
1614
1615#define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1616 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1617
Devang Patel7428d8a2009-07-22 17:43:22 +00001618 // Read all the records.
1619 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001620 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001621
Chris Lattner27d38752013-01-20 02:13:19 +00001622 switch (Entry.Kind) {
1623 case BitstreamEntry::SubBlock: // Handled for us already.
1624 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001625 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001626 case BitstreamEntry::EndBlock:
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001627 MDValueList.tryToResolveCycles();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001628 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001629 case BitstreamEntry::Record:
1630 // The interesting case.
1631 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00001632 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001633
Devang Patel7428d8a2009-07-22 17:43:22 +00001634 // Read a record.
1635 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001636 unsigned Code = Stream.readRecord(Entry.ID, Record);
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001637 bool IsDistinct = false;
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00001638 switch (Code) {
Devang Patel7428d8a2009-07-22 17:43:22 +00001639 default: // Default behavior: ignore.
1640 break;
Devang Patel27c87ff2009-07-29 22:34:41 +00001641 case bitc::METADATA_NAME: {
Chris Lattner8d140532013-01-20 02:54:05 +00001642 // Read name of the named metadata.
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001643 SmallString<8> Name(Record.begin(), Record.end());
Devang Patel27c87ff2009-07-29 22:34:41 +00001644 Record.clear();
1645 Code = Stream.ReadCode();
1646
Chris Lattner27d38752013-01-20 02:13:19 +00001647 unsigned NextBitCode = Stream.readRecord(Code, Record);
Filipe Cabecinhas14e68672015-05-30 00:17:20 +00001648 if (NextBitCode != bitc::METADATA_NAMED_NODE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001649 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
Devang Patel27c87ff2009-07-29 22:34:41 +00001650
1651 // Read named metadata elements.
1652 unsigned Size = Record.size();
Dan Gohman2637cc12010-07-21 23:38:33 +00001653 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patel27c87ff2009-07-29 22:34:41 +00001654 for (unsigned i = 0; i != Size; ++i) {
Karthik Bhat82540e92014-03-27 12:08:23 +00001655 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
Craig Topper2617dcc2014-04-15 06:32:26 +00001656 if (!MD)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001657 return error("Invalid record");
Dan Gohman2637cc12010-07-21 23:38:33 +00001658 NMD->addOperand(MD);
Devang Patel27c87ff2009-07-29 22:34:41 +00001659 }
Devang Patel27c87ff2009-07-29 22:34:41 +00001660 break;
1661 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00001662 case bitc::METADATA_OLD_FN_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00001663 // FIXME: Remove in 4.0.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001664 // This is a LocalAsMetadata record, the only type of function-local
1665 // metadata.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001666 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001667 return error("Invalid record");
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001668
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001669 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1670 // to be legal, but there's no upgrade path.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001671 auto dropRecord = [&] {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001672 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001673 };
1674 if (Record.size() != 2) {
1675 dropRecord();
1676 break;
1677 }
1678
1679 Type *Ty = getTypeByID(Record[0]);
1680 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1681 dropRecord();
1682 break;
1683 }
1684
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001685 MDValueList.assignValue(
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001686 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1687 NextMDValueNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001688 break;
1689 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00001690 case bitc::METADATA_OLD_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00001691 // FIXME: Remove in 4.0.
Dan Gohman1e0213a2010-07-13 19:33:27 +00001692 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001693 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001694
Devang Patele059ba6e2009-07-23 01:07:34 +00001695 unsigned Size = Record.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001696 SmallVector<Metadata *, 8> Elts;
Devang Patele059ba6e2009-07-23 01:07:34 +00001697 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00001698 Type *Ty = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00001699 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001700 return error("Invalid record");
Chris Lattnerfdd87902009-10-05 05:54:46 +00001701 if (Ty->isMetadataTy())
Devang Patel05eb6172009-08-04 06:00:18 +00001702 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001703 else if (!Ty->isVoidTy()) {
1704 auto *MD =
1705 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1706 assert(isa<ConstantAsMetadata>(MD) &&
1707 "Expected non-function-local metadata");
1708 Elts.push_back(MD);
1709 } else
Craig Topper2617dcc2014-04-15 06:32:26 +00001710 Elts.push_back(nullptr);
Devang Patele059ba6e2009-07-23 01:07:34 +00001711 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001712 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
Devang Patele059ba6e2009-07-23 01:07:34 +00001713 break;
1714 }
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001715 case bitc::METADATA_VALUE: {
1716 if (Record.size() != 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001717 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001718
1719 Type *Ty = getTypeByID(Record[0]);
1720 if (Ty->isMetadataTy() || Ty->isVoidTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001721 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001722
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001723 MDValueList.assignValue(
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001724 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1725 NextMDValueNo++);
1726 break;
1727 }
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001728 case bitc::METADATA_DISTINCT_NODE:
1729 IsDistinct = true;
1730 // fallthrough...
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001731 case bitc::METADATA_NODE: {
1732 SmallVector<Metadata *, 8> Elts;
1733 Elts.reserve(Record.size());
1734 for (unsigned ID : Record)
1735 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001736 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001737 : MDNode::get(Context, Elts),
1738 NextMDValueNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001739 break;
1740 }
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001741 case bitc::METADATA_LOCATION: {
1742 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001743 return error("Invalid record");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001744
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001745 unsigned Line = Record[1];
1746 unsigned Column = Record[2];
1747 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1748 Metadata *InlinedAt =
1749 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001750 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001751 GET_OR_DISTINCT(DILocation, Record[0],
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00001752 (Context, Line, Column, Scope, InlinedAt)),
1753 NextMDValueNo++);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001754 break;
1755 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001756 case bitc::METADATA_GENERIC_DEBUG: {
1757 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001758 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001759
1760 unsigned Tag = Record[1];
1761 unsigned Version = Record[2];
1762
1763 if (Tag >= 1u << 16 || Version != 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001764 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001765
1766 auto *Header = getMDString(Record[3]);
1767 SmallVector<Metadata *, 8> DwarfOps;
1768 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1769 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1770 : nullptr);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001771 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001772 (Context, Tag, Header, DwarfOps)),
1773 NextMDValueNo++);
1774 break;
1775 }
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001776 case bitc::METADATA_SUBRANGE: {
1777 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001778 return error("Invalid record");
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001779
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001780 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001781 GET_OR_DISTINCT(DISubrange, Record[0],
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001782 (Context, Record[1], unrotateSign(Record[2]))),
1783 NextMDValueNo++);
1784 break;
1785 }
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001786 case bitc::METADATA_ENUMERATOR: {
1787 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001788 return error("Invalid record");
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001789
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001790 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001791 (Context, unrotateSign(Record[1]),
1792 getMDString(Record[2]))),
1793 NextMDValueNo++);
1794 break;
1795 }
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001796 case bitc::METADATA_BASIC_TYPE: {
1797 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001798 return error("Invalid record");
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001799
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001800 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001801 GET_OR_DISTINCT(DIBasicType, Record[0],
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001802 (Context, Record[1], getMDString(Record[2]),
1803 Record[3], Record[4], Record[5])),
1804 NextMDValueNo++);
1805 break;
1806 }
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001807 case bitc::METADATA_DERIVED_TYPE: {
1808 if (Record.size() != 12)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001809 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001810
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001811 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001812 GET_OR_DISTINCT(DIDerivedType, Record[0],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001813 (Context, Record[1], getMDString(Record[2]),
1814 getMDOrNull(Record[3]), Record[4],
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001815 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1816 Record[7], Record[8], Record[9], Record[10],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001817 getMDOrNull(Record[11]))),
1818 NextMDValueNo++);
1819 break;
1820 }
1821 case bitc::METADATA_COMPOSITE_TYPE: {
1822 if (Record.size() != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001823 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001824
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001825 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001826 GET_OR_DISTINCT(DICompositeType, Record[0],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001827 (Context, Record[1], getMDString(Record[2]),
1828 getMDOrNull(Record[3]), Record[4],
1829 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1830 Record[7], Record[8], Record[9], Record[10],
1831 getMDOrNull(Record[11]), Record[12],
1832 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1833 getMDString(Record[15]))),
1834 NextMDValueNo++);
1835 break;
1836 }
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001837 case bitc::METADATA_SUBROUTINE_TYPE: {
1838 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001839 return error("Invalid record");
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001840
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001841 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001842 GET_OR_DISTINCT(DISubroutineType, Record[0],
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001843 (Context, Record[1], getMDOrNull(Record[2]))),
1844 NextMDValueNo++);
1845 break;
1846 }
Adrian Prantlab1243f2015-06-29 23:03:47 +00001847
1848 case bitc::METADATA_MODULE: {
1849 if (Record.size() != 6)
1850 return error("Invalid record");
1851
1852 MDValueList.assignValue(
1853 GET_OR_DISTINCT(DIModule, Record[0],
1854 (Context, getMDOrNull(Record[1]),
1855 getMDString(Record[2]), getMDString(Record[3]),
1856 getMDString(Record[4]), getMDString(Record[5]))),
1857 NextMDValueNo++);
1858 break;
1859 }
1860
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001861 case bitc::METADATA_FILE: {
1862 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001863 return error("Invalid record");
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001864
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001865 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001866 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001867 getMDString(Record[2]))),
1868 NextMDValueNo++);
1869 break;
1870 }
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001871 case bitc::METADATA_COMPILE_UNIT: {
Adrian Prantl1f599f92015-05-21 20:37:30 +00001872 if (Record.size() < 14 || Record.size() > 15)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001873 return error("Invalid record");
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001874
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00001875 // Ignore Record[1], which indicates whether this compile unit is
1876 // distinct. It's always distinct.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001877 MDValueList.assignValue(
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00001878 DICompileUnit::getDistinct(
1879 Context, Record[1], getMDOrNull(Record[2]),
1880 getMDString(Record[3]), Record[4], getMDString(Record[5]),
1881 Record[6], getMDString(Record[7]), Record[8],
1882 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1883 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1884 getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14]),
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001885 NextMDValueNo++);
1886 break;
1887 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001888 case bitc::METADATA_SUBPROGRAM: {
1889 if (Record.size() != 19)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001890 return error("Invalid record");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001891
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001892 MDValueList.assignValue(
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001893 GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001894 DISubprogram, Record[0],
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001895 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1896 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1897 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1898 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1899 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1900 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1901 NextMDValueNo++);
1902 break;
1903 }
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001904 case bitc::METADATA_LEXICAL_BLOCK: {
1905 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001906 return error("Invalid record");
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001907
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001908 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001909 GET_OR_DISTINCT(DILexicalBlock, Record[0],
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001910 (Context, getMDOrNull(Record[1]),
1911 getMDOrNull(Record[2]), Record[3], Record[4])),
1912 NextMDValueNo++);
1913 break;
1914 }
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001915 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1916 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001917 return error("Invalid record");
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001918
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001919 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001920 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001921 (Context, getMDOrNull(Record[1]),
1922 getMDOrNull(Record[2]), Record[3])),
1923 NextMDValueNo++);
1924 break;
1925 }
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001926 case bitc::METADATA_NAMESPACE: {
1927 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001928 return error("Invalid record");
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001929
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001930 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001931 GET_OR_DISTINCT(DINamespace, Record[0],
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001932 (Context, getMDOrNull(Record[1]),
1933 getMDOrNull(Record[2]), getMDString(Record[3]),
1934 Record[4])),
1935 NextMDValueNo++);
1936 break;
1937 }
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001938 case bitc::METADATA_TEMPLATE_TYPE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00001939 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001940 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001941
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001942 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00001943 Record[0],
1944 (Context, getMDString(Record[1]),
1945 getMDOrNull(Record[2]))),
1946 NextMDValueNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001947 break;
1948 }
1949 case bitc::METADATA_TEMPLATE_VALUE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00001950 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001951 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001952
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001953 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001954 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00001955 (Context, Record[1], getMDString(Record[2]),
1956 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001957 NextMDValueNo++);
1958 break;
1959 }
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001960 case bitc::METADATA_GLOBAL_VAR: {
1961 if (Record.size() != 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001962 return error("Invalid record");
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001963
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001964 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001965 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001966 (Context, getMDOrNull(Record[1]),
1967 getMDString(Record[2]), getMDString(Record[3]),
1968 getMDOrNull(Record[4]), Record[5],
1969 getMDOrNull(Record[6]), Record[7], Record[8],
1970 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1971 NextMDValueNo++);
1972 break;
1973 }
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001974 case bitc::METADATA_LOCAL_VAR: {
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00001975 // 10th field is for the obseleted 'inlinedAt:' field.
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00001976 if (Record.size() < 8 || Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001977 return error("Invalid record");
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001978
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00001979 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
1980 // DW_TAG_arg_variable.
1981 bool HasTag = Record.size() > 8;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001982 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001983 GET_OR_DISTINCT(DILocalVariable, Record[0],
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00001984 (Context, getMDOrNull(Record[1 + HasTag]),
1985 getMDString(Record[2 + HasTag]),
1986 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
1987 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
1988 Record[7 + HasTag])),
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001989 NextMDValueNo++);
1990 break;
1991 }
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001992 case bitc::METADATA_EXPRESSION: {
1993 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001994 return error("Invalid record");
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001995
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001996 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001997 GET_OR_DISTINCT(DIExpression, Record[0],
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001998 (Context, makeArrayRef(Record).slice(1))),
1999 NextMDValueNo++);
2000 break;
2001 }
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002002 case bitc::METADATA_OBJC_PROPERTY: {
2003 if (Record.size() != 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002004 return error("Invalid record");
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002005
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002006 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002007 GET_OR_DISTINCT(DIObjCProperty, Record[0],
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002008 (Context, getMDString(Record[1]),
2009 getMDOrNull(Record[2]), Record[3],
2010 getMDString(Record[4]), getMDString(Record[5]),
2011 Record[6], getMDOrNull(Record[7]))),
2012 NextMDValueNo++);
2013 break;
2014 }
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002015 case bitc::METADATA_IMPORTED_ENTITY: {
2016 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002017 return error("Invalid record");
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002018
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002019 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002020 GET_OR_DISTINCT(DIImportedEntity, Record[0],
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002021 (Context, Record[1], getMDOrNull(Record[2]),
2022 getMDOrNull(Record[3]), Record[4],
2023 getMDString(Record[5]))),
2024 NextMDValueNo++);
2025 break;
2026 }
Devang Patel7428d8a2009-07-22 17:43:22 +00002027 case bitc::METADATA_STRING: {
Eli Bendersky5d5e18d2014-06-25 15:41:00 +00002028 std::string String(Record.begin(), Record.end());
2029 llvm::UpgradeMDStringConstant(String);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002030 Metadata *MD = MDString::get(Context, String);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002031 MDValueList.assignValue(MD, NextMDValueNo++);
Devang Patel7428d8a2009-07-22 17:43:22 +00002032 break;
2033 }
Devang Patelaf206b82009-09-18 19:26:43 +00002034 case bitc::METADATA_KIND: {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002035 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002036 return error("Invalid record");
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002037
Devang Patelb1a44772009-09-28 21:14:55 +00002038 unsigned Kind = Record[0];
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002039 SmallString<8> Name(Record.begin()+1, Record.end());
2040
Chris Lattnera0566972009-12-29 09:01:33 +00002041 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman43aa8f02010-07-20 21:42:28 +00002042 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002043 return error("Conflicting METADATA_KIND records");
Devang Patelaf206b82009-09-18 19:26:43 +00002044 break;
2045 }
Devang Patel7428d8a2009-07-22 17:43:22 +00002046 }
2047 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002048#undef GET_OR_DISTINCT
Devang Patel7428d8a2009-07-22 17:43:22 +00002049}
2050
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002051/// Decode a signed value stored with the sign bit in the LSB for dense VBR
2052/// encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002053uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00002054 if ((V & 1) == 0)
2055 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002056 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00002057 return -(V >> 1);
2058 // There is no such thing as -0 with integers. "-0" really means MININT.
2059 return 1ULL << 63;
2060}
2061
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002062/// Resolve all of the initializers for global values and aliases that we can.
2063std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00002064 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2065 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002066 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002067 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
David Majnemer7fddecc2015-06-17 20:52:32 +00002068 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002069
Chris Lattner44c17072007-04-26 02:46:40 +00002070 GlobalInitWorklist.swap(GlobalInits);
2071 AliasInitWorklist.swap(AliasInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002072 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002073 FunctionPrologueWorklist.swap(FunctionPrologues);
David Majnemer7fddecc2015-06-17 20:52:32 +00002074 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
Chris Lattner44c17072007-04-26 02:46:40 +00002075
2076 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00002077 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002078 if (ValID >= ValueList.size()) {
2079 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00002080 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002081 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002082 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00002083 GlobalInitWorklist.back().first->setInitializer(C);
2084 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002085 return error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00002086 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002087 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002088 }
2089
2090 while (!AliasInitWorklist.empty()) {
2091 unsigned ValID = AliasInitWorklist.back().second;
2092 if (ValID >= ValueList.size()) {
2093 AliasInits.push_back(AliasInitWorklist.back());
2094 } else {
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002095 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2096 if (!C)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002097 return error("Expected a constant");
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002098 GlobalAlias *Alias = AliasInitWorklist.back().first;
2099 if (C->getType() != Alias->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002100 return error("Alias and aliasee types don't match");
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002101 Alias->setAliasee(C);
Chris Lattner44c17072007-04-26 02:46:40 +00002102 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002103 AliasInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002104 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002105
2106 while (!FunctionPrefixWorklist.empty()) {
2107 unsigned ValID = FunctionPrefixWorklist.back().second;
2108 if (ValID >= ValueList.size()) {
2109 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2110 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002111 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002112 FunctionPrefixWorklist.back().first->setPrefixData(C);
2113 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002114 return error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002115 }
2116 FunctionPrefixWorklist.pop_back();
2117 }
2118
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002119 while (!FunctionPrologueWorklist.empty()) {
2120 unsigned ValID = FunctionPrologueWorklist.back().second;
2121 if (ValID >= ValueList.size()) {
2122 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2123 } else {
2124 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2125 FunctionPrologueWorklist.back().first->setPrologueData(C);
2126 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002127 return error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002128 }
2129 FunctionPrologueWorklist.pop_back();
2130 }
2131
David Majnemer7fddecc2015-06-17 20:52:32 +00002132 while (!FunctionPersonalityFnWorklist.empty()) {
2133 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2134 if (ValID >= ValueList.size()) {
2135 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2136 } else {
2137 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2138 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2139 else
2140 return error("Expected a constant");
2141 }
2142 FunctionPersonalityFnWorklist.pop_back();
2143 }
2144
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002145 return std::error_code();
Chris Lattner44c17072007-04-26 02:46:40 +00002146}
2147
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002148static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002149 SmallVector<uint64_t, 8> Words(Vals.size());
2150 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00002151 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002152
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002153 return APInt(TypeBits, Words);
2154}
2155
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002156std::error_code BitcodeReader::parseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002157 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002158 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002159
2160 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002161
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002162 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00002163 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00002164 unsigned NextCstNo = ValueList.size();
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002165 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002166 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002167
Chris Lattner27d38752013-01-20 02:13:19 +00002168 switch (Entry.Kind) {
2169 case BitstreamEntry::SubBlock: // Handled for us already.
2170 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002171 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002172 case BitstreamEntry::EndBlock:
2173 if (NextCstNo != ValueList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002174 return error("Invalid ronstant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00002175
Chris Lattner27d38752013-01-20 02:13:19 +00002176 // Once all the constants have been read, go through and resolve forward
2177 // references.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002178 ValueList.resolveConstantForwardRefs();
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.
Chris Lattner74429932008-08-21 02:34:16 +00002182 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002183 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002184
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002185 // Read a record.
2186 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00002187 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002188 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002189 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002190 default: // Default behavior: unknown constant
2191 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00002192 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002193 break;
2194 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2195 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002196 return error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00002197 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002198 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002199 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00002200 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002201 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00002202 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002203 break;
2204 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002205 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002206 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002207 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00002208 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00002209 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002210 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002211 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002212
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002213 APInt VInt =
2214 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002215 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002216
Chris Lattner08feb1e2007-04-24 04:04:35 +00002217 break;
2218 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002219 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00002220 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002221 return error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00002222 if (CurTy->isHalfTy())
Tim Northover29178a32013-01-22 09:46:31 +00002223 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2224 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00002225 else if (CurTy->isFloatTy())
Tim Northover29178a32013-01-22 09:46:31 +00002226 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2227 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002228 else if (CurTy->isDoubleTy())
Tim Northover29178a32013-01-22 09:46:31 +00002229 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2230 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002231 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00002232 // Bits are not stored the same way as a normal i80 APInt, compensate.
2233 uint64_t Rearrange[2];
2234 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2235 Rearrange[1] = Record[0] >> 48;
Tim Northover29178a32013-01-22 09:46:31 +00002236 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2237 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002238 } else if (CurTy->isFP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002239 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2240 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002241 else if (CurTy->isPPC_FP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002242 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2243 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002244 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00002245 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002246 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00002247 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002248
Chris Lattnere14cb882007-05-04 19:11:41 +00002249 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2250 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002251 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002252
Chris Lattnere14cb882007-05-04 19:11:41 +00002253 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00002254 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002255
Chris Lattner229907c2011-07-18 04:54:35 +00002256 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00002257 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002258 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00002259 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00002260 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002261 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2262 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002263 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002264 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00002265 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002266 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2267 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002268 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002269 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00002270 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00002271 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002272 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00002273 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002274 break;
2275 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002276 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00002277 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2278 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002279 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002280
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002281 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002282 V = ConstantDataArray::getString(Context, Elts,
2283 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00002284 break;
2285 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002286 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2287 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002288 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002289
Chris Lattner372dd1e2012-01-30 00:51:16 +00002290 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2291 unsigned Size = Record.size();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002292
Chris Lattner372dd1e2012-01-30 00:51:16 +00002293 if (EltTy->isIntegerTy(8)) {
2294 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2295 if (isa<VectorType>(CurTy))
2296 V = ConstantDataVector::get(Context, Elts);
2297 else
2298 V = ConstantDataArray::get(Context, Elts);
2299 } else if (EltTy->isIntegerTy(16)) {
2300 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2301 if (isa<VectorType>(CurTy))
2302 V = ConstantDataVector::get(Context, Elts);
2303 else
2304 V = ConstantDataArray::get(Context, Elts);
2305 } else if (EltTy->isIntegerTy(32)) {
2306 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2307 if (isa<VectorType>(CurTy))
2308 V = ConstantDataVector::get(Context, Elts);
2309 else
2310 V = ConstantDataArray::get(Context, Elts);
2311 } else if (EltTy->isIntegerTy(64)) {
2312 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2313 if (isa<VectorType>(CurTy))
2314 V = ConstantDataVector::get(Context, Elts);
2315 else
2316 V = ConstantDataArray::get(Context, Elts);
2317 } else if (EltTy->isFloatTy()) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002318 SmallVector<float, 16> Elts(Size);
2319 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002320 if (isa<VectorType>(CurTy))
2321 V = ConstantDataVector::get(Context, Elts);
2322 else
2323 V = ConstantDataArray::get(Context, Elts);
2324 } else if (EltTy->isDoubleTy()) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002325 SmallVector<double, 16> Elts(Size);
2326 std::transform(Record.begin(), Record.end(), Elts.begin(),
2327 BitsToDouble);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002328 if (isa<VectorType>(CurTy))
2329 V = ConstantDataVector::get(Context, Elts);
2330 else
2331 V = ConstantDataArray::get(Context, Elts);
2332 } else {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002333 return error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00002334 }
2335 break;
2336 }
2337
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002338 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002339 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002340 return error("Invalid record");
2341 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002342 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002343 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00002344 } else {
2345 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2346 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00002347 unsigned Flags = 0;
2348 if (Record.size() >= 4) {
2349 if (Opc == Instruction::Add ||
2350 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002351 Opc == Instruction::Mul ||
2352 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00002353 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2354 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2355 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2356 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002357 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002358 Opc == Instruction::UDiv ||
2359 Opc == Instruction::LShr ||
2360 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00002361 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00002362 Flags |= SDivOperator::IsExact;
2363 }
2364 }
2365 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00002366 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002367 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002368 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002369 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002370 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002371 return error("Invalid record");
2372 int Opc = getDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00002373 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002374 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00002375 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002376 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002377 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002378 return error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00002379 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002380 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2381 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002382 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002383 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002384 }
Dan Gohman1639c392009-07-27 21:53:46 +00002385 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002386 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
David Blaikieb9263572015-03-13 21:03:36 +00002387 unsigned OpNum = 0;
2388 Type *PointeeType = nullptr;
2389 if (Record.size() % 2)
2390 PointeeType = getTypeByID(Record[OpNum++]);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002391 SmallVector<Constant*, 16> Elts;
David Blaikieb9263572015-03-13 21:03:36 +00002392 while (OpNum != Record.size()) {
2393 Type *ElTy = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002394 if (!ElTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002395 return error("Invalid record");
David Blaikieb9263572015-03-13 21:03:36 +00002396 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002397 }
David Blaikieb9263572015-03-13 21:03:36 +00002398
David Blaikieb9263572015-03-13 21:03:36 +00002399 if (PointeeType &&
David Blaikie4a2e73b2015-04-02 18:55:32 +00002400 PointeeType !=
2401 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2402 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002403 return error("Explicit gep operator type does not match pointee type "
David Blaikie12cf5d702015-03-16 22:03:50 +00002404 "of pointer operand");
David Blaikie4a2e73b2015-04-02 18:55:32 +00002405
2406 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2407 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2408 BitCode ==
2409 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattner890683d2007-04-24 18:15:21 +00002410 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002411 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00002412 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002413 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002414 return error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00002415
2416 Type *SelectorTy = Type::getInt1Ty(Context);
2417
2418 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
2419 // vector. Otherwise, it must be a single bit.
2420 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2421 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
2422 VTy->getNumElements());
2423
2424 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2425 SelectorTy),
2426 ValueList.getConstantFwdRef(Record[1],CurTy),
2427 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002428 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00002429 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002430 case bitc::CST_CODE_CE_EXTRACTELT
2431 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002432 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002433 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002434 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002435 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002436 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002437 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002438 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002439 Constant *Op1 = nullptr;
2440 if (Record.size() == 4) {
2441 Type *IdxTy = getTypeByID(Record[2]);
2442 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002443 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002444 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2445 } else // TODO: Remove with llvm 4.0
2446 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2447 if (!Op1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002448 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002449 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002450 break;
2451 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002452 case bitc::CST_CODE_CE_INSERTELT
2453 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002454 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002455 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002456 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002457 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2458 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2459 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002460 Constant *Op2 = nullptr;
2461 if (Record.size() == 4) {
2462 Type *IdxTy = getTypeByID(Record[2]);
2463 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002464 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002465 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2466 } else // TODO: Remove with llvm 4.0
2467 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2468 if (!Op2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002469 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002470 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002471 break;
2472 }
2473 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002474 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002475 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002476 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002477 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2478 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002479 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002480 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002481 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002482 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002483 break;
2484 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00002485 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002486 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2487 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00002488 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002489 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002490 return error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002491 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2492 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002493 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002494 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00002495 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002496 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00002497 break;
2498 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002499 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002500 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002501 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002502 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002503 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002504 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002505 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2506 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2507
Duncan Sands9dff9be2010-02-15 16:12:20 +00002508 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002509 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00002510 else
Owen Anderson487375e2009-07-29 18:55:55 +00002511 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002512 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00002513 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002514 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00002515 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002516 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002517 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002518 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002519 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00002520 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002521 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002522 unsigned AsmStrSize = Record[1];
2523 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002524 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002525 unsigned ConstStrSize = Record[2+AsmStrSize];
2526 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002527 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002528
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002529 for (unsigned i = 0; i != AsmStrSize; ++i)
2530 AsmStr += (char)Record[2+i];
2531 for (unsigned i = 0; i != ConstStrSize; ++i)
2532 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00002533 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002534 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002535 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002536 break;
2537 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002538 // This version adds support for the asm dialect keywords (e.g.,
2539 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002540 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002541 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002542 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002543 std::string AsmStr, ConstrStr;
2544 bool HasSideEffects = Record[0] & 1;
2545 bool IsAlignStack = (Record[0] >> 1) & 1;
2546 unsigned AsmDialect = Record[0] >> 2;
2547 unsigned AsmStrSize = Record[1];
2548 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002549 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002550 unsigned ConstStrSize = Record[2+AsmStrSize];
2551 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002552 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002553
2554 for (unsigned i = 0; i != AsmStrSize; ++i)
2555 AsmStr += (char)Record[2+i];
2556 for (unsigned i = 0; i != ConstStrSize; ++i)
2557 ConstrStr += (char)Record[3+AsmStrSize+i];
2558 PointerType *PTy = cast<PointerType>(CurTy);
2559 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2560 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00002561 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002562 break;
2563 }
Chris Lattner5956dc82009-10-28 05:53:48 +00002564 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00002565 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002566 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002567 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002568 if (!FnTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002569 return error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00002570 Function *Fn =
2571 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00002572 if (!Fn)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002573 return error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002574
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00002575 // Don't let Fn get dematerialized.
2576 BlockAddressesTaken.insert(Fn);
2577
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002578 // If the function is already parsed we can insert the block address right
2579 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002580 BasicBlock *BB;
2581 unsigned BBID = Record[2];
2582 if (!BBID)
2583 // Invalid reference to entry block.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002584 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002585 if (!Fn->empty()) {
2586 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002587 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002588 if (BBI == BBE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002589 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002590 ++BBI;
2591 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002592 BB = BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002593 } else {
2594 // Otherwise insert a placeholder and remember it so it can be inserted
2595 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00002596 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2597 if (FwdBBs.empty())
2598 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00002599 if (FwdBBs.size() < BBID + 1)
2600 FwdBBs.resize(BBID + 1);
2601 if (!FwdBBs[BBID])
2602 FwdBBs[BBID] = BasicBlock::Create(Context);
2603 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002604 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002605 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00002606 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002607 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002608 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002609
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002610 ValueList.assignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00002611 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002612 }
2613}
Chris Lattner1314b992007-04-22 06:23:29 +00002614
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002615std::error_code BitcodeReader::parseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00002616 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002617 return error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00002618
Chad Rosierca2567b2011-12-07 21:44:12 +00002619 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002620 SmallVector<uint64_t, 64> Record;
Chad Rosierca2567b2011-12-07 21:44:12 +00002621 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002622 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002623
Chris Lattner27d38752013-01-20 02:13:19 +00002624 switch (Entry.Kind) {
2625 case BitstreamEntry::SubBlock: // Handled for us already.
2626 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002627 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002628 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002629 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002630 case BitstreamEntry::Record:
2631 // The interesting case.
2632 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00002633 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002634
Chad Rosierca2567b2011-12-07 21:44:12 +00002635 // Read a use list record.
2636 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002637 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00002638 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00002639 default: // Default behavior: unknown type.
2640 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002641 case bitc::USELIST_CODE_BB:
2642 IsBB = true;
2643 // fallthrough
2644 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00002645 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002646 if (RecordLength < 3)
2647 // Records should have at least an ID and two indexes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002648 return error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002649 unsigned ID = Record.back();
2650 Record.pop_back();
2651
2652 Value *V;
2653 if (IsBB) {
2654 assert(ID < FunctionBBs.size() && "Basic block not found");
2655 V = FunctionBBs[ID];
2656 } else
2657 V = ValueList[ID];
2658 unsigned NumUses = 0;
2659 SmallDenseMap<const Use *, unsigned, 16> Order;
2660 for (const Use &U : V->uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00002661 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002662 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00002663 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002664 }
2665 if (Order.size() != Record.size() || NumUses > Record.size())
2666 // Mismatches can happen if the functions are being materialized lazily
2667 // (out-of-order), or a value has been upgraded.
2668 break;
2669
2670 V->sortUseList([&](const Use &L, const Use &R) {
2671 return Order.lookup(&L) < Order.lookup(&R);
2672 });
Chad Rosierca2567b2011-12-07 21:44:12 +00002673 break;
2674 }
2675 }
2676 }
2677}
2678
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002679/// When we see the block for metadata, remember where it is and then skip it.
2680/// This lets us lazily deserialize the metadata.
2681std::error_code BitcodeReader::rememberAndSkipMetadata() {
2682 // Save the current stream state.
2683 uint64_t CurBit = Stream.GetCurrentBitNo();
2684 DeferredMetadataInfo.push_back(CurBit);
2685
2686 // Skip over the block for now.
2687 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002688 return error("Invalid record");
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002689 return std::error_code();
2690}
2691
2692std::error_code BitcodeReader::materializeMetadata() {
2693 for (uint64_t BitPos : DeferredMetadataInfo) {
2694 // Move the bit stream to the saved position.
2695 Stream.JumpToBit(BitPos);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002696 if (std::error_code EC = parseMetadata())
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002697 return EC;
2698 }
2699 DeferredMetadataInfo.clear();
2700 return std::error_code();
2701}
2702
Rafael Espindola468b8682015-04-01 14:44:59 +00002703void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00002704
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002705/// When we see the block for a function body, remember where it is and then
2706/// skip it. This lets us lazily deserialize the functions.
2707std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002708 // Get the function we are talking about.
2709 if (FunctionsWithBodies.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002710 return error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002711
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002712 Function *Fn = FunctionsWithBodies.back();
2713 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002714
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002715 // Save the current stream state.
2716 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00002717 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002718
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002719 // Skip over the function block for now.
2720 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002721 return error("Invalid record");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002722 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002723}
2724
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002725std::error_code BitcodeReader::globalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002726 // Patch the initializers for globals and aliases up.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002727 resolveGlobalAndAliasInits();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002728 if (!GlobalInits.empty() || !AliasInits.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002729 return error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002730
2731 // Look for intrinsic functions which need to be upgraded at some point
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002732 for (Function &F : *TheModule) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002733 Function *NewFn;
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002734 if (UpgradeIntrinsicFunction(&F, NewFn))
Rafael Espindola4e721212015-07-02 16:22:40 +00002735 UpgradedIntrinsics[&F] = NewFn;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002736 }
2737
2738 // Look for global variables which need to be renamed.
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002739 for (GlobalVariable &GV : TheModule->globals())
2740 UpgradeGlobalVariable(&GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00002741
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002742 // Force deallocation of memory for these vectors to favor the client that
2743 // want lazy deserialization.
2744 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2745 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002746 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002747}
2748
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002749std::error_code BitcodeReader::parseModule(bool Resume,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002750 bool ShouldLazyLoadMetadata) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002751 if (Resume)
2752 Stream.JumpToBit(NextUnreadBit);
2753 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002754 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002755
Chris Lattner1314b992007-04-22 06:23:29 +00002756 SmallVector<uint64_t, 64> Record;
2757 std::vector<std::string> SectionTable;
Gordon Henriksend930f912008-08-17 18:44:35 +00002758 std::vector<std::string> GCTable;
Chris Lattner1314b992007-04-22 06:23:29 +00002759
2760 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00002761 while (1) {
2762 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00002763
Chris Lattner27d38752013-01-20 02:13:19 +00002764 switch (Entry.Kind) {
2765 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002766 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002767 case BitstreamEntry::EndBlock:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002768 return globalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00002769
Chris Lattner27d38752013-01-20 02:13:19 +00002770 case BitstreamEntry::SubBlock:
2771 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00002772 default: // Skip unknown content.
2773 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002774 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002775 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00002776 case bitc::BLOCKINFO_BLOCK_ID:
2777 if (Stream.ReadBlockInfoBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002778 return error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00002779 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00002780 case bitc::PARAMATTR_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002781 if (std::error_code EC = parseAttributeBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002782 return EC;
Chris Lattnerfee5a372007-05-04 03:30:17 +00002783 break;
Bill Wendlingba629332013-02-10 23:24:25 +00002784 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002785 if (std::error_code EC = parseAttributeGroupBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002786 return EC;
Bill Wendlingba629332013-02-10 23:24:25 +00002787 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002788 case bitc::TYPE_BLOCK_ID_NEW:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002789 if (std::error_code EC = parseTypeTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002790 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00002791 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00002792 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002793 if (std::error_code EC = parseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002794 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002795 SeenValueSymbolTable = true;
Chris Lattnerccaa4482007-04-23 21:26:05 +00002796 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002797 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002798 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002799 return EC;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002800 if (std::error_code EC = resolveGlobalAndAliasInits())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002801 return EC;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002802 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00002803 case bitc::METADATA_BLOCK_ID:
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002804 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2805 if (std::error_code EC = rememberAndSkipMetadata())
2806 return EC;
2807 break;
2808 }
2809 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002810 if (std::error_code EC = parseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002811 return EC;
Devang Patel7428d8a2009-07-22 17:43:22 +00002812 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002813 case bitc::FUNCTION_BLOCK_ID:
2814 // If this is the first function body we've seen, reverse the
2815 // FunctionsWithBodies list.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002816 if (!SeenFirstFunctionBody) {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002817 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002818 if (std::error_code EC = globalCleanup())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002819 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002820 SeenFirstFunctionBody = true;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002821 }
Joe Abbey97b7a172013-02-06 22:14:06 +00002822
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002823 if (std::error_code EC = rememberAndSkipFunctionBody())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002824 return EC;
Rafael Espindola1c863ca2015-06-22 18:06:15 +00002825 // Suspend parsing when we reach the function bodies. Subsequent
2826 // materialization calls will resume it when necessary. If the bitcode
2827 // file is old, the symbol table will be at the end instead and will not
2828 // have been seen yet. In this case, just finish the parse now.
2829 if (SeenValueSymbolTable) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002830 NextUnreadBit = Stream.GetCurrentBitNo();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002831 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002832 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002833 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00002834 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002835 if (std::error_code EC = parseUseLists())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002836 return EC;
Chad Rosierca2567b2011-12-07 21:44:12 +00002837 break;
Chris Lattner1314b992007-04-22 06:23:29 +00002838 }
2839 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00002840
Chris Lattner27d38752013-01-20 02:13:19 +00002841 case BitstreamEntry::Record:
2842 // The interesting case.
2843 break;
Chris Lattner1314b992007-04-22 06:23:29 +00002844 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002845
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002846
Chris Lattner1314b992007-04-22 06:23:29 +00002847 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00002848 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner1314b992007-04-22 06:23:29 +00002849 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002850 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattner1314b992007-04-22 06:23:29 +00002851 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002852 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002853 // Only version #0 and #1 are supported so far.
2854 unsigned module_version = Record[0];
2855 switch (module_version) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002856 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002857 return error("Invalid value");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002858 case 0:
2859 UseRelativeIDs = false;
2860 break;
2861 case 1:
2862 UseRelativeIDs = true;
2863 break;
2864 }
Chris Lattner1314b992007-04-22 06:23:29 +00002865 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00002866 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002867 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002868 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002869 if (convertToString(Record, 0, S))
2870 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002871 TheModule->setTargetTriple(S);
2872 break;
2873 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002874 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002875 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002876 if (convertToString(Record, 0, S))
2877 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002878 TheModule->setDataLayout(S);
2879 break;
2880 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002881 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002882 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002883 if (convertToString(Record, 0, S))
2884 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002885 TheModule->setModuleInlineAsm(S);
2886 break;
2887 }
Bill Wendling706d3d62012-11-28 08:41:48 +00002888 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2889 // FIXME: Remove in 4.0.
2890 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002891 if (convertToString(Record, 0, S))
2892 return error("Invalid record");
Bill Wendling706d3d62012-11-28 08:41:48 +00002893 // Ignore value.
2894 break;
2895 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002896 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002897 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002898 if (convertToString(Record, 0, S))
2899 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002900 SectionTable.push_back(S);
2901 break;
2902 }
Gordon Henriksend930f912008-08-17 18:44:35 +00002903 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00002904 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002905 if (convertToString(Record, 0, S))
2906 return error("Invalid record");
Gordon Henriksend930f912008-08-17 18:44:35 +00002907 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00002908 break;
2909 }
David Majnemerdad0a642014-06-27 18:19:56 +00002910 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2911 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002912 return error("Invalid record");
David Majnemerdad0a642014-06-27 18:19:56 +00002913 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2914 unsigned ComdatNameSize = Record[1];
2915 std::string ComdatName;
2916 ComdatName.reserve(ComdatNameSize);
2917 for (unsigned i = 0; i != ComdatNameSize; ++i)
2918 ComdatName += (char)Record[2 + i];
2919 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2920 C->setSelectionKind(SK);
2921 ComdatList.push_back(C);
2922 break;
2923 }
Christopher Lamb54dd24c2007-12-11 08:59:05 +00002924 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00002925 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00002926 // unnamed_addr, externally_initialized, dllstorageclass,
2927 // comdat]
Chris Lattner1314b992007-04-22 06:23:29 +00002928 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner4b00d922007-04-23 16:04:05 +00002929 if (Record.size() < 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002930 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002931 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002932 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002933 return error("Invalid record");
David Blaikie1a848da2015-04-27 19:58:56 +00002934 bool isConstant = Record[1] & 1;
2935 bool explicitType = Record[1] & 2;
2936 unsigned AddressSpace;
2937 if (explicitType) {
2938 AddressSpace = Record[1] >> 2;
2939 } else {
2940 if (!Ty->isPointerTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002941 return error("Invalid type for value");
David Blaikie1a848da2015-04-27 19:58:56 +00002942 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2943 Ty = cast<PointerType>(Ty)->getElementType();
2944 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002945
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002946 uint64_t RawLinkage = Record[3];
2947 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
JF Bastien30bf96b2015-02-22 19:32:03 +00002948 unsigned Alignment;
2949 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
2950 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00002951 std::string Section;
2952 if (Record[5]) {
2953 if (Record[5]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002954 return error("Invalid ID");
Chris Lattner1314b992007-04-22 06:23:29 +00002955 Section = SectionTable[Record[5]-1];
2956 }
Chris Lattner4b00d922007-04-23 16:04:05 +00002957 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00002958 // Local linkage must have default visibility.
2959 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2960 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002961 Visibility = getDecodedVisibility(Record[6]);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00002962
2963 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner53862f72007-05-06 19:27:46 +00002964 if (Record.size() > 7)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002965 TLM = getDecodedThreadLocalMode(Record[7]);
Chris Lattner1314b992007-04-22 06:23:29 +00002966
Rafael Espindola45e6c192011-01-08 16:42:36 +00002967 bool UnnamedAddr = false;
2968 if (Record.size() > 8)
2969 UnnamedAddr = Record[8];
2970
Michael Gottesman27e7ef32013-02-05 05:57:38 +00002971 bool ExternallyInitialized = false;
2972 if (Record.size() > 9)
2973 ExternallyInitialized = Record[9];
2974
Chris Lattner1314b992007-04-22 06:23:29 +00002975 GlobalVariable *NewGV =
Craig Topper2617dcc2014-04-15 06:32:26 +00002976 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
Michael Gottesman27e7ef32013-02-05 05:57:38 +00002977 TLM, AddressSpace, ExternallyInitialized);
Chris Lattner1314b992007-04-22 06:23:29 +00002978 NewGV->setAlignment(Alignment);
2979 if (!Section.empty())
2980 NewGV->setSection(Section);
2981 NewGV->setVisibility(Visibility);
Rafael Espindola45e6c192011-01-08 16:42:36 +00002982 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002983
Nico Rieck7157bb72014-01-14 15:22:47 +00002984 if (Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002985 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
Nico Rieck7157bb72014-01-14 15:22:47 +00002986 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002987 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00002988
Chris Lattnerccaa4482007-04-23 21:26:05 +00002989 ValueList.push_back(NewGV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002990
Chris Lattner47d131b2007-04-24 00:18:21 +00002991 // Remember which value to use for the global initializer.
2992 if (unsigned InitID = Record[2])
2993 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
David Majnemerdad0a642014-06-27 18:19:56 +00002994
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002995 if (Record.size() > 11) {
David Majnemerdad0a642014-06-27 18:19:56 +00002996 if (unsigned ComdatID = Record[11]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00002997 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002998 return error("Invalid global variable comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00002999 NewGV->setComdat(ComdatList[ComdatID - 1]);
3000 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003001 } else if (hasImplicitComdat(RawLinkage)) {
3002 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3003 }
Chris Lattner1314b992007-04-22 06:23:29 +00003004 break;
3005 }
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003006 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Nico Rieck7157bb72014-01-14 15:22:47 +00003007 // alignment, section, visibility, gc, unnamed_addr,
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003008 // prologuedata, dllstorageclass, comdat, prefixdata]
Chris Lattner1314b992007-04-22 06:23:29 +00003009 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003010 if (Record.size() < 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003011 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003012 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003013 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003014 return error("Invalid record");
David Blaikie561a1572015-04-17 16:28:26 +00003015 if (auto *PTy = dyn_cast<PointerType>(Ty))
3016 Ty = PTy->getElementType();
3017 auto *FTy = dyn_cast<FunctionType>(Ty);
Chris Lattner1314b992007-04-22 06:23:29 +00003018 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003019 return error("Invalid type for value");
Chris Lattner1314b992007-04-22 06:23:29 +00003020
Gabor Greife9ecc682008-04-06 20:25:17 +00003021 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3022 "", TheModule);
Chris Lattner1314b992007-04-22 06:23:29 +00003023
Sandeep Patel68c5f472009-09-02 08:44:58 +00003024 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003025 bool isProto = Record[2];
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003026 uint64_t RawLinkage = Record[3];
3027 Func->setLinkage(getDecodedLinkage(RawLinkage));
Devang Patel4c758ea2008-09-25 21:00:45 +00003028 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003029
JF Bastien30bf96b2015-02-22 19:32:03 +00003030 unsigned Alignment;
3031 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3032 return EC;
3033 Func->setAlignment(Alignment);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003034 if (Record[6]) {
3035 if (Record[6]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003036 return error("Invalid ID");
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003037 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattner1314b992007-04-22 06:23:29 +00003038 }
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003039 // Local linkage must have default visibility.
3040 if (!Func->hasLocalLinkage())
3041 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003042 Func->setVisibility(getDecodedVisibility(Record[7]));
Gordon Henriksen71183b62007-12-10 03:18:06 +00003043 if (Record.size() > 8 && Record[8]) {
Filipe Cabecinhasf8a16a92015-04-30 04:09:41 +00003044 if (Record[8]-1 >= GCTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003045 return error("Invalid ID");
Gordon Henriksend930f912008-08-17 18:44:35 +00003046 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen71183b62007-12-10 03:18:06 +00003047 }
Rafael Espindola45e6c192011-01-08 16:42:36 +00003048 bool UnnamedAddr = false;
3049 if (Record.size() > 9)
3050 UnnamedAddr = Record[9];
3051 Func->setUnnamedAddr(UnnamedAddr);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003052 if (Record.size() > 10 && Record[10] != 0)
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003053 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
Nico Rieck7157bb72014-01-14 15:22:47 +00003054
3055 if (Record.size() > 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003056 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003057 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003058 upgradeDLLImportExportLinkage(Func, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00003059
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003060 if (Record.size() > 12) {
David Majnemerdad0a642014-06-27 18:19:56 +00003061 if (unsigned ComdatID = Record[12]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00003062 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003063 return error("Invalid function comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00003064 Func->setComdat(ComdatList[ComdatID - 1]);
3065 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003066 } else if (hasImplicitComdat(RawLinkage)) {
3067 Func->setComdat(reinterpret_cast<Comdat *>(1));
3068 }
David Majnemerdad0a642014-06-27 18:19:56 +00003069
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003070 if (Record.size() > 13 && Record[13] != 0)
3071 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3072
David Majnemer7fddecc2015-06-17 20:52:32 +00003073 if (Record.size() > 14 && Record[14] != 0)
3074 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3075
Chris Lattnerccaa4482007-04-23 21:26:05 +00003076 ValueList.push_back(Func);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003077
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003078 // If this is a function with a body, remember the prototype we are
3079 // creating now, so that we can match up the body with them later.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003080 if (!isProto) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00003081 Func->setIsMaterializable(true);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003082 FunctionsWithBodies.push_back(Func);
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003083 DeferredFunctionInfo[Func] = 0;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003084 }
Chris Lattner1314b992007-04-22 06:23:29 +00003085 break;
3086 }
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00003087 // ALIAS: [alias type, aliasee val#, linkage]
Nico Rieck7157bb72014-01-14 15:22:47 +00003088 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
Chris Lattner831d4202007-04-26 03:27:58 +00003089 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner44c17072007-04-26 02:46:40 +00003090 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003091 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003092 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003093 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003094 return error("Invalid record");
Rafael Espindolaa8004452014-05-16 14:22:33 +00003095 auto *PTy = dyn_cast<PointerType>(Ty);
3096 if (!PTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003097 return error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003098
Rafael Espindolaa8004452014-05-16 14:22:33 +00003099 auto *NewGA =
David Blaikief64246b2015-04-29 21:22:39 +00003100 GlobalAlias::create(PTy, getDecodedLinkage(Record[2]), "", TheModule);
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00003101 // Old bitcode files didn't have visibility field.
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003102 // Local linkage must have default visibility.
3103 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3104 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003105 NewGA->setVisibility(getDecodedVisibility(Record[3]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003106 if (Record.size() > 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003107 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[4]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003108 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003109 upgradeDLLImportExportLinkage(NewGA, Record[2]);
Rafael Espindola59f7eba2014-05-28 18:15:43 +00003110 if (Record.size() > 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003111 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[5]));
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00003112 if (Record.size() > 6)
NAKAMURA Takumi32c87ac2014-10-29 23:44:35 +00003113 NewGA->setUnnamedAddr(Record[6]);
Chris Lattner44c17072007-04-26 02:46:40 +00003114 ValueList.push_back(NewGA);
3115 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3116 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003117 }
Chris Lattner831d4202007-04-26 03:27:58 +00003118 /// MODULE_CODE_PURGEVALS: [numvals]
3119 case bitc::MODULE_CODE_PURGEVALS:
3120 // Trim down the value list to the specified size.
3121 if (Record.size() < 1 || Record[0] > ValueList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003122 return error("Invalid record");
Chris Lattner831d4202007-04-26 03:27:58 +00003123 ValueList.shrinkTo(Record[0]);
3124 break;
3125 }
Chris Lattner1314b992007-04-22 06:23:29 +00003126 Record.clear();
3127 }
Chris Lattner1314b992007-04-22 06:23:29 +00003128}
3129
Rafael Espindola1aabf982015-06-16 23:29:49 +00003130std::error_code
3131BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3132 Module *M, bool ShouldLazyLoadMetadata) {
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003133 TheModule = M;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003134
Rafael Espindola1aabf982015-06-16 23:29:49 +00003135 if (std::error_code EC = initStream(std::move(Streamer)))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003136 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003137
Chris Lattner1314b992007-04-22 06:23:29 +00003138 // Sniff for the signature.
3139 if (Stream.Read(8) != 'B' ||
3140 Stream.Read(8) != 'C' ||
3141 Stream.Read(4) != 0x0 ||
3142 Stream.Read(4) != 0xC ||
3143 Stream.Read(4) != 0xE ||
3144 Stream.Read(4) != 0xD)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003145 return error("Invalid bitcode signature");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003146
Chris Lattner1314b992007-04-22 06:23:29 +00003147 // We expect a number of well-defined blocks, though we don't necessarily
3148 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00003149 while (1) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003150 if (Stream.AtEndOfStream()) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003151 // We didn't really read a proper Module.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003152 return error("Malformed IR file");
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003153 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003154
Chris Lattner27d38752013-01-20 02:13:19 +00003155 BitstreamEntry Entry =
3156 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbey97b7a172013-02-06 22:14:06 +00003157
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003158 if (Entry.Kind != BitstreamEntry::SubBlock)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003159 return error("Malformed block");
Joe Abbey97b7a172013-02-06 22:14:06 +00003160
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003161 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3162 return parseModule(false, ShouldLazyLoadMetadata);
Joe Abbey97b7a172013-02-06 22:14:06 +00003163
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003164 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003165 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003166 }
Chris Lattner1314b992007-04-22 06:23:29 +00003167}
Chris Lattner6694f602007-04-29 07:54:31 +00003168
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003169ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
Bill Wendling0198ce02010-10-06 01:22:42 +00003170 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003171 return error("Invalid record");
Bill Wendling0198ce02010-10-06 01:22:42 +00003172
3173 SmallVector<uint64_t, 64> Record;
3174
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003175 std::string Triple;
Bill Wendling0198ce02010-10-06 01:22:42 +00003176 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00003177 while (1) {
3178 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003179
Chris Lattner27d38752013-01-20 02:13:19 +00003180 switch (Entry.Kind) {
3181 case BitstreamEntry::SubBlock: // Handled for us already.
3182 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003183 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003184 case BitstreamEntry::EndBlock:
Rafael Espindolae6107792014-07-04 20:05:56 +00003185 return Triple;
Chris Lattner27d38752013-01-20 02:13:19 +00003186 case BitstreamEntry::Record:
3187 // The interesting case.
3188 break;
Bill Wendling0198ce02010-10-06 01:22:42 +00003189 }
3190
3191 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00003192 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling0198ce02010-10-06 01:22:42 +00003193 default: break; // Default behavior, ignore unknown content.
Bill Wendling0198ce02010-10-06 01:22:42 +00003194 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003195 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003196 if (convertToString(Record, 0, S))
3197 return error("Invalid record");
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003198 Triple = S;
Bill Wendling0198ce02010-10-06 01:22:42 +00003199 break;
3200 }
3201 }
3202 Record.clear();
3203 }
Rafael Espindolae6107792014-07-04 20:05:56 +00003204 llvm_unreachable("Exit infinite loop");
Bill Wendling0198ce02010-10-06 01:22:42 +00003205}
3206
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003207ErrorOr<std::string> BitcodeReader::parseTriple() {
Rafael Espindola1aabf982015-06-16 23:29:49 +00003208 if (std::error_code EC = initStream(nullptr))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003209 return EC;
Bill Wendling0198ce02010-10-06 01:22:42 +00003210
3211 // Sniff for the signature.
3212 if (Stream.Read(8) != 'B' ||
3213 Stream.Read(8) != 'C' ||
3214 Stream.Read(4) != 0x0 ||
3215 Stream.Read(4) != 0xC ||
3216 Stream.Read(4) != 0xE ||
3217 Stream.Read(4) != 0xD)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003218 return error("Invalid bitcode signature");
Bill Wendling0198ce02010-10-06 01:22:42 +00003219
3220 // We expect a number of well-defined blocks, though we don't necessarily
3221 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00003222 while (1) {
3223 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003224
Chris Lattner27d38752013-01-20 02:13:19 +00003225 switch (Entry.Kind) {
3226 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003227 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003228 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003229 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00003230
Chris Lattner27d38752013-01-20 02:13:19 +00003231 case BitstreamEntry::SubBlock:
3232 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Rafael Espindolad346cc82014-07-04 13:52:01 +00003233 return parseModuleTriple();
Joe Abbey97b7a172013-02-06 22:14:06 +00003234
Chris Lattner27d38752013-01-20 02:13:19 +00003235 // Ignore other sub-blocks.
Rafael Espindola48da4f42013-11-04 16:16:24 +00003236 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003237 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003238 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003239
Chris Lattner27d38752013-01-20 02:13:19 +00003240 case BitstreamEntry::Record:
3241 Stream.skipRecord(Entry.ID);
3242 continue;
Bill Wendling0198ce02010-10-06 01:22:42 +00003243 }
3244 }
Bill Wendling0198ce02010-10-06 01:22:42 +00003245}
3246
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003247/// Parse metadata attachments.
3248std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
Devang Patelaf206b82009-09-18 19:26:43 +00003249 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003250 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003251
Devang Patelaf206b82009-09-18 19:26:43 +00003252 SmallVector<uint64_t, 64> Record;
Chris Lattner27d38752013-01-20 02:13:19 +00003253 while (1) {
3254 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003255
Chris Lattner27d38752013-01-20 02:13:19 +00003256 switch (Entry.Kind) {
3257 case BitstreamEntry::SubBlock: // Handled for us already.
3258 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003259 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003260 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003261 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003262 case BitstreamEntry::Record:
3263 // The interesting case.
Devang Patelaf206b82009-09-18 19:26:43 +00003264 break;
3265 }
Chris Lattner27d38752013-01-20 02:13:19 +00003266
Devang Patelaf206b82009-09-18 19:26:43 +00003267 // Read a metadata attachment record.
3268 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00003269 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patelaf206b82009-09-18 19:26:43 +00003270 default: // Default behavior: ignore.
3271 break;
Chris Lattnerb8778552011-06-17 17:50:30 +00003272 case bitc::METADATA_ATTACHMENT: {
Devang Patelaf206b82009-09-18 19:26:43 +00003273 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003274 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003275 return error("Invalid record");
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003276 if (RecordLength % 2 == 0) {
3277 // A function attachment.
3278 for (unsigned I = 0; I != RecordLength; I += 2) {
3279 auto K = MDKindMap.find(Record[I]);
3280 if (K == MDKindMap.end())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003281 return error("Invalid ID");
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003282 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3283 F.setMetadata(K->second, cast<MDNode>(MD));
3284 }
3285 continue;
3286 }
3287
3288 // An instruction attachment.
Devang Patelaf206b82009-09-18 19:26:43 +00003289 Instruction *Inst = InstructionList[Record[0]];
3290 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patelb1a44772009-09-28 21:14:55 +00003291 unsigned Kind = Record[i];
Dan Gohman43aa8f02010-07-20 21:42:28 +00003292 DenseMap<unsigned, unsigned>::iterator I =
3293 MDKindMap.find(Kind);
3294 if (I == MDKindMap.end())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003295 return error("Invalid ID");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003296 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3297 if (isa<LocalAsMetadata>(Node))
Duncan P. N. Exon Smith35303fd2014-12-06 02:29:44 +00003298 // Drop the attachment. This used to be legal, but there's no
3299 // upgrade path.
3300 break;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003301 Inst->setMetadata(I->second, cast<MDNode>(Node));
Manman Ren209b17c2013-09-28 00:22:27 +00003302 if (I->second == LLVMContext::MD_tbaa)
3303 InstsWithTBAATag.push_back(Inst);
Devang Patelaf206b82009-09-18 19:26:43 +00003304 }
3305 break;
3306 }
3307 }
3308 }
Devang Patelaf206b82009-09-18 19:26:43 +00003309}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003310
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003311static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003312 Type *ValType, Type *PtrType) {
3313 if (!isa<PointerType>(PtrType))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003314 return error(DH, "Load/Store operand is not a pointer type");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003315 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3316
3317 if (ValType && ValType != ElemType)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003318 return error(DH, "Explicit load/store type does not match pointee type of "
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003319 "pointer operand");
3320 if (!PointerType::isLoadableOrStorableType(ElemType))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003321 return error(DH, "Cannot load/store from pointer");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003322 return std::error_code();
3323}
3324
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003325/// Lazily parse the specified function body block.
3326std::error_code BitcodeReader::parseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00003327 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003328 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003329
Nick Lewyckya72e1af2010-02-25 08:30:17 +00003330 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00003331 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman26d837d2010-08-25 20:22:53 +00003332 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003333
Chris Lattner85b7b402007-05-01 05:52:21 +00003334 // Add all the function arguments to the value table.
3335 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3336 ValueList.push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003337
Chris Lattner83930552007-05-01 07:01:57 +00003338 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00003339 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00003340 unsigned CurBBNo = 0;
3341
Chris Lattner07d09ed2010-04-03 02:17:50 +00003342 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003343 auto getLastInstruction = [&]() -> Instruction * {
3344 if (CurBB && !CurBB->empty())
3345 return &CurBB->back();
3346 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3347 !FunctionBBs[CurBBNo - 1]->empty())
3348 return &FunctionBBs[CurBBNo - 1]->back();
3349 return nullptr;
3350 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003351
Chris Lattner85b7b402007-05-01 05:52:21 +00003352 // Read all the records.
3353 SmallVector<uint64_t, 64> Record;
3354 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00003355 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003356
Chris Lattner27d38752013-01-20 02:13:19 +00003357 switch (Entry.Kind) {
3358 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003359 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003360 case BitstreamEntry::EndBlock:
3361 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00003362
Chris Lattner27d38752013-01-20 02:13:19 +00003363 case BitstreamEntry::SubBlock:
3364 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00003365 default: // Skip unknown content.
3366 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003367 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00003368 break;
3369 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003370 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003371 return EC;
Chris Lattner83930552007-05-01 07:01:57 +00003372 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00003373 break;
3374 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003375 if (std::error_code EC = parseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003376 return EC;
Chris Lattner85b7b402007-05-01 05:52:21 +00003377 break;
Devang Patelaf206b82009-09-18 19:26:43 +00003378 case bitc::METADATA_ATTACHMENT_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003379 if (std::error_code EC = parseMetadataAttachment(*F))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003380 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003381 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00003382 case bitc::METADATA_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003383 if (std::error_code EC = parseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003384 return EC;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00003385 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003386 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003387 if (std::error_code EC = parseUseLists())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003388 return EC;
3389 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00003390 }
3391 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003392
Chris Lattner27d38752013-01-20 02:13:19 +00003393 case BitstreamEntry::Record:
3394 // The interesting case.
3395 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00003396 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003397
Chris Lattner85b7b402007-05-01 05:52:21 +00003398 // Read a record.
3399 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00003400 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00003401 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00003402 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00003403 default: // Default behavior: reject
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003404 return error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003405 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00003406 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003407 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00003408 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00003409 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003410
3411 // See if anything took the address of blocks in this function.
3412 auto BBFRI = BasicBlockFwdRefs.find(F);
3413 if (BBFRI == BasicBlockFwdRefs.end()) {
3414 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3415 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3416 } else {
3417 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003418 // Check for invalid basic block references.
3419 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003420 return error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003421 assert(!BBRefs.empty() && "Unexpected empty array");
3422 assert(!BBRefs.front() && "Invalid reference to entry block");
3423 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3424 ++I)
3425 if (I < RE && BBRefs[I]) {
3426 BBRefs[I]->insertInto(F);
3427 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003428 } else {
3429 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3430 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003431
3432 // Erase from the table.
3433 BasicBlockFwdRefs.erase(BBFRI);
3434 }
3435
Chris Lattner83930552007-05-01 07:01:57 +00003436 CurBB = FunctionBBs[0];
3437 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003438 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003439
Chris Lattner07d09ed2010-04-03 02:17:50 +00003440 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3441 // This record indicates that the last instruction is at the same
3442 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003443 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003444
Craig Topper2617dcc2014-04-15 06:32:26 +00003445 if (!I)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003446 return error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00003447 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003448 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003449 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003450
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00003451 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003452 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00003453 if (!I || Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003454 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003455
Chris Lattner07d09ed2010-04-03 02:17:50 +00003456 unsigned Line = Record[0], Col = Record[1];
3457 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003458
Craig Topper2617dcc2014-04-15 06:32:26 +00003459 MDNode *Scope = nullptr, *IA = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003460 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3461 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3462 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3463 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003464 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003465 continue;
3466 }
3467
Chris Lattnere9759c22007-05-06 00:21:25 +00003468 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3469 unsigned OpNum = 0;
3470 Value *LHS, *RHS;
3471 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003472 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00003473 OpNum+1 > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003474 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003475
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003476 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00003477 if (Opc == -1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003478 return error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003479 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00003480 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00003481 if (OpNum < Record.size()) {
3482 if (Opc == Instruction::Add ||
3483 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003484 Opc == Instruction::Mul ||
3485 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00003486 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00003487 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00003488 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00003489 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00003490 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003491 Opc == Instruction::UDiv ||
3492 Opc == Instruction::LShr ||
3493 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00003494 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00003495 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003496 } else if (isa<FPMathOperator>(I)) {
James Molloy88eb5352015-07-10 12:52:00 +00003497 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003498 if (FMF.any())
3499 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00003500 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003501
Dan Gohman1b849082009-09-07 23:54:19 +00003502 }
Chris Lattner85b7b402007-05-01 05:52:21 +00003503 break;
3504 }
Chris Lattnere9759c22007-05-06 00:21:25 +00003505 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3506 unsigned OpNum = 0;
3507 Value *Op;
3508 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3509 OpNum+2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003510 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003511
Chris Lattner229907c2011-07-18 04:54:35 +00003512 Type *ResTy = getTypeByID(Record[OpNum]);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003513 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003514 if (Opc == -1 || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003515 return error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00003516 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003517 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3518 if (Temp) {
3519 InstructionList.push_back(Temp);
3520 CurBB->getInstList().push_back(Temp);
3521 }
3522 } else {
3523 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3524 }
Devang Patelaf206b82009-09-18 19:26:43 +00003525 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00003526 break;
3527 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00003528 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3529 case bitc::FUNC_CODE_INST_GEP_OLD:
3530 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003531 unsigned OpNum = 0;
David Blaikieb5b5efd2015-02-25 01:08:52 +00003532
3533 Type *Ty;
3534 bool InBounds;
3535
3536 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3537 InBounds = Record[OpNum++];
3538 Ty = getTypeByID(Record[OpNum++]);
3539 } else {
3540 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3541 Ty = nullptr;
3542 }
3543
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003544 Value *BasePtr;
3545 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003546 return error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00003547
David Blaikie60310f22015-05-08 00:42:26 +00003548 if (!Ty)
3549 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
3550 ->getElementType();
3551 else if (Ty !=
3552 cast<SequentialType>(BasePtr->getType()->getScalarType())
3553 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003554 return error(
David Blaikie675e8cb2015-03-16 21:35:48 +00003555 "Explicit gep type does not match pointee type of pointer operand");
3556
Chris Lattner5285b5e2007-05-02 05:46:45 +00003557 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003558 while (OpNum != Record.size()) {
3559 Value *Op;
3560 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003561 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003562 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003563 }
3564
David Blaikie096b1da2015-03-14 19:53:33 +00003565 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
David Blaikie675e8cb2015-03-16 21:35:48 +00003566
Devang Patelaf206b82009-09-18 19:26:43 +00003567 InstructionList.push_back(I);
David Blaikieb5b5efd2015-02-25 01:08:52 +00003568 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00003569 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003570 break;
3571 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003572
Dan Gohman1ecaf452008-05-31 00:58:22 +00003573 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3574 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00003575 unsigned OpNum = 0;
3576 Value *Agg;
3577 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003578 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003579
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003580 unsigned RecSize = Record.size();
3581 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003582 return error("EXTRACTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003583
Dan Gohman1ecaf452008-05-31 00:58:22 +00003584 SmallVector<unsigned, 4> EXTRACTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003585 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003586 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003587 bool IsArray = CurTy->isArrayTy();
3588 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003589 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003590
3591 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003592 return error("EXTRACTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003593 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003594 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003595 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003596 return error("EXTRACTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003597 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003598 return error("EXTRACTVAL: Invalid array index");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003599 EXTRACTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003600
3601 if (IsStruct)
3602 CurTy = CurTy->subtypes()[Index];
3603 else
3604 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00003605 }
3606
Jay Foad57aa6362011-07-13 10:26:04 +00003607 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003608 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00003609 break;
3610 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003611
Dan Gohman1ecaf452008-05-31 00:58:22 +00003612 case bitc::FUNC_CODE_INST_INSERTVAL: {
3613 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00003614 unsigned OpNum = 0;
3615 Value *Agg;
3616 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003617 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003618 Value *Val;
3619 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003620 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003621
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003622 unsigned RecSize = Record.size();
3623 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003624 return error("INSERTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003625
Dan Gohman1ecaf452008-05-31 00:58:22 +00003626 SmallVector<unsigned, 4> INSERTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003627 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003628 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003629 bool IsArray = CurTy->isArrayTy();
3630 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003631 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003632
3633 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003634 return error("INSERTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003635 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003636 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003637 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003638 return error("INSERTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003639 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003640 return error("INSERTVAL: Invalid array index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003641
Dan Gohman1ecaf452008-05-31 00:58:22 +00003642 INSERTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003643 if (IsStruct)
3644 CurTy = CurTy->subtypes()[Index];
3645 else
3646 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00003647 }
3648
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00003649 if (CurTy != Val->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003650 return error("Inserted value type doesn't match aggregate type");
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00003651
Jay Foad57aa6362011-07-13 10:26:04 +00003652 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003653 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00003654 break;
3655 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003656
Chris Lattnere9759c22007-05-06 00:21:25 +00003657 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00003658 // obsolete form of select
3659 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00003660 unsigned OpNum = 0;
3661 Value *TrueVal, *FalseVal, *Cond;
3662 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003663 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3664 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003665 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003666
Dan Gohmanc5d28922008-09-16 01:01:33 +00003667 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00003668 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00003669 break;
3670 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003671
Dan Gohmanc5d28922008-09-16 01:01:33 +00003672 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3673 // new form of select
3674 // handles select i1 or select [N x i1]
3675 unsigned OpNum = 0;
3676 Value *TrueVal, *FalseVal, *Cond;
3677 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003678 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00003679 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003680 return error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00003681
3682 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00003683 if (VectorType* vector_type =
3684 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00003685 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003686 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003687 return error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00003688 } else {
3689 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003690 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003691 return error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003692 }
3693
Gabor Greife9ecc682008-04-06 20:25:17 +00003694 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00003695 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003696 break;
3697 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003698
Chris Lattner1fc27f02007-05-02 05:16:49 +00003699 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00003700 unsigned OpNum = 0;
3701 Value *Vec, *Idx;
3702 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003703 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003704 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003705 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003706 return error("Invalid type for value");
Eric Christopherc9742252009-07-25 02:28:41 +00003707 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00003708 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003709 break;
3710 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003711
Chris Lattner1fc27f02007-05-02 05:16:49 +00003712 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00003713 unsigned OpNum = 0;
3714 Value *Vec, *Elt, *Idx;
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003715 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003716 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003717 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003718 return error("Invalid type for value");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003719 if (popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00003720 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003721 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003722 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00003723 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00003724 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003725 break;
3726 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003727
Chris Lattnere9759c22007-05-06 00:21:25 +00003728 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3729 unsigned OpNum = 0;
3730 Value *Vec1, *Vec2, *Mask;
3731 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003732 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003733 return error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00003734
Mon P Wang25f01062008-11-10 04:46:22 +00003735 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003736 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003737 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003738 return error("Invalid type for value");
Chris Lattner1fc27f02007-05-02 05:16:49 +00003739 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00003740 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003741 break;
3742 }
Mon P Wang25f01062008-11-10 04:46:22 +00003743
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003744 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3745 // Old form of ICmp/FCmp returning bool
3746 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3747 // both legal on vectors but had different behaviour.
3748 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3749 // FCmp/ICmp returning bool or vector of bool
3750
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003751 unsigned OpNum = 0;
3752 Value *LHS, *RHS;
3753 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
James Molloy88eb5352015-07-10 12:52:00 +00003754 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3755 return error("Invalid record");
3756
3757 unsigned PredVal = Record[OpNum];
3758 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3759 FastMathFlags FMF;
3760 if (IsFP && Record.size() > OpNum+1)
3761 FMF = getDecodedFastMathFlags(Record[++OpNum]);
3762
3763 if (OpNum+1 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003764 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003765
Duncan Sands9dff9be2010-02-15 16:12:20 +00003766 if (LHS->getType()->isFPOrFPVectorTy())
James Molloy88eb5352015-07-10 12:52:00 +00003767 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003768 else
James Molloy88eb5352015-07-10 12:52:00 +00003769 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3770
3771 if (FMF.any())
3772 I->setFastMathFlags(FMF);
Devang Patelaf206b82009-09-18 19:26:43 +00003773 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00003774 break;
3775 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003776
Chris Lattnere53603e2007-05-02 04:27:25 +00003777 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00003778 {
3779 unsigned Size = Record.size();
3780 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00003781 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003782 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00003783 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003784 }
Devang Patelbbfd8742008-02-26 01:29:32 +00003785
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003786 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00003787 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00003788 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003789 return error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00003790 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003791 return error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003792
Chris Lattnerf1c87102011-06-17 18:09:11 +00003793 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003794 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003795 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00003796 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003797 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00003798 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003799 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003800 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003801 if (!TrueDest)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003802 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003803
Devang Patelaf206b82009-09-18 19:26:43 +00003804 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00003805 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003806 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00003807 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003808 else {
3809 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003810 Value *Cond = getValue(Record, 2, NextValueNo,
3811 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00003812 if (!FalseDest || !Cond)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003813 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00003814 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003815 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003816 }
3817 break;
3818 }
David Majnemer654e1302015-07-31 17:58:14 +00003819 // CLEANUPRET: [] or [ty,val] or [bb#] or [ty,val,bb#]
3820 case bitc::FUNC_CODE_INST_CLEANUPRET: {
3821 if (Record.size() < 2)
3822 return error("Invalid record");
3823 unsigned Idx = 0;
3824 bool HasReturnValue = !!Record[Idx++];
3825 bool HasUnwindDest = !!Record[Idx++];
3826 Value *RetVal = nullptr;
3827 BasicBlock *UnwindDest = nullptr;
3828
3829 if (HasReturnValue && getValueTypePair(Record, Idx, NextValueNo, RetVal))
3830 return error("Invalid record");
3831 if (HasUnwindDest) {
3832 if (Idx == Record.size())
3833 return error("Invalid record");
3834 UnwindDest = getBasicBlock(Record[Idx++]);
3835 if (!UnwindDest)
3836 return error("Invalid record");
3837 }
3838
3839 if (Record.size() != Idx)
3840 return error("Invalid record");
3841
3842 I = CleanupReturnInst::Create(Context, RetVal, UnwindDest);
3843 InstructionList.push_back(I);
3844 break;
3845 }
3846 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [bb#]
3847 if (Record.size() != 1)
3848 return error("Invalid record");
3849 BasicBlock *BB = getBasicBlock(Record[0]);
3850 if (!BB)
3851 return error("Invalid record");
3852 I = CatchReturnInst::Create(BB);
3853 InstructionList.push_back(I);
3854 break;
3855 }
3856 case bitc::FUNC_CODE_INST_CATCHPAD: { // CATCHPAD: [ty,bb#,bb#,num,(ty,val)*]
3857 if (Record.size() < 4)
3858 return error("Invalid record");
3859 unsigned Idx = 0;
3860 Type *Ty = getTypeByID(Record[Idx++]);
3861 if (!Ty)
3862 return error("Invalid record");
3863 BasicBlock *NormalBB = getBasicBlock(Record[Idx++]);
3864 if (!NormalBB)
3865 return error("Invalid record");
3866 BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]);
3867 if (!UnwindBB)
3868 return error("Invalid record");
3869 unsigned NumArgOperands = Record[Idx++];
3870 SmallVector<Value *, 2> Args;
3871 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3872 Value *Val;
3873 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3874 return error("Invalid record");
3875 Args.push_back(Val);
3876 }
3877 if (Record.size() != Idx)
3878 return error("Invalid record");
3879
3880 I = CatchPadInst::Create(Ty, NormalBB, UnwindBB, Args);
3881 InstructionList.push_back(I);
3882 break;
3883 }
3884 case bitc::FUNC_CODE_INST_TERMINATEPAD: { // TERMINATEPAD: [bb#,num,(ty,val)*]
3885 if (Record.size() < 1)
3886 return error("Invalid record");
3887 unsigned Idx = 0;
3888 bool HasUnwindDest = !!Record[Idx++];
3889 BasicBlock *UnwindDest = nullptr;
3890 if (HasUnwindDest) {
3891 if (Idx == Record.size())
3892 return error("Invalid record");
3893 UnwindDest = getBasicBlock(Record[Idx++]);
3894 if (!UnwindDest)
3895 return error("Invalid record");
3896 }
3897 unsigned NumArgOperands = Record[Idx++];
3898 SmallVector<Value *, 2> Args;
3899 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3900 Value *Val;
3901 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3902 return error("Invalid record");
3903 Args.push_back(Val);
3904 }
3905 if (Record.size() != Idx)
3906 return error("Invalid record");
3907
3908 I = TerminatePadInst::Create(Context, UnwindDest, Args);
3909 InstructionList.push_back(I);
3910 break;
3911 }
3912 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // CLEANUPPAD: [ty, num,(ty,val)*]
3913 if (Record.size() < 2)
3914 return error("Invalid record");
3915 unsigned Idx = 0;
3916 Type *Ty = getTypeByID(Record[Idx++]);
3917 if (!Ty)
3918 return error("Invalid record");
3919 unsigned NumArgOperands = Record[Idx++];
3920 SmallVector<Value *, 2> Args;
3921 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3922 Value *Val;
3923 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3924 return error("Invalid record");
3925 Args.push_back(Val);
3926 }
3927 if (Record.size() != Idx)
3928 return error("Invalid record");
3929
3930 I = CleanupPadInst::Create(Ty, Args);
3931 InstructionList.push_back(I);
3932 break;
3933 }
3934 case bitc::FUNC_CODE_INST_CATCHENDPAD: { // CATCHENDPADINST: [bb#] or []
3935 if (Record.size() > 1)
3936 return error("Invalid record");
3937 BasicBlock *BB = nullptr;
3938 if (Record.size() == 1) {
3939 BB = getBasicBlock(Record[0]);
3940 if (!BB)
3941 return error("Invalid record");
3942 }
3943 I = CatchEndPadInst::Create(Context, BB);
3944 InstructionList.push_back(I);
3945 break;
3946 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00003947 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003948 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003949 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00003950 // "New" SwitchInst format with case ranges. The changes to write this
3951 // format were reverted but we still recognize bitcode that uses it.
3952 // Hopefully someday we will have support for case ranges and can use
3953 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003954
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003955 Type *OpTy = getTypeByID(Record[1]);
3956 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3957
Jan Wen Voungafaced02012-10-11 20:20:40 +00003958 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003959 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003960 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003961 return error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003962
3963 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003964
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003965 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3966 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003967
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003968 unsigned CurIdx = 5;
3969 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00003970 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003971 unsigned NumItems = Record[CurIdx++];
3972 for (unsigned ci = 0; ci != NumItems; ++ci) {
3973 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003974
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003975 APInt Low;
3976 unsigned ActiveWords = 1;
3977 if (ValueBitWidth > 64)
3978 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003979 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
Benjamin Kramer9704ed02012-05-28 14:10:31 +00003980 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003981 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00003982
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003983 if (!isSingleNumber) {
3984 ActiveWords = 1;
3985 if (ValueBitWidth > 64)
3986 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003987 APInt High = readWideAPInt(
3988 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003989 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00003990
3991 // FIXME: It is not clear whether values in the range should be
3992 // compared as signed or unsigned values. The partially
3993 // implemented changes that used this format in the past used
3994 // unsigned comparisons.
3995 for ( ; Low.ule(High); ++Low)
3996 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003997 } else
Bob Wilsone4077362013-09-09 19:14:35 +00003998 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003999 }
4000 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00004001 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4002 cve = CaseVals.end(); cvi != cve; ++cvi)
4003 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004004 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004005 I = SI;
4006 break;
4007 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004008
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004009 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004010
Chris Lattner5285b5e2007-05-02 05:46:45 +00004011 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004012 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004013 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004014 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004015 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004016 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004017 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004018 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00004019 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00004020 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004021 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004022 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00004023 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4024 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004025 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00004026 delete SI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004027 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004028 }
4029 SI->addCase(CaseVal, DestBB);
4030 }
4031 I = SI;
4032 break;
4033 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004034 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00004035 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004036 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004037 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004038 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00004039 if (!OpTy || !Address)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004040 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004041 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004042 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00004043 InstructionList.push_back(IBI);
4044 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4045 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4046 IBI->addDestination(DestBB);
4047 } else {
4048 delete IBI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004049 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004050 }
4051 }
4052 I = IBI;
4053 break;
4054 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004055
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004056 case bitc::FUNC_CODE_INST_INVOKE: {
4057 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00004058 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004059 return error("Invalid record");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004060 unsigned OpNum = 0;
4061 AttributeSet PAL = getAttributes(Record[OpNum++]);
4062 unsigned CCInfo = Record[OpNum++];
4063 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4064 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004065
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004066 FunctionType *FTy = nullptr;
4067 if (CCInfo >> 13 & 1 &&
4068 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004069 return error("Explicit invoke type is not a function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004070
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004071 Value *Callee;
4072 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004073 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004074
Chris Lattner229907c2011-07-18 04:54:35 +00004075 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004076 if (!CalleeTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004077 return error("Callee is not a pointer");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004078 if (!FTy) {
4079 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4080 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004081 return error("Callee is not of pointer to function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004082 } else if (CalleeTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004083 return error("Explicit invoke type does not match pointee type of "
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004084 "callee operand");
4085 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004086 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004087
Chris Lattner5285b5e2007-05-02 05:46:45 +00004088 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004089 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004090 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4091 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004092 if (!Ops.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004093 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004094 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004095
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004096 if (!FTy->isVarArg()) {
4097 if (Record.size() != OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004098 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004099 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004100 // Read type/value pairs for varargs params.
4101 while (OpNum != Record.size()) {
4102 Value *Op;
4103 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004104 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004105 Ops.push_back(Op);
4106 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004107 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004108
Jay Foad5bd375a2011-07-15 08:37:34 +00004109 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patelaf206b82009-09-18 19:26:43 +00004110 InstructionList.push_back(I);
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004111 cast<InvokeInst>(I)
4112 ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00004113 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004114 break;
4115 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00004116 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4117 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004118 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004119 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004120 return error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00004121 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00004122 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004123 break;
4124 }
Chris Lattnere53603e2007-05-02 04:27:25 +00004125 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00004126 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00004127 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004128 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00004129 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00004130 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004131 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004132 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004133 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004134 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004135
Jay Foad52131342011-03-30 11:28:46 +00004136 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00004137 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004138
Chris Lattnere14cb882007-05-04 19:11:41 +00004139 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004140 Value *V;
4141 // With the new function encoding, it is possible that operands have
4142 // negative IDs (for forward references). Use a signed VBR
4143 // representation to keep the encoding small.
4144 if (UseRelativeIDs)
4145 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4146 else
4147 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00004148 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004149 if (!V || !BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004150 return error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00004151 PN->addIncoming(V, BB);
4152 }
4153 I = PN;
4154 break;
4155 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004156
David Majnemer7fddecc2015-06-17 20:52:32 +00004157 case bitc::FUNC_CODE_INST_LANDINGPAD:
4158 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
Bill Wendlingfae14752011-08-12 20:24:12 +00004159 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4160 unsigned Idx = 0;
David Majnemer7fddecc2015-06-17 20:52:32 +00004161 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4162 if (Record.size() < 3)
4163 return error("Invalid record");
4164 } else {
4165 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4166 if (Record.size() < 4)
4167 return error("Invalid record");
4168 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004169 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004170 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004171 return error("Invalid record");
David Majnemer7fddecc2015-06-17 20:52:32 +00004172 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4173 Value *PersFn = nullptr;
4174 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4175 return error("Invalid record");
4176
4177 if (!F->hasPersonalityFn())
4178 F->setPersonalityFn(cast<Constant>(PersFn));
4179 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4180 return error("Personality function mismatch");
4181 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004182
4183 bool IsCleanup = !!Record[Idx++];
4184 unsigned NumClauses = Record[Idx++];
David Majnemer7fddecc2015-06-17 20:52:32 +00004185 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
Bill Wendlingfae14752011-08-12 20:24:12 +00004186 LP->setCleanup(IsCleanup);
4187 for (unsigned J = 0; J != NumClauses; ++J) {
4188 LandingPadInst::ClauseType CT =
4189 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4190 Value *Val;
4191
4192 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4193 delete LP;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004194 return error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00004195 }
4196
4197 assert((CT != LandingPadInst::Catch ||
4198 !isa<ArrayType>(Val->getType())) &&
4199 "Catch clause has a invalid type!");
4200 assert((CT != LandingPadInst::Filter ||
4201 isa<ArrayType>(Val->getType())) &&
4202 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004203 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00004204 }
4205
4206 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00004207 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00004208 break;
4209 }
4210
Chris Lattnerf1c87102011-06-17 18:09:11 +00004211 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4212 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004213 return error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00004214 uint64_t AlignRecord = Record[3];
4215 const uint64_t InAllocaMask = uint64_t(1) << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00004216 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
Bob Wilson043ee652015-07-28 04:05:45 +00004217 // Reserve bit 7 for SwiftError flag.
4218 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
David Blaikiebdb49102015-04-28 16:51:01 +00004219 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
JF Bastien30bf96b2015-02-22 19:32:03 +00004220 bool InAlloca = AlignRecord & InAllocaMask;
David Blaikiebdb49102015-04-28 16:51:01 +00004221 Type *Ty = getTypeByID(Record[0]);
4222 if ((AlignRecord & ExplicitTypeMask) == 0) {
4223 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4224 if (!PTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004225 return error("Old-style alloca with a non-pointer type");
David Blaikiebdb49102015-04-28 16:51:01 +00004226 Ty = PTy->getElementType();
4227 }
4228 Type *OpTy = getTypeByID(Record[1]);
4229 Value *Size = getFnValueByID(Record[2], OpTy);
JF Bastien30bf96b2015-02-22 19:32:03 +00004230 unsigned Align;
4231 if (std::error_code EC =
David Blaikiebdb49102015-04-28 16:51:01 +00004232 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
JF Bastien30bf96b2015-02-22 19:32:03 +00004233 return EC;
4234 }
Rafael Espindola48da4f42013-11-04 16:16:24 +00004235 if (!Ty || !Size)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004236 return error("Invalid record");
David Blaikiebdb49102015-04-28 16:51:01 +00004237 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00004238 AI->setUsedWithInAlloca(InAlloca);
4239 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00004240 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00004241 break;
4242 }
Chris Lattner9f600c52007-05-03 22:04:19 +00004243 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004244 unsigned OpNum = 0;
4245 Value *Op;
4246 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004247 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004248 return error("Invalid record");
David Blaikie85035652015-02-25 01:07:20 +00004249
4250 Type *Ty = nullptr;
4251 if (OpNum + 3 == Record.size())
4252 Ty = getTypeByID(Record[OpNum++]);
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004253 if (std::error_code EC =
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004254 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004255 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00004256 if (!Ty)
4257 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004258
JF Bastien30bf96b2015-02-22 19:32:03 +00004259 unsigned Align;
4260 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4261 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00004262 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
David Blaikie85035652015-02-25 01:07:20 +00004263
Devang Patelaf206b82009-09-18 19:26:43 +00004264 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00004265 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00004266 }
Eli Friedman59b66882011-08-09 23:02:53 +00004267 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4268 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4269 unsigned OpNum = 0;
4270 Value *Op;
4271 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004272 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004273 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004274
David Blaikie85035652015-02-25 01:07:20 +00004275 Type *Ty = nullptr;
4276 if (OpNum + 5 == Record.size())
4277 Ty = getTypeByID(Record[OpNum++]);
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004278 if (std::error_code EC =
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004279 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004280 return EC;
4281 if (!Ty)
4282 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004283
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004284 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman59b66882011-08-09 23:02:53 +00004285 if (Ordering == NotAtomic || Ordering == Release ||
4286 Ordering == AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004287 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004288 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004289 return error("Invalid record");
4290 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00004291
JF Bastien30bf96b2015-02-22 19:32:03 +00004292 unsigned Align;
4293 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4294 return EC;
4295 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
David Blaikie85035652015-02-25 01:07:20 +00004296
Eli Friedman59b66882011-08-09 23:02:53 +00004297 InstructionList.push_back(I);
4298 break;
4299 }
David Blaikie612ddbf2015-04-22 04:14:42 +00004300 case bitc::FUNC_CODE_INST_STORE:
4301 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004302 unsigned OpNum = 0;
4303 Value *Val, *Ptr;
4304 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie612ddbf2015-04-22 04:14:42 +00004305 (BitCode == bitc::FUNC_CODE_INST_STORE
4306 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4307 : popValue(Record, OpNum, NextValueNo,
4308 cast<PointerType>(Ptr->getType())->getElementType(),
4309 Val)) ||
4310 OpNum + 2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004311 return error("Invalid record");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004312
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004313 if (std::error_code EC = typeCheckLoadStoreInst(
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004314 DiagnosticHandler, Val->getType(), Ptr->getType()))
4315 return EC;
JF Bastien30bf96b2015-02-22 19:32:03 +00004316 unsigned Align;
4317 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4318 return EC;
4319 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
Devang Patelaf206b82009-09-18 19:26:43 +00004320 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004321 break;
4322 }
David Blaikie50a06152015-04-22 04:14:46 +00004323 case bitc::FUNC_CODE_INST_STOREATOMIC:
4324 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
Eli Friedman59b66882011-08-09 23:02:53 +00004325 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4326 unsigned OpNum = 0;
4327 Value *Val, *Ptr;
4328 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie50a06152015-04-22 04:14:46 +00004329 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4330 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4331 : popValue(Record, OpNum, NextValueNo,
4332 cast<PointerType>(Ptr->getType())->getElementType(),
4333 Val)) ||
4334 OpNum + 4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004335 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004336
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004337 if (std::error_code EC = typeCheckLoadStoreInst(
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004338 DiagnosticHandler, Val->getType(), Ptr->getType()))
4339 return EC;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004340 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman222b5a42011-09-19 19:41:28 +00004341 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman59b66882011-08-09 23:02:53 +00004342 Ordering == AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004343 return error("Invalid record");
4344 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00004345 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004346 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004347
JF Bastien30bf96b2015-02-22 19:32:03 +00004348 unsigned Align;
4349 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4350 return EC;
4351 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
Eli Friedman59b66882011-08-09 23:02:53 +00004352 InstructionList.push_back(I);
4353 break;
4354 }
David Blaikie2a661cd2015-04-28 04:30:29 +00004355 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004356 case bitc::FUNC_CODE_INST_CMPXCHG: {
Tim Northovere94a5182014-03-11 10:48:52 +00004357 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
Tim Northover420a2162014-06-13 14:24:07 +00004358 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004359 unsigned OpNum = 0;
4360 Value *Ptr, *Cmp, *New;
4361 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie2a661cd2015-04-28 04:30:29 +00004362 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4363 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4364 : popValue(Record, OpNum, NextValueNo,
4365 cast<PointerType>(Ptr->getType())->getElementType(),
4366 Cmp)) ||
4367 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4368 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004369 return error("Invalid record");
4370 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
Tim Northovere94a5182014-03-11 10:48:52 +00004371 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004372 return error("Invalid record");
4373 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
Tim Northovere94a5182014-03-11 10:48:52 +00004374
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004375 if (std::error_code EC = typeCheckLoadStoreInst(
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004376 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4377 return EC;
Tim Northovere94a5182014-03-11 10:48:52 +00004378 AtomicOrdering FailureOrdering;
4379 if (Record.size() < 7)
4380 FailureOrdering =
4381 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4382 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004383 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
Tim Northovere94a5182014-03-11 10:48:52 +00004384
4385 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4386 SynchScope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004387 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00004388
4389 if (Record.size() < 8) {
4390 // Before weak cmpxchgs existed, the instruction simply returned the
4391 // value loaded from memory, so bitcode files from that era will be
4392 // expecting the first component of a modern cmpxchg.
4393 CurBB->getInstList().push_back(I);
4394 I = ExtractValueInst::Create(I, 0);
4395 } else {
4396 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4397 }
4398
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004399 InstructionList.push_back(I);
4400 break;
4401 }
4402 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4403 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4404 unsigned OpNum = 0;
4405 Value *Ptr, *Val;
4406 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004407 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004408 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4409 OpNum+4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004410 return error("Invalid record");
4411 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004412 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4413 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004414 return error("Invalid record");
4415 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman59b66882011-08-09 23:02:53 +00004416 if (Ordering == NotAtomic || Ordering == Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004417 return error("Invalid record");
4418 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004419 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4420 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4421 InstructionList.push_back(I);
4422 break;
4423 }
Eli Friedmanfee02c62011-07-25 23:16:38 +00004424 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4425 if (2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004426 return error("Invalid record");
4427 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004428 if (Ordering == NotAtomic || Ordering == Unordered ||
4429 Ordering == Monotonic)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004430 return error("Invalid record");
4431 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004432 I = new FenceInst(Context, Ordering, SynchScope);
4433 InstructionList.push_back(I);
4434 break;
4435 }
Chris Lattnerc44070802011-06-17 18:17:37 +00004436 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004437 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4438 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004439 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004440
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004441 unsigned OpNum = 0;
4442 AttributeSet PAL = getAttributes(Record[OpNum++]);
4443 unsigned CCInfo = Record[OpNum++];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004444
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004445 FunctionType *FTy = nullptr;
4446 if (CCInfo >> 15 & 1 &&
4447 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004448 return error("Explicit call type is not a function type");
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004449
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004450 Value *Callee;
4451 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004452 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004453
Chris Lattner229907c2011-07-18 04:54:35 +00004454 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004455 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004456 return error("Callee is not a pointer type");
David Blaikie348de692015-04-23 21:36:23 +00004457 if (!FTy) {
4458 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4459 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004460 return error("Callee is not of pointer to function type");
David Blaikie348de692015-04-23 21:36:23 +00004461 } else if (OpTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004462 return error("Explicit call type does not match pointee type of "
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004463 "callee operand");
4464 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004465 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004466
Chris Lattner9f600c52007-05-03 22:04:19 +00004467 SmallVector<Value*, 16> Args;
4468 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004469 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004470 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00004471 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00004472 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00004473 Args.push_back(getValue(Record, OpNum, NextValueNo,
4474 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004475 if (!Args.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004476 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004477 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004478
Chris Lattner9f600c52007-05-03 22:04:19 +00004479 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00004480 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004481 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004482 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004483 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004484 while (OpNum != Record.size()) {
4485 Value *Op;
4486 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004487 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004488 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00004489 }
4490 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004491
David Blaikie348de692015-04-23 21:36:23 +00004492 I = CallInst::Create(FTy, Callee, Args);
Devang Patelaf206b82009-09-18 19:26:43 +00004493 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00004494 cast<CallInst>(I)->setCallingConv(
Reid Kleckner5772b772014-04-24 20:14:34 +00004495 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4496 CallInst::TailCallKind TCK = CallInst::TCK_None;
4497 if (CCInfo & 1)
4498 TCK = CallInst::TCK_Tail;
4499 if (CCInfo & (1 << 14))
4500 TCK = CallInst::TCK_MustTail;
4501 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00004502 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner9f600c52007-05-03 22:04:19 +00004503 break;
4504 }
4505 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4506 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004507 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004508 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004509 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00004510 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00004511 if (!OpTy || !Op || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004512 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004513 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00004514 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00004515 break;
4516 }
Chris Lattner83930552007-05-01 07:01:57 +00004517 }
4518
4519 // Add instruction to end of current BB. If there is no current BB, reject
4520 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00004521 if (!CurBB) {
Chris Lattner83930552007-05-01 07:01:57 +00004522 delete I;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004523 return error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00004524 }
4525 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004526
Chris Lattner83930552007-05-01 07:01:57 +00004527 // If this was a terminator instruction, move to the next block.
4528 if (isa<TerminatorInst>(I)) {
4529 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00004530 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00004531 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004532
Chris Lattner83930552007-05-01 07:01:57 +00004533 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00004534 if (I && !I->getType()->isVoidTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004535 ValueList.assignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00004536 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004537
Chris Lattner27d38752013-01-20 02:13:19 +00004538OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00004539
Chris Lattner83930552007-05-01 07:01:57 +00004540 // Check the function list for unresolved values.
4541 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004542 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00004543 // We found at least one unresolved value. Nuke them all to avoid leaks.
4544 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00004545 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00004546 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00004547 delete A;
4548 }
4549 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004550 return error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00004551 }
Chris Lattner83930552007-05-01 07:01:57 +00004552 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004553
Dan Gohman9b9ff462010-08-25 20:23:38 +00004554 // FIXME: Check for unresolved forward-declared metadata references
4555 // and clean up leaks.
4556
Chris Lattner85b7b402007-05-01 05:52:21 +00004557 // Trim the value list down to the size it was before we parsed this function.
4558 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman26d837d2010-08-25 20:22:53 +00004559 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00004560 std::vector<BasicBlock*>().swap(FunctionBBs);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004561 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004562}
4563
Rafael Espindola7d712032013-11-05 17:16:08 +00004564/// Find the function body in the bitcode stream
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004565std::error_code BitcodeReader::findFunctionInStream(
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004566 Function *F,
4567 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004568 while (DeferredFunctionInfoIterator->second == 0) {
4569 if (Stream.AtEndOfStream())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004570 return error("Could not find function in stream");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004571 // ParseModule will parse the next body in the stream and set its
4572 // position in the DeferredFunctionInfo map.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004573 if (std::error_code EC = parseModule(true))
Rafael Espindola7d712032013-11-05 17:16:08 +00004574 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004575 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004576 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004577}
4578
Chris Lattner9eeada92007-05-18 04:02:46 +00004579//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004580// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00004581//===----------------------------------------------------------------------===//
4582
Rafael Espindolac3f9b5a2014-06-23 21:53:12 +00004583void BitcodeReader::releaseBuffer() { Buffer.release(); }
Chris Lattner9eeada92007-05-18 04:02:46 +00004584
Rafael Espindola5a52e6d2014-10-24 22:50:48 +00004585std::error_code BitcodeReader::materialize(GlobalValue *GV) {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004586 if (std::error_code EC = materializeMetadata())
4587 return EC;
4588
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004589 Function *F = dyn_cast<Function>(GV);
4590 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004591 if (!F || !F->isMaterializable())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004592 return std::error_code();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004593
4594 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00004595 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004596 // If its position is recorded as 0, its body is somewhere in the stream
4597 // but we haven't seen it yet.
Rafael Espindola1c863ca2015-06-22 18:06:15 +00004598 if (DFII->second == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004599 if (std::error_code EC = findFunctionInStream(F, DFII))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004600 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004601
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004602 // Move the bit stream to the saved position of the deferred function body.
4603 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004604
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004605 if (std::error_code EC = parseFunctionBody(F))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004606 return EC;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00004607 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00004608
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00004609 if (StripDebugInfo)
4610 stripDebugInfo(*F);
4611
Chandler Carruth7132e002007-08-04 01:51:18 +00004612 // Upgrade any old intrinsic calls in the function.
Rafael Espindola86e33402015-07-02 15:55:09 +00004613 for (auto &I : UpgradedIntrinsics) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004614 for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
4615 User *U = *UI;
4616 ++UI;
4617 if (CallInst *CI = dyn_cast<CallInst>(U))
4618 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00004619 }
4620 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004621
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004622 // Bring in any functions that this function forward-referenced via
4623 // blockaddresses.
4624 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00004625}
4626
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004627bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4628 const Function *F = dyn_cast<Function>(GV);
4629 if (!F || F->isDeclaration())
4630 return false;
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004631
4632 // Dematerializing F would leave dangling references that wouldn't be
4633 // reconnected on re-materialization.
4634 if (BlockAddressesTaken.count(F))
4635 return false;
4636
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004637 return DeferredFunctionInfo.count(const_cast<Function*>(F));
4638}
4639
Eric Christopher97cb5652015-05-15 18:20:14 +00004640void BitcodeReader::dematerialize(GlobalValue *GV) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004641 Function *F = dyn_cast<Function>(GV);
4642 // If this function isn't dematerializable, this is a noop.
4643 if (!F || !isDematerializable(F))
Chris Lattner9eeada92007-05-18 04:02:46 +00004644 return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004645
Chris Lattner9eeada92007-05-18 04:02:46 +00004646 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004647
Chris Lattner9eeada92007-05-18 04:02:46 +00004648 // Just forget the function body, we can remat it later.
Petar Jovanovic7480e4d2014-09-23 12:54:19 +00004649 F->dropAllReferences();
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00004650 F->setIsMaterializable(true);
Chris Lattner9eeada92007-05-18 04:02:46 +00004651}
4652
Eric Christopher97cb5652015-05-15 18:20:14 +00004653std::error_code BitcodeReader::materializeModule(Module *M) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004654 assert(M == TheModule &&
4655 "Can only Materialize the Module this BitcodeReader is attached to.");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004656
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004657 if (std::error_code EC = materializeMetadata())
4658 return EC;
4659
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004660 // Promise to materialize all forward references.
4661 WillMaterializeAllForwardRefs = true;
4662
Chris Lattner06310bf2009-06-16 05:15:21 +00004663 // Iterate over the module, deserializing any functions that are still on
4664 // disk.
4665 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004666 F != E; ++F) {
Rafael Espindola246c4fb2014-11-01 16:46:18 +00004667 if (std::error_code EC = materialize(F))
4668 return EC;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004669 }
Derek Schuff92ef9752012-02-29 00:07:09 +00004670 // At this point, if there are any function bodies, the current bit is
4671 // pointing to the END_BLOCK record after them. Now make sure the rest
4672 // of the bits in the module have been read.
4673 if (NextUnreadBit)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004674 parseModule(true);
Derek Schuff92ef9752012-02-29 00:07:09 +00004675
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004676 // Check that all block address forward references got resolved (as we
4677 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004678 if (!BasicBlockFwdRefs.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004679 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004680
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004681 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4682 // delete the old functions to clean up. We can't do this unless the entire
4683 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00004684 // with calls to the old function.
Rafael Espindola86e33402015-07-02 15:55:09 +00004685 for (auto &I : UpgradedIntrinsics) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004686 for (auto *U : I.first->users()) {
4687 if (CallInst *CI = dyn_cast<CallInst>(U))
4688 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00004689 }
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004690 if (!I.first->use_empty())
4691 I.first->replaceAllUsesWith(I.second);
4692 I.first->eraseFromParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00004693 }
Rafael Espindola4e721212015-07-02 16:22:40 +00004694 UpgradedIntrinsics.clear();
Devang Patel80ae3492009-08-28 23:24:31 +00004695
Manman Ren209b17c2013-09-28 00:22:27 +00004696 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4697 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4698
Manman Ren8b4306c2013-12-02 21:29:56 +00004699 UpgradeDebugInfo(*M);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004700 return std::error_code();
Chris Lattner9eeada92007-05-18 04:02:46 +00004701}
4702
Rafael Espindola2fa1e432014-12-03 07:18:23 +00004703std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4704 return IdentifiedStructTypes;
4705}
4706
Rafael Espindola1aabf982015-06-16 23:29:49 +00004707std::error_code
4708BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
Rafael Espindola4223a1f2015-06-15 20:08:17 +00004709 if (Streamer)
Rafael Espindola1aabf982015-06-16 23:29:49 +00004710 return initLazyStream(std::move(Streamer));
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004711 return initStreamFromBuffer();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004712}
4713
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004714std::error_code BitcodeReader::initStreamFromBuffer() {
Roman Divacky4717a8d2012-09-06 15:42:13 +00004715 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004716 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4717
Rafael Espindola27435252014-07-29 21:01:24 +00004718 if (Buffer->getBufferSize() & 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004719 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004720
4721 // If we have a wrapper header, parse it and ignore the non-bc file contents.
4722 // The magic number is 0x0B17C0DE stored in little endian.
4723 if (isBitcodeWrapper(BufPtr, BufEnd))
4724 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004725 return error("Invalid bitcode wrapper header");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004726
4727 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00004728 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004729
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004730 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004731}
4732
Rafael Espindola1aabf982015-06-16 23:29:49 +00004733std::error_code
4734BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004735 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4736 // see it.
Rafael Espindola1aabf982015-06-16 23:29:49 +00004737 auto OwnedBytes =
4738 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
Rafael Espindola7d727b52014-12-18 05:08:43 +00004739 StreamingMemoryObject &Bytes = *OwnedBytes;
Yaron Keren06d69302014-12-18 10:03:35 +00004740 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00004741 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004742
4743 unsigned char buf[16];
Rafael Espindola7d727b52014-12-18 05:08:43 +00004744 if (Bytes.readBytes(buf, 16, 0) != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004745 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004746
4747 if (!isBitcode(buf, buf + 16))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004748 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004749
4750 if (isBitcodeWrapper(buf, buf + 4)) {
4751 const unsigned char *bitcodeStart = buf;
4752 const unsigned char *bitcodeEnd = buf + 16;
4753 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
Rafael Espindola7d727b52014-12-18 05:08:43 +00004754 Bytes.dropLeadingBytes(bitcodeStart - buf);
4755 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004756 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004757 return std::error_code();
Rafael Espindola48da4f42013-11-04 16:16:24 +00004758}
4759
4760namespace {
Rafael Espindola25188c92014-06-12 01:45:43 +00004761class BitcodeErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +00004762 const char *name() const LLVM_NOEXCEPT override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00004763 return "llvm.bitcode";
4764 }
Craig Topper73156022014-03-02 09:09:27 +00004765 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00004766 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004767 switch (E) {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00004768 case BitcodeError::InvalidBitcodeSignature:
Rafael Espindola48da4f42013-11-04 16:16:24 +00004769 return "Invalid bitcode signature";
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004770 case BitcodeError::CorruptedBitcode:
4771 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00004772 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00004773 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00004774 }
4775};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00004776}
Rafael Espindola48da4f42013-11-04 16:16:24 +00004777
Chris Bieneman770163e2014-09-19 20:29:02 +00004778static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4779
Rafael Espindolac3f2e732014-07-29 20:22:46 +00004780const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00004781 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004782}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004783
Chris Lattner6694f602007-04-29 07:54:31 +00004784//===----------------------------------------------------------------------===//
4785// External interface
4786//===----------------------------------------------------------------------===//
4787
Rafael Espindola456baad2015-06-17 01:15:47 +00004788static ErrorOr<std::unique_ptr<Module>>
4789getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
4790 BitcodeReader *R, LLVMContext &Context,
4791 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
4792 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4793 M->setMaterializer(R);
4794
4795 auto cleanupOnError = [&](std::error_code EC) {
4796 R->releaseBuffer(); // Never take ownership on error.
4797 return EC;
4798 };
4799
4800 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
4801 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
4802 ShouldLazyLoadMetadata))
4803 return cleanupOnError(EC);
4804
4805 if (MaterializeAll) {
4806 // Read in the entire module, and destroy the BitcodeReader.
4807 if (std::error_code EC = M->materializeAllPermanently())
4808 return cleanupOnError(EC);
4809 } else {
4810 // Resolve forward references from blockaddresses.
4811 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4812 return cleanupOnError(EC);
4813 }
4814 return std::move(M);
4815}
4816
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00004817/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00004818///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00004819/// This isn't always used in a lazy context. In particular, it's also used by
4820/// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
4821/// in forward-referenced functions from block address references.
4822///
Rafael Espindola728074b2015-06-17 00:40:56 +00004823/// \param[in] MaterializeAll Set to \c true if we should materialize
4824/// everything.
Rafael Espindoladcd1dca2015-06-16 22:27:55 +00004825static ErrorOr<std::unique_ptr<Module>>
Rafael Espindola68812152014-09-03 17:31:46 +00004826getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindola728074b2015-06-17 00:40:56 +00004827 LLVMContext &Context, bool MaterializeAll,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004828 DiagnosticHandlerFunction DiagnosticHandler,
4829 bool ShouldLazyLoadMetadata = false) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004830 BitcodeReader *R =
4831 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004832
Rafael Espindola456baad2015-06-17 01:15:47 +00004833 ErrorOr<std::unique_ptr<Module>> Ret =
4834 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
4835 MaterializeAll, ShouldLazyLoadMetadata);
4836 if (!Ret)
4837 return Ret;
Rafael Espindolab7993462012-01-02 07:49:53 +00004838
Rafael Espindolae2c1d772014-08-26 22:00:09 +00004839 Buffer.release(); // The BitcodeReader owns it now.
Rafael Espindola456baad2015-06-17 01:15:47 +00004840 return Ret;
Chris Lattner6694f602007-04-29 07:54:31 +00004841}
4842
Rafael Espindoladcd1dca2015-06-16 22:27:55 +00004843ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
4844 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
4845 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004846 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004847 DiagnosticHandler, ShouldLazyLoadMetadata);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00004848}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004849
Rafael Espindola1aabf982015-06-16 23:29:49 +00004850ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
4851 StringRef Name, std::unique_ptr<DataStreamer> Streamer,
4852 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindola7d727b52014-12-18 05:08:43 +00004853 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
Rafael Espindola1aabf982015-06-16 23:29:49 +00004854 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
Rafael Espindola456baad2015-06-17 01:15:47 +00004855
4856 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
4857 false);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004858}
4859
Rafael Espindoladcd1dca2015-06-16 22:27:55 +00004860ErrorOr<std::unique_ptr<Module>>
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004861llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4862 DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00004863 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola728074b2015-06-17 00:40:56 +00004864 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
4865 DiagnosticHandler);
Chad Rosierca2567b2011-12-07 21:44:12 +00004866 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4867 // written. We must defer until the Module has been fully materialized.
Chris Lattner6694f602007-04-29 07:54:31 +00004868}
Bill Wendling0198ce02010-10-06 01:22:42 +00004869
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004870std::string
4871llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4872 DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00004873 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004874 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4875 DiagnosticHandler);
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004876 ErrorOr<std::string> Triple = R->parseTriple();
Rafael Espindolad346cc82014-07-04 13:52:01 +00004877 if (Triple.getError())
4878 return "";
4879 return Triple.get();
Bill Wendling0198ce02010-10-06 01:22:42 +00004880}