blob: 09e3e75f99d7de744ce588a6b39bb2734f4fac4a [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
47 /// ResolveConstants - As we resolve forward-referenced constants, we add
48 /// information about them to this vector. This allows us to resolve them in
49 /// bulk instead of resolving each reference at a time. See the code in
50 /// 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); }
66 void push_back(Value *V) {
67 ValuePtrs.push_back(V);
68 }
69
70 void clear() {
71 assert(ResolveConstants.empty() && "Constants not resolved?");
72 ValuePtrs.clear();
73 }
74
75 Value *operator[](unsigned i) const {
76 assert(i < ValuePtrs.size());
77 return ValuePtrs[i];
78 }
79
80 Value *back() const { return ValuePtrs.back(); }
81 void pop_back() { ValuePtrs.pop_back(); }
82 bool empty() const { return ValuePtrs.empty(); }
83 void shrinkTo(unsigned N) {
84 assert(N <= size() && "Invalid shrinkTo request!");
85 ValuePtrs.resize(N);
86 }
87
88 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
89 Value *getValueFwdRef(unsigned Idx, Type *Ty);
90
91 void AssignValue(Value *V, unsigned Idx);
92
93 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
94 /// resolves any forward references.
95 void ResolveConstantForwardRefs();
96};
97
98class BitcodeReaderMDValueList {
99 unsigned NumFwdRefs;
100 bool AnyFwdRefs;
101 unsigned MinFwdRef;
102 unsigned MaxFwdRef;
103 std::vector<TrackingMDRef> MDValuePtrs;
104
105 LLVMContext &Context;
106public:
107 BitcodeReaderMDValueList(LLVMContext &C)
108 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
109
110 // vector compatibility methods
111 unsigned size() const { return MDValuePtrs.size(); }
112 void resize(unsigned N) { MDValuePtrs.resize(N); }
113 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
114 void clear() { MDValuePtrs.clear(); }
115 Metadata *back() const { return MDValuePtrs.back(); }
116 void pop_back() { MDValuePtrs.pop_back(); }
117 bool empty() const { return MDValuePtrs.empty(); }
118
119 Metadata *operator[](unsigned i) const {
120 assert(i < MDValuePtrs.size());
121 return MDValuePtrs[i];
122 }
123
124 void shrinkTo(unsigned N) {
125 assert(N <= size() && "Invalid shrinkTo request!");
126 MDValuePtrs.resize(N);
127 }
128
129 Metadata *getValueFwdRef(unsigned Idx);
130 void AssignValue(Metadata *MD, unsigned Idx);
131 void tryToResolveCycles();
132};
133
134class BitcodeReader : public GVMaterializer {
135 LLVMContext &Context;
136 DiagnosticHandlerFunction DiagnosticHandler;
137 Module *TheModule;
138 std::unique_ptr<MemoryBuffer> Buffer;
139 std::unique_ptr<BitstreamReader> StreamFile;
140 BitstreamCursor Stream;
141 DataStreamer *LazyStreamer;
142 uint64_t NextUnreadBit;
143 bool SeenValueSymbolTable;
144
145 std::vector<Type*> TypeList;
146 BitcodeReaderValueList ValueList;
147 BitcodeReaderMDValueList MDValueList;
148 std::vector<Comdat *> ComdatList;
149 SmallVector<Instruction *, 64> InstructionList;
150
151 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
152 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
153 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
154 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
155
156 SmallVector<Instruction*, 64> InstsWithTBAATag;
157
158 /// MAttributes - The set of attributes by index. Index zero in the
159 /// file is for null, and is thus not represented here. As such all indices
160 /// are off by one.
161 std::vector<AttributeSet> MAttributes;
162
163 /// \brief The set of attribute groups.
164 std::map<unsigned, AttributeSet> MAttributeGroups;
165
166 /// FunctionBBs - While parsing a function body, this is a list of the basic
167 /// blocks for the function.
168 std::vector<BasicBlock*> FunctionBBs;
169
170 // When reading the module header, this list is populated with functions that
171 // have bodies later in the file.
172 std::vector<Function*> FunctionsWithBodies;
173
174 // When intrinsic functions are encountered which require upgrading they are
175 // stored here with their replacement function.
176 typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
177 UpgradedIntrinsicMap UpgradedIntrinsics;
178
179 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
180 DenseMap<unsigned, unsigned> MDKindMap;
181
182 // Several operations happen after the module header has been read, but
183 // before function bodies are processed. This keeps track of whether
184 // we've done this yet.
185 bool SeenFirstFunctionBody;
186
187 /// DeferredFunctionInfo - When function bodies are initially scanned, this
188 /// map contains info about where to find deferred function body in the
189 /// stream.
190 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
191
192 /// When Metadata block is initially scanned when parsing the module, we may
193 /// choose to defer parsing of the metadata. This vector contains info about
194 /// which Metadata blocks are deferred.
195 std::vector<uint64_t> DeferredMetadataInfo;
196
197 /// These are basic blocks forward-referenced by block addresses. They are
198 /// inserted lazily into functions when they're loaded. The basic block ID is
199 /// its index into the vector.
200 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
201 std::deque<Function *> BasicBlockFwdRefQueue;
202
203 /// UseRelativeIDs - Indicates that we are using a new encoding for
204 /// instruction operands where most operands in the current
205 /// FUNCTION_BLOCK are encoded relative to the instruction number,
206 /// for a more compact encoding. Some instruction operands are not
207 /// relative to the instruction ID: basic block numbers, and types.
208 /// Once the old style function blocks have been phased out, we would
209 /// not need this flag.
210 bool UseRelativeIDs;
211
212 /// True if all functions will be materialized, negating the need to process
213 /// (e.g.) blockaddress forward references.
214 bool WillMaterializeAllForwardRefs;
215
216 /// Functions that have block addresses taken. This is usually empty.
217 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
218
219 /// True if any Metadata block has been materialized.
220 bool IsMetadataMaterialized;
221
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000222 bool StripDebugInfo = false;
223
Benjamin Kramercced8be2015-03-17 20:40:24 +0000224public:
225 std::error_code Error(BitcodeError E, const Twine &Message);
226 std::error_code Error(BitcodeError E);
227 std::error_code Error(const Twine &Message);
228
229 explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
230 DiagnosticHandlerFunction DiagnosticHandler);
231 explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C,
232 DiagnosticHandlerFunction DiagnosticHandler);
233 ~BitcodeReader() { FreeState(); }
234
235 std::error_code materializeForwardReferencedFunctions();
236
237 void FreeState();
238
239 void releaseBuffer();
240
241 bool isDematerializable(const GlobalValue *GV) const override;
242 std::error_code materialize(GlobalValue *GV) override;
243 std::error_code MaterializeModule(Module *M) override;
244 std::vector<StructType *> getIdentifiedStructTypes() const override;
245 void Dematerialize(GlobalValue *GV) override;
246
247 /// @brief Main interface to parsing a bitcode buffer.
248 /// @returns true if an error occurred.
249 std::error_code ParseBitcodeInto(Module *M,
250 bool ShouldLazyLoadMetadata = false);
251
252 /// @brief Cheap mechanism to just extract module triple
253 /// @returns true if an error occurred.
254 ErrorOr<std::string> parseTriple();
255
256 static uint64_t decodeSignRotatedValue(uint64_t V);
257
258 /// Materialize any deferred Metadata block.
259 std::error_code materializeMetadata() override;
260
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000261 void setStripDebugInfo() override;
262
Benjamin Kramercced8be2015-03-17 20:40:24 +0000263private:
264 std::vector<StructType *> IdentifiedStructTypes;
265 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
266 StructType *createIdentifiedStructType(LLVMContext &Context);
267
268 Type *getTypeByID(unsigned ID);
269 Value *getFnValueByID(unsigned ID, Type *Ty) {
270 if (Ty && Ty->isMetadataTy())
271 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
272 return ValueList.getValueFwdRef(ID, Ty);
273 }
274 Metadata *getFnMetadataByID(unsigned ID) {
275 return MDValueList.getValueFwdRef(ID);
276 }
277 BasicBlock *getBasicBlock(unsigned ID) const {
278 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
279 return FunctionBBs[ID];
280 }
281 AttributeSet getAttributes(unsigned i) const {
282 if (i-1 < MAttributes.size())
283 return MAttributes[i-1];
284 return AttributeSet();
285 }
286
287 /// getValueTypePair - Read a value/type pair out of the specified record from
288 /// slot 'Slot'. Increment Slot past the number of slots used in the record.
289 /// Return true on failure.
290 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
291 unsigned InstNum, Value *&ResVal) {
292 if (Slot == Record.size()) return true;
293 unsigned ValNo = (unsigned)Record[Slot++];
294 // Adjust the ValNo, if it was encoded relative to the InstNum.
295 if (UseRelativeIDs)
296 ValNo = InstNum - ValNo;
297 if (ValNo < InstNum) {
298 // If this is not a forward reference, just return the value we already
299 // have.
300 ResVal = getFnValueByID(ValNo, nullptr);
301 return ResVal == nullptr;
302 } else if (Slot == Record.size()) {
303 return true;
304 }
305
306 unsigned TypeNo = (unsigned)Record[Slot++];
307 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
308 return ResVal == nullptr;
309 }
310
311 /// popValue - Read a value out of the specified record from slot 'Slot'.
312 /// Increment Slot past the number of slots used by the value in the record.
313 /// Return true if there is an error.
314 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
315 unsigned InstNum, Type *Ty, Value *&ResVal) {
316 if (getValue(Record, Slot, InstNum, Ty, ResVal))
317 return true;
318 // All values currently take a single record slot.
319 ++Slot;
320 return false;
321 }
322
323 /// getValue -- Like popValue, but does not increment the Slot number.
324 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
325 unsigned InstNum, Type *Ty, Value *&ResVal) {
326 ResVal = getValue(Record, Slot, InstNum, Ty);
327 return ResVal == nullptr;
328 }
329
330 /// getValue -- Version of getValue that returns ResVal directly,
331 /// or 0 if there is an error.
332 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
333 unsigned InstNum, Type *Ty) {
334 if (Slot == Record.size()) return nullptr;
335 unsigned ValNo = (unsigned)Record[Slot];
336 // Adjust the ValNo, if it was encoded relative to the InstNum.
337 if (UseRelativeIDs)
338 ValNo = InstNum - ValNo;
339 return getFnValueByID(ValNo, Ty);
340 }
341
342 /// getValueSigned -- Like getValue, but decodes signed VBRs.
343 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
344 unsigned InstNum, Type *Ty) {
345 if (Slot == Record.size()) return nullptr;
346 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
347 // Adjust the ValNo, if it was encoded relative to the InstNum.
348 if (UseRelativeIDs)
349 ValNo = InstNum - ValNo;
350 return getFnValueByID(ValNo, Ty);
351 }
352
353 /// Converts alignment exponent (i.e. power of two (or zero)) to the
354 /// corresponding alignment to use. If alignment is too large, returns
355 /// a corresponding error code.
356 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
357 std::error_code ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
358 std::error_code ParseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
359 std::error_code ParseAttributeBlock();
360 std::error_code ParseAttributeGroupBlock();
361 std::error_code ParseTypeTable();
362 std::error_code ParseTypeTableBody();
363
364 std::error_code ParseValueSymbolTable();
365 std::error_code ParseConstants();
366 std::error_code RememberAndSkipFunctionBody();
367 /// Save the positions of the Metadata blocks and skip parsing the blocks.
368 std::error_code rememberAndSkipMetadata();
369 std::error_code ParseFunctionBody(Function *F);
370 std::error_code GlobalCleanup();
371 std::error_code ResolveGlobalAndAliasInits();
372 std::error_code ParseMetadata();
373 std::error_code ParseMetadataAttachment();
374 ErrorOr<std::string> parseModuleTriple();
375 std::error_code ParseUseLists();
376 std::error_code InitStream();
377 std::error_code InitStreamFromBuffer();
378 std::error_code InitLazyStream();
379 std::error_code FindFunctionInStream(
380 Function *F,
381 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
382};
383} // namespace
384
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000385BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
386 DiagnosticSeverity Severity,
387 const Twine &Msg)
388 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
389
390void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
391
392static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
393 std::error_code EC, const Twine &Message) {
394 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
395 DiagnosticHandler(DI);
396 return EC;
397}
398
399static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
400 std::error_code EC) {
401 return Error(DiagnosticHandler, EC, EC.message());
402}
403
404std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
405 return ::Error(DiagnosticHandler, make_error_code(E), Message);
406}
407
408std::error_code BitcodeReader::Error(const Twine &Message) {
409 return ::Error(DiagnosticHandler,
410 make_error_code(BitcodeError::CorruptedBitcode), Message);
411}
412
413std::error_code BitcodeReader::Error(BitcodeError E) {
414 return ::Error(DiagnosticHandler, make_error_code(E));
415}
416
417static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
418 LLVMContext &C) {
419 if (F)
420 return F;
421 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
422}
423
424BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
425 DiagnosticHandlerFunction DiagnosticHandler)
426 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
427 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
428 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
429 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
Manman Ren4a9b0eb2015-03-13 19:24:30 +0000430 WillMaterializeAllForwardRefs(false), IsMetadataMaterialized(false) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000431
432BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
433 DiagnosticHandlerFunction DiagnosticHandler)
434 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
435 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
436 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
437 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
Manman Ren4a9b0eb2015-03-13 19:24:30 +0000438 WillMaterializeAllForwardRefs(false), IsMetadataMaterialized(false) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000439
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000440std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
441 if (WillMaterializeAllForwardRefs)
442 return std::error_code();
443
444 // Prevent recursion.
445 WillMaterializeAllForwardRefs = true;
446
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000447 while (!BasicBlockFwdRefQueue.empty()) {
448 Function *F = BasicBlockFwdRefQueue.front();
449 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000450 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000451 if (!BasicBlockFwdRefs.count(F))
452 // Already materialized.
453 continue;
454
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000455 // Check for a function that isn't materializable to prevent an infinite
456 // loop. When parsing a blockaddress stored in a global variable, there
457 // isn't a trivial way to check if a function will have a body without a
458 // linear search through FunctionsWithBodies, so just check it here.
459 if (!F->isMaterializable())
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000460 return Error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000461
462 // Try to materialize F.
Rafael Espindola5a52e6d2014-10-24 22:50:48 +0000463 if (std::error_code EC = materialize(F))
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000464 return EC;
Rafael Espindolab7993462012-01-02 07:49:53 +0000465 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000466 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000467
468 // Reset state.
469 WillMaterializeAllForwardRefs = false;
470 return std::error_code();
Rafael Espindolab7993462012-01-02 07:49:53 +0000471}
472
Chris Lattner9eeada92007-05-18 04:02:46 +0000473void BitcodeReader::FreeState() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000474 Buffer = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000475 std::vector<Type*>().swap(TypeList);
Chris Lattner9eeada92007-05-18 04:02:46 +0000476 ValueList.clear();
Devang Patel05eb6172009-08-04 06:00:18 +0000477 MDValueList.clear();
David Majnemerdad0a642014-06-27 18:19:56 +0000478 std::vector<Comdat *>().swap(ComdatList);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000479
Bill Wendlinge94d8432012-12-07 23:16:57 +0000480 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattner9eeada92007-05-18 04:02:46 +0000481 std::vector<BasicBlock*>().swap(FunctionBBs);
482 std::vector<Function*>().swap(FunctionsWithBodies);
483 DeferredFunctionInfo.clear();
Manman Ren4a9b0eb2015-03-13 19:24:30 +0000484 DeferredMetadataInfo.clear();
Dan Gohman43aa8f02010-07-20 21:42:28 +0000485 MDKindMap.clear();
Benjamin Kramer736a4fc2012-09-21 14:34:31 +0000486
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +0000487 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000488 BasicBlockFwdRefQueue.clear();
Chris Lattner6694f602007-04-29 07:54:31 +0000489}
490
Chris Lattnerfee5a372007-05-04 03:30:17 +0000491//===----------------------------------------------------------------------===//
492// Helper functions to implement forward reference resolution, etc.
493//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +0000494
Chris Lattner1314b992007-04-22 06:23:29 +0000495/// ConvertToString - Convert a string from a record into an std::string, return
496/// true on failure.
Chris Lattnerccaa4482007-04-23 21:26:05 +0000497template<typename StrTy>
Benjamin Kramer9704ed02012-05-28 14:10:31 +0000498static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattnerccaa4482007-04-23 21:26:05 +0000499 StrTy &Result) {
Chris Lattnere14cb882007-05-04 19:11:41 +0000500 if (Idx > Record.size())
Chris Lattner1314b992007-04-22 06:23:29 +0000501 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000502
Chris Lattnere14cb882007-05-04 19:11:41 +0000503 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
504 Result += (char)Record[i];
Chris Lattner1314b992007-04-22 06:23:29 +0000505 return false;
506}
507
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000508static bool hasImplicitComdat(size_t Val) {
509 switch (Val) {
510 default:
511 return false;
512 case 1: // Old WeakAnyLinkage
513 case 4: // Old LinkOnceAnyLinkage
514 case 10: // Old WeakODRLinkage
515 case 11: // Old LinkOnceODRLinkage
516 return true;
517 }
518}
519
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000520static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000521 switch (Val) {
522 default: // Map unknown/new linkages to external
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000523 case 0:
524 return GlobalValue::ExternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000525 case 2:
526 return GlobalValue::AppendingLinkage;
527 case 3:
528 return GlobalValue::InternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000529 case 5:
530 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
531 case 6:
532 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
533 case 7:
534 return GlobalValue::ExternalWeakLinkage;
535 case 8:
536 return GlobalValue::CommonLinkage;
537 case 9:
538 return GlobalValue::PrivateLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000539 case 12:
540 return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000541 case 13:
542 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
543 case 14:
544 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Rafael Espindolabec6af62015-01-08 15:39:50 +0000545 case 15:
546 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000547 case 1: // Old value with implicit comdat.
548 case 16:
549 return GlobalValue::WeakAnyLinkage;
550 case 10: // Old value with implicit comdat.
551 case 17:
552 return GlobalValue::WeakODRLinkage;
553 case 4: // Old value with implicit comdat.
554 case 18:
555 return GlobalValue::LinkOnceAnyLinkage;
556 case 11: // Old value with implicit comdat.
557 case 19:
558 return GlobalValue::LinkOnceODRLinkage;
Chris Lattner1314b992007-04-22 06:23:29 +0000559 }
560}
561
562static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
563 switch (Val) {
564 default: // Map unknown visibilities to default.
565 case 0: return GlobalValue::DefaultVisibility;
566 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000567 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000568 }
569}
570
Nico Rieck7157bb72014-01-14 15:22:47 +0000571static GlobalValue::DLLStorageClassTypes
572GetDecodedDLLStorageClass(unsigned Val) {
573 switch (Val) {
574 default: // Map unknown values to default.
575 case 0: return GlobalValue::DefaultStorageClass;
576 case 1: return GlobalValue::DLLImportStorageClass;
577 case 2: return GlobalValue::DLLExportStorageClass;
578 }
579}
580
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000581static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
582 switch (Val) {
583 case 0: return GlobalVariable::NotThreadLocal;
584 default: // Map unknown non-zero value to general dynamic.
585 case 1: return GlobalVariable::GeneralDynamicTLSModel;
586 case 2: return GlobalVariable::LocalDynamicTLSModel;
587 case 3: return GlobalVariable::InitialExecTLSModel;
588 case 4: return GlobalVariable::LocalExecTLSModel;
589 }
590}
591
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000592static int GetDecodedCastOpcode(unsigned Val) {
593 switch (Val) {
594 default: return -1;
595 case bitc::CAST_TRUNC : return Instruction::Trunc;
596 case bitc::CAST_ZEXT : return Instruction::ZExt;
597 case bitc::CAST_SEXT : return Instruction::SExt;
598 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
599 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
600 case bitc::CAST_UITOFP : return Instruction::UIToFP;
601 case bitc::CAST_SITOFP : return Instruction::SIToFP;
602 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
603 case bitc::CAST_FPEXT : return Instruction::FPExt;
604 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
605 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
606 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000607 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000608 }
609}
Chris Lattner229907c2011-07-18 04:54:35 +0000610static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000611 switch (Val) {
612 default: return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000613 case bitc::BINOP_ADD:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000614 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000615 case bitc::BINOP_SUB:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000616 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000617 case bitc::BINOP_MUL:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000618 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000619 case bitc::BINOP_UDIV: return Instruction::UDiv;
620 case bitc::BINOP_SDIV:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000621 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000622 case bitc::BINOP_UREM: return Instruction::URem;
623 case bitc::BINOP_SREM:
Duncan Sands9dff9be2010-02-15 16:12:20 +0000624 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000625 case bitc::BINOP_SHL: return Instruction::Shl;
626 case bitc::BINOP_LSHR: return Instruction::LShr;
627 case bitc::BINOP_ASHR: return Instruction::AShr;
628 case bitc::BINOP_AND: return Instruction::And;
629 case bitc::BINOP_OR: return Instruction::Or;
630 case bitc::BINOP_XOR: return Instruction::Xor;
631 }
632}
633
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000634static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
635 switch (Val) {
636 default: return AtomicRMWInst::BAD_BINOP;
637 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
638 case bitc::RMW_ADD: return AtomicRMWInst::Add;
639 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
640 case bitc::RMW_AND: return AtomicRMWInst::And;
641 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
642 case bitc::RMW_OR: return AtomicRMWInst::Or;
643 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
644 case bitc::RMW_MAX: return AtomicRMWInst::Max;
645 case bitc::RMW_MIN: return AtomicRMWInst::Min;
646 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
647 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
648 }
649}
650
Eli Friedmanfee02c62011-07-25 23:16:38 +0000651static AtomicOrdering GetDecodedOrdering(unsigned Val) {
652 switch (Val) {
653 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
654 case bitc::ORDERING_UNORDERED: return Unordered;
655 case bitc::ORDERING_MONOTONIC: return Monotonic;
656 case bitc::ORDERING_ACQUIRE: return Acquire;
657 case bitc::ORDERING_RELEASE: return Release;
658 case bitc::ORDERING_ACQREL: return AcquireRelease;
659 default: // Map unknown orderings to sequentially-consistent.
660 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
661 }
662}
663
664static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
665 switch (Val) {
666 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
667 default: // Map unknown scopes to cross-thread.
668 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
669 }
670}
671
David Majnemerdad0a642014-06-27 18:19:56 +0000672static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
673 switch (Val) {
674 default: // Map unknown selection kinds to any.
675 case bitc::COMDAT_SELECTION_KIND_ANY:
676 return Comdat::Any;
677 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
678 return Comdat::ExactMatch;
679 case bitc::COMDAT_SELECTION_KIND_LARGEST:
680 return Comdat::Largest;
681 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
682 return Comdat::NoDuplicates;
683 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
684 return Comdat::SameSize;
685 }
686}
687
Nico Rieck7157bb72014-01-14 15:22:47 +0000688static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
689 switch (Val) {
690 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
691 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
692 }
693}
694
Gabor Greiff6caff662008-05-10 08:32:32 +0000695namespace llvm {
Chris Lattner1663cca2007-04-24 05:48:56 +0000696namespace {
697 /// @brief A class for maintaining the slot number definition
698 /// as a placeholder for the actual definition for forward constants defs.
699 class ConstantPlaceHolder : public ConstantExpr {
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000700 void operator=(const ConstantPlaceHolder &) = delete;
Gabor Greife9ecc682008-04-06 20:25:17 +0000701 public:
702 // allocate space for exactly one operand
703 void *operator new(size_t s) {
704 return User::operator new(s, 1);
705 }
Chris Lattner229907c2011-07-18 04:54:35 +0000706 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greiff6caff662008-05-10 08:32:32 +0000707 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000708 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner1663cca2007-04-24 05:48:56 +0000709 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000710
Chris Lattner74429932008-08-21 02:34:16 +0000711 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattner74429932008-08-21 02:34:16 +0000712 static bool classof(const Value *V) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000713 return isa<ConstantExpr>(V) &&
Chris Lattner74429932008-08-21 02:34:16 +0000714 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
715 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000716
717
Gabor Greiff6caff662008-05-10 08:32:32 +0000718 /// Provide fast operand accessors
Richard Trieue3d126c2014-11-21 02:42:08 +0000719 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner1663cca2007-04-24 05:48:56 +0000720 };
721}
722
Chris Lattner2d8cd802009-03-31 22:55:09 +0000723// FIXME: can we inherit this from ConstantExpr?
Gabor Greiff6caff662008-05-10 08:32:32 +0000724template <>
Jay Foadc8adf5f2011-01-11 15:07:38 +0000725struct OperandTraits<ConstantPlaceHolder> :
726 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greiff6caff662008-05-10 08:32:32 +0000727};
Richard Trieue3d126c2014-11-21 02:42:08 +0000728DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
Gabor Greiff6caff662008-05-10 08:32:32 +0000729}
730
Chris Lattner2d8cd802009-03-31 22:55:09 +0000731
732void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
733 if (Idx == size()) {
734 push_back(V);
735 return;
736 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000737
Chris Lattner2d8cd802009-03-31 22:55:09 +0000738 if (Idx >= size())
739 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000740
Chris Lattner2d8cd802009-03-31 22:55:09 +0000741 WeakVH &OldV = ValuePtrs[Idx];
Craig Topper2617dcc2014-04-15 06:32:26 +0000742 if (!OldV) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000743 OldV = V;
744 return;
745 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000746
Chris Lattner2d8cd802009-03-31 22:55:09 +0000747 // Handle constants and non-constants (e.g. instrs) differently for
748 // efficiency.
749 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
750 ResolveConstants.push_back(std::make_pair(PHC, Idx));
751 OldV = V;
752 } else {
753 // If there was a forward reference to this value, replace it.
754 Value *PrevVal = OldV;
755 OldV->replaceAllUsesWith(V);
756 delete PrevVal;
Gabor Greiff6caff662008-05-10 08:32:32 +0000757 }
758}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000759
Gabor Greiff6caff662008-05-10 08:32:32 +0000760
Chris Lattner1663cca2007-04-24 05:48:56 +0000761Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattner229907c2011-07-18 04:54:35 +0000762 Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000763 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000764 resize(Idx + 1);
Chris Lattner1663cca2007-04-24 05:48:56 +0000765
Chris Lattner2d8cd802009-03-31 22:55:09 +0000766 if (Value *V = ValuePtrs[Idx]) {
Chris Lattner83930552007-05-01 07:01:57 +0000767 assert(Ty == V->getType() && "Type mismatch in constant table!");
768 return cast<Constant>(V);
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000769 }
Chris Lattner1663cca2007-04-24 05:48:56 +0000770
771 // Create and return a placeholder, which will later be RAUW'd.
Owen Andersone9f98042009-07-07 20:18:58 +0000772 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000773 ValuePtrs[Idx] = C;
Chris Lattner1663cca2007-04-24 05:48:56 +0000774 return C;
775}
776
Chris Lattner229907c2011-07-18 04:54:35 +0000777Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000778 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000779 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000780
Chris Lattner2d8cd802009-03-31 22:55:09 +0000781 if (Value *V = ValuePtrs[Idx]) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000782 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
Chris Lattner83930552007-05-01 07:01:57 +0000783 return V;
784 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000785
Chris Lattner1fc27f02007-05-02 05:16:49 +0000786 // No type specified, must be invalid reference.
Craig Topper2617dcc2014-04-15 06:32:26 +0000787 if (!Ty) return nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000788
Chris Lattner83930552007-05-01 07:01:57 +0000789 // Create and return a placeholder, which will later be RAUW'd.
790 Value *V = new Argument(Ty);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000791 ValuePtrs[Idx] = V;
Chris Lattner83930552007-05-01 07:01:57 +0000792 return V;
793}
794
Chris Lattner74429932008-08-21 02:34:16 +0000795/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
796/// resolves any forward references. The idea behind this is that we sometimes
797/// get constants (such as large arrays) which reference *many* forward ref
798/// constants. Replacing each of these causes a lot of thrashing when
799/// building/reuniquing the constant. Instead of doing this, we look at all the
800/// uses and rewrite all the place holders at once for any constant that uses
801/// a placeholder.
802void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000803 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattner74429932008-08-21 02:34:16 +0000804 // binary search.
805 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000806
Chris Lattner74429932008-08-21 02:34:16 +0000807 SmallVector<Constant*, 64> NewOps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000808
Chris Lattner74429932008-08-21 02:34:16 +0000809 while (!ResolveConstants.empty()) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000810 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattner74429932008-08-21 02:34:16 +0000811 Constant *Placeholder = ResolveConstants.back().first;
812 ResolveConstants.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000813
Chris Lattner74429932008-08-21 02:34:16 +0000814 // Loop over all users of the placeholder, updating them to reference the
815 // new value. If they reference more than one placeholder, update them all
816 // at once.
817 while (!Placeholder->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000818 auto UI = Placeholder->user_begin();
Gabor Greif2c0ab482010-07-09 16:01:21 +0000819 User *U = *UI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000820
Chris Lattner74429932008-08-21 02:34:16 +0000821 // If the using object isn't uniqued, just update the operands. This
822 // handles instructions and initializers for global variables.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000823 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattner479c5d92008-08-21 17:31:45 +0000824 UI.getUse().set(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +0000825 continue;
826 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000827
Chris Lattner74429932008-08-21 02:34:16 +0000828 // Otherwise, we have a constant that uses the placeholder. Replace that
829 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000830 Constant *UserC = cast<Constant>(U);
Chris Lattner74429932008-08-21 02:34:16 +0000831 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
832 I != E; ++I) {
833 Value *NewOp;
834 if (!isa<ConstantPlaceHolder>(*I)) {
835 // Not a placeholder reference.
836 NewOp = *I;
837 } else if (*I == Placeholder) {
838 // Common case is that it just references this one placeholder.
839 NewOp = RealVal;
840 } else {
841 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000842 ResolveConstantsTy::iterator It =
843 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattner74429932008-08-21 02:34:16 +0000844 std::pair<Constant*, unsigned>(cast<Constant>(*I),
845 0));
846 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000847 NewOp = operator[](It->second);
Chris Lattner74429932008-08-21 02:34:16 +0000848 }
849
850 NewOps.push_back(cast<Constant>(NewOp));
851 }
852
853 // Make the new constant.
854 Constant *NewC;
855 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad83be3612011-06-22 09:24:39 +0000856 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000857 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnercc19efa2011-06-20 04:01:31 +0000858 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000859 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner69229312011-02-15 00:14:00 +0000860 NewC = ConstantVector::get(NewOps);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000861 } else {
862 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foad5c984e562011-04-13 13:46:01 +0000863 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000864 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000865
Chris Lattner74429932008-08-21 02:34:16 +0000866 UserC->replaceAllUsesWith(NewC);
867 UserC->destroyConstant();
868 NewOps.clear();
869 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000870
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000871 // Update all ValueHandles, they should be the only users at this point.
872 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +0000873 delete Placeholder;
874 }
875}
876
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000877void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +0000878 if (Idx == size()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000879 push_back(MD);
Devang Patel05eb6172009-08-04 06:00:18 +0000880 return;
881 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000882
Devang Patel05eb6172009-08-04 06:00:18 +0000883 if (Idx >= size())
884 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000885
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000886 TrackingMDRef &OldMD = MDValuePtrs[Idx];
887 if (!OldMD) {
888 OldMD.reset(MD);
Devang Patel05eb6172009-08-04 06:00:18 +0000889 return;
890 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000891
Devang Patel05eb6172009-08-04 06:00:18 +0000892 // If there was a forward reference to this value, replace it.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000893 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000894 PrevMD->replaceAllUsesWith(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000895 --NumFwdRefs;
Devang Patel05eb6172009-08-04 06:00:18 +0000896}
897
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000898Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +0000899 if (Idx >= size())
900 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000901
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000902 if (Metadata *MD = MDValuePtrs[Idx])
903 return MD;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000904
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +0000905 // Track forward refs to be resolved later.
906 if (AnyFwdRefs) {
907 MinFwdRef = std::min(MinFwdRef, Idx);
908 MaxFwdRef = std::max(MaxFwdRef, Idx);
909 } else {
910 AnyFwdRefs = true;
911 MinFwdRef = MaxFwdRef = Idx;
912 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000913 ++NumFwdRefs;
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +0000914
915 // Create and return a placeholder, which will later be RAUW'd.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000916 Metadata *MD = MDNode::getTemporary(Context, None).release();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000917 MDValuePtrs[Idx].reset(MD);
918 return MD;
919}
920
921void BitcodeReaderMDValueList::tryToResolveCycles() {
922 if (!AnyFwdRefs)
923 // Nothing to do.
924 return;
925
926 if (NumFwdRefs)
927 // Still forward references... can't resolve cycles.
928 return;
929
930 // Resolve any cycles.
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +0000931 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
932 auto &MD = MDValuePtrs[I];
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000933 auto *N = dyn_cast_or_null<MDNode>(MD);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000934 if (!N)
935 continue;
936
937 assert(!N->isTemporary() && "Unexpected forward reference");
938 N->resolveCycles();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000939 }
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +0000940
941 // Make sure we return early again until there's another forward ref.
942 AnyFwdRefs = false;
Devang Patel05eb6172009-08-04 06:00:18 +0000943}
Chris Lattner1314b992007-04-22 06:23:29 +0000944
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000945Type *BitcodeReader::getTypeByID(unsigned ID) {
946 // The type table size is always specified correctly.
947 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +0000948 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +0000949
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000950 if (Type *Ty = TypeList[ID])
951 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000952
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000953 // If we have a forward reference, the only possible case is when it is to a
954 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +0000955 return TypeList[ID] = createIdentifiedStructType(Context);
956}
957
958StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
959 StringRef Name) {
960 auto *Ret = StructType::create(Context, Name);
961 IdentifiedStructTypes.push_back(Ret);
962 return Ret;
963}
964
965StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
966 auto *Ret = StructType::create(Context);
967 IdentifiedStructTypes.push_back(Ret);
968 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +0000969}
970
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000971
Chris Lattnerfee5a372007-05-04 03:30:17 +0000972//===----------------------------------------------------------------------===//
973// Functions for parsing blocks from the bitcode file
974//===----------------------------------------------------------------------===//
975
Bill Wendling56aeccc2013-02-04 23:32:23 +0000976
977/// \brief This fills an AttrBuilder object with the LLVM attributes that have
978/// been decoded from the given integer. This function must stay in sync with
979/// 'encodeLLVMAttributesForBitcode'.
980static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
981 uint64_t EncodedAttrs) {
982 // FIXME: Remove in 4.0.
983
984 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
985 // the bits above 31 down by 11 bits.
986 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
987 assert((!Alignment || isPowerOf2_32(Alignment)) &&
988 "Alignment must be a power of two.");
989
990 if (Alignment)
991 B.addAlignmentAttr(Alignment);
Kostya Serebryanyd688bab2013-02-11 08:13:54 +0000992 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
Bill Wendling56aeccc2013-02-04 23:32:23 +0000993 (EncodedAttrs & 0xffff));
994}
995
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000996std::error_code BitcodeReader::ParseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +0000997 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000998 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000999
Devang Patela05633e2008-09-26 22:53:05 +00001000 if (!MAttributes.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001001 return Error("Invalid multiple blocks");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001002
Chris Lattnerfee5a372007-05-04 03:30:17 +00001003 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001004
Bill Wendling71173cb2013-01-27 00:36:48 +00001005 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001006
Chris Lattnerfee5a372007-05-04 03:30:17 +00001007 // Read all the records.
1008 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001009 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001010
Chris Lattner27d38752013-01-20 02:13:19 +00001011 switch (Entry.Kind) {
1012 case BitstreamEntry::SubBlock: // Handled for us already.
1013 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001014 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001015 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001016 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001017 case BitstreamEntry::Record:
1018 // The interesting case.
1019 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001020 }
Joe Abbey97b7a172013-02-06 22:14:06 +00001021
Chris Lattnerfee5a372007-05-04 03:30:17 +00001022 // Read a record.
1023 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001024 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +00001025 default: // Default behavior: ignore.
1026 break;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001027 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1028 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +00001029 if (Record.size() & 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001030 return Error("Invalid record");
Chris Lattnerfee5a372007-05-04 03:30:17 +00001031
Chris Lattnerfee5a372007-05-04 03:30:17 +00001032 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +00001033 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001034 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling60011b82013-01-29 01:43:29 +00001035 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +00001036 }
Devang Patela05633e2008-09-26 22:53:05 +00001037
Bill Wendlinge94d8432012-12-07 23:16:57 +00001038 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +00001039 Attrs.clear();
1040 break;
1041 }
Bill Wendling0dc08912013-02-12 08:13:50 +00001042 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1043 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1044 Attrs.push_back(MAttributeGroups[Record[i]]);
1045
1046 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1047 Attrs.clear();
1048 break;
1049 }
Duncan Sands04eb67e2007-11-20 14:09:29 +00001050 }
Chris Lattnerfee5a372007-05-04 03:30:17 +00001051 }
1052}
1053
Reid Klecknere9f36af2013-11-12 01:31:00 +00001054// Returns Attribute::None on unrecognized codes.
1055static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
1056 switch (Code) {
1057 default:
1058 return Attribute::None;
1059 case bitc::ATTR_KIND_ALIGNMENT:
1060 return Attribute::Alignment;
1061 case bitc::ATTR_KIND_ALWAYS_INLINE:
1062 return Attribute::AlwaysInline;
1063 case bitc::ATTR_KIND_BUILTIN:
1064 return Attribute::Builtin;
1065 case bitc::ATTR_KIND_BY_VAL:
1066 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +00001067 case bitc::ATTR_KIND_IN_ALLOCA:
1068 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001069 case bitc::ATTR_KIND_COLD:
1070 return Attribute::Cold;
1071 case bitc::ATTR_KIND_INLINE_HINT:
1072 return Attribute::InlineHint;
1073 case bitc::ATTR_KIND_IN_REG:
1074 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +00001075 case bitc::ATTR_KIND_JUMP_TABLE:
1076 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001077 case bitc::ATTR_KIND_MIN_SIZE:
1078 return Attribute::MinSize;
1079 case bitc::ATTR_KIND_NAKED:
1080 return Attribute::Naked;
1081 case bitc::ATTR_KIND_NEST:
1082 return Attribute::Nest;
1083 case bitc::ATTR_KIND_NO_ALIAS:
1084 return Attribute::NoAlias;
1085 case bitc::ATTR_KIND_NO_BUILTIN:
1086 return Attribute::NoBuiltin;
1087 case bitc::ATTR_KIND_NO_CAPTURE:
1088 return Attribute::NoCapture;
1089 case bitc::ATTR_KIND_NO_DUPLICATE:
1090 return Attribute::NoDuplicate;
1091 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1092 return Attribute::NoImplicitFloat;
1093 case bitc::ATTR_KIND_NO_INLINE:
1094 return Attribute::NoInline;
1095 case bitc::ATTR_KIND_NON_LAZY_BIND:
1096 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001097 case bitc::ATTR_KIND_NON_NULL:
1098 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001099 case bitc::ATTR_KIND_DEREFERENCEABLE:
1100 return Attribute::Dereferenceable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001101 case bitc::ATTR_KIND_NO_RED_ZONE:
1102 return Attribute::NoRedZone;
1103 case bitc::ATTR_KIND_NO_RETURN:
1104 return Attribute::NoReturn;
1105 case bitc::ATTR_KIND_NO_UNWIND:
1106 return Attribute::NoUnwind;
1107 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1108 return Attribute::OptimizeForSize;
1109 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1110 return Attribute::OptimizeNone;
1111 case bitc::ATTR_KIND_READ_NONE:
1112 return Attribute::ReadNone;
1113 case bitc::ATTR_KIND_READ_ONLY:
1114 return Attribute::ReadOnly;
1115 case bitc::ATTR_KIND_RETURNED:
1116 return Attribute::Returned;
1117 case bitc::ATTR_KIND_RETURNS_TWICE:
1118 return Attribute::ReturnsTwice;
1119 case bitc::ATTR_KIND_S_EXT:
1120 return Attribute::SExt;
1121 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1122 return Attribute::StackAlignment;
1123 case bitc::ATTR_KIND_STACK_PROTECT:
1124 return Attribute::StackProtect;
1125 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1126 return Attribute::StackProtectReq;
1127 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1128 return Attribute::StackProtectStrong;
1129 case bitc::ATTR_KIND_STRUCT_RET:
1130 return Attribute::StructRet;
1131 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1132 return Attribute::SanitizeAddress;
1133 case bitc::ATTR_KIND_SANITIZE_THREAD:
1134 return Attribute::SanitizeThread;
1135 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1136 return Attribute::SanitizeMemory;
1137 case bitc::ATTR_KIND_UW_TABLE:
1138 return Attribute::UWTable;
1139 case bitc::ATTR_KIND_Z_EXT:
1140 return Attribute::ZExt;
1141 }
1142}
1143
JF Bastien30bf96b2015-02-22 19:32:03 +00001144std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1145 unsigned &Alignment) {
1146 // Note: Alignment in bitcode files is incremented by 1, so that zero
1147 // can be used for default alignment.
1148 if (Exponent > Value::MaxAlignmentExponent + 1)
1149 return Error("Invalid alignment value");
1150 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1151 return std::error_code();
1152}
1153
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001154std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
1155 Attribute::AttrKind *Kind) {
Reid Klecknere9f36af2013-11-12 01:31:00 +00001156 *Kind = GetAttrFromCode(Code);
1157 if (*Kind == Attribute::None)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001158 return Error(BitcodeError::CorruptedBitcode,
1159 "Unknown attribute kind (" + Twine(Code) + ")");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001160 return std::error_code();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001161}
1162
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001163std::error_code BitcodeReader::ParseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +00001164 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001165 return Error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001166
1167 if (!MAttributeGroups.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001168 return Error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +00001169
1170 SmallVector<uint64_t, 64> Record;
1171
1172 // Read all the records.
1173 while (1) {
1174 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1175
1176 switch (Entry.Kind) {
1177 case BitstreamEntry::SubBlock: // Handled for us already.
1178 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001179 return Error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +00001180 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001181 return std::error_code();
Bill Wendlingba629332013-02-10 23:24:25 +00001182 case BitstreamEntry::Record:
1183 // The interesting case.
1184 break;
1185 }
1186
1187 // Read a record.
1188 Record.clear();
1189 switch (Stream.readRecord(Entry.ID, Record)) {
1190 default: // Default behavior: ignore.
1191 break;
1192 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1193 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001194 return Error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001195
Bill Wendlinge46707e2013-02-11 22:32:29 +00001196 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +00001197 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1198
1199 AttrBuilder B;
1200 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1201 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001202 Attribute::AttrKind Kind;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001203 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001204 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001205
1206 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +00001207 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001208 Attribute::AttrKind Kind;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001209 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001210 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001211 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001212 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001213 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001214 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001215 else if (Kind == Attribute::Dereferenceable)
1216 B.addDereferenceableAttr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +00001217 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +00001218 assert((Record[i] == 3 || Record[i] == 4) &&
1219 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +00001220 bool HasValue = (Record[i++] == 4);
1221 SmallString<64> KindStr;
1222 SmallString<64> ValStr;
1223
1224 while (Record[i] != 0 && i != e)
1225 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001226 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001227
1228 if (HasValue) {
1229 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +00001230 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +00001231 while (Record[i] != 0 && i != e)
1232 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001233 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001234 }
1235
1236 B.addAttribute(KindStr.str(), ValStr.str());
1237 }
1238 }
1239
Bill Wendlinge46707e2013-02-11 22:32:29 +00001240 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +00001241 break;
1242 }
1243 }
1244 }
1245}
1246
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001247std::error_code BitcodeReader::ParseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001248 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001249 return Error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +00001250
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001251 return ParseTypeTableBody();
1252}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001253
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001254std::error_code BitcodeReader::ParseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +00001255 if (!TypeList.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001256 return Error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +00001257
1258 SmallVector<uint64_t, 64> Record;
1259 unsigned NumRecords = 0;
1260
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001261 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +00001262
Chris Lattner1314b992007-04-22 06:23:29 +00001263 // Read all the records for this type table.
1264 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001265 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001266
Chris Lattner27d38752013-01-20 02:13:19 +00001267 switch (Entry.Kind) {
1268 case BitstreamEntry::SubBlock: // Handled for us already.
1269 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001270 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001271 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +00001272 if (NumRecords != TypeList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001273 return Error("Malformed block");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001274 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001275 case BitstreamEntry::Record:
1276 // The interesting case.
1277 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001278 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001279
Chris Lattner1314b992007-04-22 06:23:29 +00001280 // Read a record.
1281 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001282 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001283 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001284 default:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001285 return Error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +00001286 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1287 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1288 // type list. This allows us to reserve space.
1289 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001290 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001291 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001292 continue;
Chris Lattner1314b992007-04-22 06:23:29 +00001293 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +00001294 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001295 break;
Dan Gohman518cda42011-12-17 00:04:22 +00001296 case bitc::TYPE_CODE_HALF: // HALF
1297 ResultTy = Type::getHalfTy(Context);
1298 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001299 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +00001300 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001301 break;
1302 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +00001303 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001304 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001305 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +00001306 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001307 break;
1308 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001309 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001310 break;
1311 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001312 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001313 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001314 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +00001315 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001316 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001317 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +00001318 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001319 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +00001320 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1321 ResultTy = Type::getX86_MMXTy(Context);
1322 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001323 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
Chris Lattner1314b992007-04-22 06:23:29 +00001324 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001325 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001326
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001327 uint64_t NumBits = Record[0];
1328 if (NumBits < IntegerType::MIN_INT_BITS ||
1329 NumBits > IntegerType::MAX_INT_BITS)
1330 return Error("Bitwidth for integer type out of range");
1331 ResultTy = IntegerType::get(Context, NumBits);
Chris Lattner1314b992007-04-22 06:23:29 +00001332 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001333 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001334 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001335 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +00001336 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001337 return Error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001338 unsigned AddressSpace = 0;
1339 if (Record.size() == 2)
1340 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001341 ResultTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001342 if (!ResultTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001343 return Error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001344 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +00001345 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001346 }
Nuno Lopes561dae02012-05-23 15:19:39 +00001347 case bitc::TYPE_CODE_FUNCTION_OLD: {
1348 // FIXME: attrid is dead, remove it in LLVM 4.0
1349 // FUNCTION: [vararg, attrid, retty, paramty x N]
1350 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001351 return Error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +00001352 SmallVector<Type*, 8> ArgTys;
1353 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1354 if (Type *T = getTypeByID(Record[i]))
1355 ArgTys.push_back(T);
1356 else
1357 break;
1358 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001359
Nuno Lopes561dae02012-05-23 15:19:39 +00001360 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001361 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001362 return Error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +00001363
1364 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1365 break;
1366 }
Chad Rosier95898722011-11-03 00:14:01 +00001367 case bitc::TYPE_CODE_FUNCTION: {
1368 // FUNCTION: [vararg, retty, paramty x N]
1369 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001370 return Error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001371 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +00001372 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1373 if (Type *T = getTypeByID(Record[i]))
1374 ArgTys.push_back(T);
1375 else
1376 break;
1377 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001378
Chad Rosier95898722011-11-03 00:14:01 +00001379 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001380 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001381 return Error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +00001382
1383 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1384 break;
1385 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001386 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +00001387 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001388 return Error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001389 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001390 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1391 if (Type *T = getTypeByID(Record[i]))
1392 EltTys.push_back(T);
1393 else
1394 break;
1395 }
1396 if (EltTys.size() != Record.size()-1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001397 return Error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001398 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001399 break;
1400 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001401 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1402 if (ConvertToString(Record, 0, TypeName))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001403 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001404 continue;
1405
1406 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1407 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001408 return Error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001409
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001410 if (NumRecords >= TypeList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001411 return Error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001412
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001413 // Check to see if this was forward referenced, if so fill in the temp.
1414 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1415 if (Res) {
1416 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001417 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001418 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001419 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001420 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001421
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001422 SmallVector<Type*, 8> EltTys;
1423 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1424 if (Type *T = getTypeByID(Record[i]))
1425 EltTys.push_back(T);
1426 else
1427 break;
1428 }
1429 if (EltTys.size() != Record.size()-1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001430 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001431 Res->setBody(EltTys, Record[0]);
1432 ResultTy = Res;
1433 break;
1434 }
1435 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1436 if (Record.size() != 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001437 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001438
1439 if (NumRecords >= TypeList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001440 return Error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001441
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001442 // Check to see if this was forward referenced, if so fill in the temp.
1443 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1444 if (Res) {
1445 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001446 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001447 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001448 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001449 TypeName.clear();
1450 ResultTy = Res;
1451 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001452 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001453 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1454 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001455 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001456 if ((ResultTy = getTypeByID(Record[1])))
1457 ResultTy = ArrayType::get(ResultTy, Record[0]);
1458 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001459 return Error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001460 break;
1461 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1462 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001463 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001464 if ((ResultTy = getTypeByID(Record[1])))
1465 ResultTy = VectorType::get(ResultTy, Record[0]);
1466 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001467 return Error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001468 break;
1469 }
1470
1471 if (NumRecords >= TypeList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001472 return Error("Invalid TYPE table");
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001473 if (TypeList[NumRecords])
1474 return Error(
1475 "Invalid TYPE table: Only named structs can be forward referenced");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001476 assert(ResultTy && "Didn't read a type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001477 TypeList[NumRecords++] = ResultTy;
1478 }
1479}
1480
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001481std::error_code BitcodeReader::ParseValueSymbolTable() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001482 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001483 return Error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001484
1485 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001486
David Majnemer3087b222015-01-20 05:58:07 +00001487 Triple TT(TheModule->getTargetTriple());
1488
Chris Lattnerccaa4482007-04-23 21:26:05 +00001489 // Read all the records for this value table.
1490 SmallString<128> ValueName;
1491 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001492 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001493
Chris Lattner27d38752013-01-20 02:13:19 +00001494 switch (Entry.Kind) {
1495 case BitstreamEntry::SubBlock: // Handled for us already.
1496 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001497 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001498 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001499 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001500 case BitstreamEntry::Record:
1501 // The interesting case.
1502 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001503 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001504
Chris Lattnerccaa4482007-04-23 21:26:05 +00001505 // Read a record.
1506 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001507 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001508 default: // Default behavior: unknown type.
1509 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00001510 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattnerccaa4482007-04-23 21:26:05 +00001511 if (ConvertToString(Record, 1, ValueName))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001512 return Error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001513 unsigned ValueID = Record[0];
Karthik Bhat82540e92014-03-27 12:08:23 +00001514 if (ValueID >= ValueList.size() || !ValueList[ValueID])
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001515 return Error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001516 Value *V = ValueList[ValueID];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001517
Daniel Dunbard786b512009-07-26 00:34:27 +00001518 V->setName(StringRef(ValueName.data(), ValueName.size()));
Rafael Espindola12ca34f2015-01-19 15:16:06 +00001519 if (auto *GO = dyn_cast<GlobalObject>(V)) {
David Majnemer3087b222015-01-20 05:58:07 +00001520 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1521 if (TT.isOSBinFormatMachO())
1522 GO->setComdat(nullptr);
1523 else
1524 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1525 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00001526 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001527 ValueName.clear();
1528 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00001529 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00001530 case bitc::VST_CODE_BBENTRY: {
Chris Lattner6be58c62007-05-03 22:18:21 +00001531 if (ConvertToString(Record, 1, ValueName))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001532 return Error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00001533 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001534 if (!BB)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001535 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001536
Daniel Dunbard786b512009-07-26 00:34:27 +00001537 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00001538 ValueName.clear();
1539 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001540 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00001541 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001542 }
1543}
1544
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001545static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1546
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001547std::error_code BitcodeReader::ParseMetadata() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00001548 IsMetadataMaterialized = true;
Devang Patel89923232010-01-11 18:52:33 +00001549 unsigned NextMDValueNo = MDValueList.size();
Devang Patel7428d8a2009-07-22 17:43:22 +00001550
1551 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001552 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001553
Devang Patel7428d8a2009-07-22 17:43:22 +00001554 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001555
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001556 auto getMD =
1557 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1558 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1559 if (ID)
1560 return getMD(ID - 1);
1561 return nullptr;
1562 };
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001563 auto getMDString = [&](unsigned ID) -> MDString *{
1564 // This requires that the ID is not really a forward reference. In
1565 // particular, the MDString must already have been resolved.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001566 return cast_or_null<MDString>(getMDOrNull(ID));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001567 };
1568
1569#define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1570 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1571
Devang Patel7428d8a2009-07-22 17:43:22 +00001572 // Read all the records.
1573 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001574 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001575
Chris Lattner27d38752013-01-20 02:13:19 +00001576 switch (Entry.Kind) {
1577 case BitstreamEntry::SubBlock: // Handled for us already.
1578 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001579 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001580 case BitstreamEntry::EndBlock:
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001581 MDValueList.tryToResolveCycles();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001582 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001583 case BitstreamEntry::Record:
1584 // The interesting case.
1585 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00001586 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001587
Devang Patel7428d8a2009-07-22 17:43:22 +00001588 // Read a record.
1589 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001590 unsigned Code = Stream.readRecord(Entry.ID, Record);
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001591 bool IsDistinct = false;
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00001592 switch (Code) {
Devang Patel7428d8a2009-07-22 17:43:22 +00001593 default: // Default behavior: ignore.
1594 break;
Devang Patel27c87ff2009-07-29 22:34:41 +00001595 case bitc::METADATA_NAME: {
Chris Lattner8d140532013-01-20 02:54:05 +00001596 // Read name of the named metadata.
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001597 SmallString<8> Name(Record.begin(), Record.end());
Devang Patel27c87ff2009-07-29 22:34:41 +00001598 Record.clear();
1599 Code = Stream.ReadCode();
1600
Chris Lattnerb8778552011-06-17 17:50:30 +00001601 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Chris Lattner27d38752013-01-20 02:13:19 +00001602 unsigned NextBitCode = Stream.readRecord(Code, Record);
Chris Lattnerb8778552011-06-17 17:50:30 +00001603 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patel27c87ff2009-07-29 22:34:41 +00001604
1605 // Read named metadata elements.
1606 unsigned Size = Record.size();
Dan Gohman2637cc12010-07-21 23:38:33 +00001607 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patel27c87ff2009-07-29 22:34:41 +00001608 for (unsigned i = 0; i != Size; ++i) {
Karthik Bhat82540e92014-03-27 12:08:23 +00001609 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
Craig Topper2617dcc2014-04-15 06:32:26 +00001610 if (!MD)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001611 return Error("Invalid record");
Dan Gohman2637cc12010-07-21 23:38:33 +00001612 NMD->addOperand(MD);
Devang Patel27c87ff2009-07-29 22:34:41 +00001613 }
Devang Patel27c87ff2009-07-29 22:34:41 +00001614 break;
1615 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00001616 case bitc::METADATA_OLD_FN_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00001617 // FIXME: Remove in 4.0.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001618 // This is a LocalAsMetadata record, the only type of function-local
1619 // metadata.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001620 if (Record.size() % 2 == 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001621 return Error("Invalid record");
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001622
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001623 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1624 // to be legal, but there's no upgrade path.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001625 auto dropRecord = [&] {
1626 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1627 };
1628 if (Record.size() != 2) {
1629 dropRecord();
1630 break;
1631 }
1632
1633 Type *Ty = getTypeByID(Record[0]);
1634 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1635 dropRecord();
1636 break;
1637 }
1638
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001639 MDValueList.AssignValue(
1640 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1641 NextMDValueNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001642 break;
1643 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00001644 case bitc::METADATA_OLD_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00001645 // FIXME: Remove in 4.0.
Dan Gohman1e0213a2010-07-13 19:33:27 +00001646 if (Record.size() % 2 == 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001647 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001648
Devang Patele059ba6e2009-07-23 01:07:34 +00001649 unsigned Size = Record.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001650 SmallVector<Metadata *, 8> Elts;
Devang Patele059ba6e2009-07-23 01:07:34 +00001651 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00001652 Type *Ty = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00001653 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001654 return Error("Invalid record");
Chris Lattnerfdd87902009-10-05 05:54:46 +00001655 if (Ty->isMetadataTy())
Devang Patel05eb6172009-08-04 06:00:18 +00001656 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001657 else if (!Ty->isVoidTy()) {
1658 auto *MD =
1659 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1660 assert(isa<ConstantAsMetadata>(MD) &&
1661 "Expected non-function-local metadata");
1662 Elts.push_back(MD);
1663 } else
Craig Topper2617dcc2014-04-15 06:32:26 +00001664 Elts.push_back(nullptr);
Devang Patele059ba6e2009-07-23 01:07:34 +00001665 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001666 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
Devang Patele059ba6e2009-07-23 01:07:34 +00001667 break;
1668 }
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001669 case bitc::METADATA_VALUE: {
1670 if (Record.size() != 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001671 return Error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001672
1673 Type *Ty = getTypeByID(Record[0]);
1674 if (Ty->isMetadataTy() || Ty->isVoidTy())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001675 return Error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001676
1677 MDValueList.AssignValue(
1678 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1679 NextMDValueNo++);
1680 break;
1681 }
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001682 case bitc::METADATA_DISTINCT_NODE:
1683 IsDistinct = true;
1684 // fallthrough...
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001685 case bitc::METADATA_NODE: {
1686 SmallVector<Metadata *, 8> Elts;
1687 Elts.reserve(Record.size());
1688 for (unsigned ID : Record)
1689 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001690 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1691 : MDNode::get(Context, Elts),
1692 NextMDValueNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001693 break;
1694 }
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001695 case bitc::METADATA_LOCATION: {
1696 if (Record.size() != 5)
1697 return Error("Invalid record");
1698
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001699 unsigned Line = Record[1];
1700 unsigned Column = Record[2];
1701 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1702 Metadata *InlinedAt =
1703 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00001704 MDValueList.AssignValue(
1705 GET_OR_DISTINCT(MDLocation, Record[0],
1706 (Context, Line, Column, Scope, InlinedAt)),
1707 NextMDValueNo++);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001708 break;
1709 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001710 case bitc::METADATA_GENERIC_DEBUG: {
1711 if (Record.size() < 4)
1712 return Error("Invalid record");
1713
1714 unsigned Tag = Record[1];
1715 unsigned Version = Record[2];
1716
1717 if (Tag >= 1u << 16 || Version != 0)
1718 return Error("Invalid record");
1719
1720 auto *Header = getMDString(Record[3]);
1721 SmallVector<Metadata *, 8> DwarfOps;
1722 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1723 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1724 : nullptr);
1725 MDValueList.AssignValue(GET_OR_DISTINCT(GenericDebugNode, Record[0],
1726 (Context, Tag, Header, DwarfOps)),
1727 NextMDValueNo++);
1728 break;
1729 }
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001730 case bitc::METADATA_SUBRANGE: {
1731 if (Record.size() != 3)
1732 return Error("Invalid record");
1733
1734 MDValueList.AssignValue(
1735 GET_OR_DISTINCT(MDSubrange, Record[0],
1736 (Context, Record[1], unrotateSign(Record[2]))),
1737 NextMDValueNo++);
1738 break;
1739 }
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001740 case bitc::METADATA_ENUMERATOR: {
1741 if (Record.size() != 3)
1742 return Error("Invalid record");
1743
1744 MDValueList.AssignValue(GET_OR_DISTINCT(MDEnumerator, Record[0],
1745 (Context, unrotateSign(Record[1]),
1746 getMDString(Record[2]))),
1747 NextMDValueNo++);
1748 break;
1749 }
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001750 case bitc::METADATA_BASIC_TYPE: {
1751 if (Record.size() != 6)
1752 return Error("Invalid record");
1753
1754 MDValueList.AssignValue(
1755 GET_OR_DISTINCT(MDBasicType, Record[0],
1756 (Context, Record[1], getMDString(Record[2]),
1757 Record[3], Record[4], Record[5])),
1758 NextMDValueNo++);
1759 break;
1760 }
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001761 case bitc::METADATA_DERIVED_TYPE: {
1762 if (Record.size() != 12)
1763 return Error("Invalid record");
1764
1765 MDValueList.AssignValue(
1766 GET_OR_DISTINCT(MDDerivedType, Record[0],
1767 (Context, Record[1], getMDString(Record[2]),
1768 getMDOrNull(Record[3]), Record[4],
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001769 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1770 Record[7], Record[8], Record[9], Record[10],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001771 getMDOrNull(Record[11]))),
1772 NextMDValueNo++);
1773 break;
1774 }
1775 case bitc::METADATA_COMPOSITE_TYPE: {
1776 if (Record.size() != 16)
1777 return Error("Invalid record");
1778
1779 MDValueList.AssignValue(
1780 GET_OR_DISTINCT(MDCompositeType, Record[0],
1781 (Context, Record[1], getMDString(Record[2]),
1782 getMDOrNull(Record[3]), Record[4],
1783 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1784 Record[7], Record[8], Record[9], Record[10],
1785 getMDOrNull(Record[11]), Record[12],
1786 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1787 getMDString(Record[15]))),
1788 NextMDValueNo++);
1789 break;
1790 }
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001791 case bitc::METADATA_SUBROUTINE_TYPE: {
1792 if (Record.size() != 3)
1793 return Error("Invalid record");
1794
1795 MDValueList.AssignValue(
1796 GET_OR_DISTINCT(MDSubroutineType, Record[0],
1797 (Context, Record[1], getMDOrNull(Record[2]))),
1798 NextMDValueNo++);
1799 break;
1800 }
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001801 case bitc::METADATA_FILE: {
1802 if (Record.size() != 3)
1803 return Error("Invalid record");
1804
1805 MDValueList.AssignValue(
1806 GET_OR_DISTINCT(MDFile, Record[0], (Context, getMDString(Record[1]),
1807 getMDString(Record[2]))),
1808 NextMDValueNo++);
1809 break;
1810 }
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001811 case bitc::METADATA_COMPILE_UNIT: {
1812 if (Record.size() != 14)
1813 return Error("Invalid record");
1814
1815 MDValueList.AssignValue(
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001816 GET_OR_DISTINCT(MDCompileUnit, Record[0],
1817 (Context, Record[1], getMDOrNull(Record[2]),
1818 getMDString(Record[3]), Record[4],
1819 getMDString(Record[5]), Record[6],
1820 getMDString(Record[7]), Record[8],
1821 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1822 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1823 getMDOrNull(Record[13]))),
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001824 NextMDValueNo++);
1825 break;
1826 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001827 case bitc::METADATA_SUBPROGRAM: {
1828 if (Record.size() != 19)
1829 return Error("Invalid record");
1830
1831 MDValueList.AssignValue(
1832 GET_OR_DISTINCT(
1833 MDSubprogram, Record[0],
1834 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1835 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1836 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1837 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1838 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1839 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1840 NextMDValueNo++);
1841 break;
1842 }
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001843 case bitc::METADATA_LEXICAL_BLOCK: {
1844 if (Record.size() != 5)
1845 return Error("Invalid record");
1846
1847 MDValueList.AssignValue(
1848 GET_OR_DISTINCT(MDLexicalBlock, Record[0],
1849 (Context, getMDOrNull(Record[1]),
1850 getMDOrNull(Record[2]), Record[3], Record[4])),
1851 NextMDValueNo++);
1852 break;
1853 }
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001854 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1855 if (Record.size() != 4)
1856 return Error("Invalid record");
1857
1858 MDValueList.AssignValue(
1859 GET_OR_DISTINCT(MDLexicalBlockFile, Record[0],
1860 (Context, getMDOrNull(Record[1]),
1861 getMDOrNull(Record[2]), Record[3])),
1862 NextMDValueNo++);
1863 break;
1864 }
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001865 case bitc::METADATA_NAMESPACE: {
1866 if (Record.size() != 5)
1867 return Error("Invalid record");
1868
1869 MDValueList.AssignValue(
1870 GET_OR_DISTINCT(MDNamespace, Record[0],
1871 (Context, getMDOrNull(Record[1]),
1872 getMDOrNull(Record[2]), getMDString(Record[3]),
1873 Record[4])),
1874 NextMDValueNo++);
1875 break;
1876 }
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001877 case bitc::METADATA_TEMPLATE_TYPE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00001878 if (Record.size() != 3)
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001879 return Error("Invalid record");
1880
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00001881 MDValueList.AssignValue(GET_OR_DISTINCT(MDTemplateTypeParameter,
1882 Record[0],
1883 (Context, getMDString(Record[1]),
1884 getMDOrNull(Record[2]))),
1885 NextMDValueNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001886 break;
1887 }
1888 case bitc::METADATA_TEMPLATE_VALUE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00001889 if (Record.size() != 5)
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001890 return Error("Invalid record");
1891
1892 MDValueList.AssignValue(
1893 GET_OR_DISTINCT(MDTemplateValueParameter, Record[0],
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00001894 (Context, Record[1], getMDString(Record[2]),
1895 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001896 NextMDValueNo++);
1897 break;
1898 }
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001899 case bitc::METADATA_GLOBAL_VAR: {
1900 if (Record.size() != 11)
1901 return Error("Invalid record");
1902
1903 MDValueList.AssignValue(
1904 GET_OR_DISTINCT(MDGlobalVariable, Record[0],
1905 (Context, getMDOrNull(Record[1]),
1906 getMDString(Record[2]), getMDString(Record[3]),
1907 getMDOrNull(Record[4]), Record[5],
1908 getMDOrNull(Record[6]), Record[7], Record[8],
1909 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1910 NextMDValueNo++);
1911 break;
1912 }
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001913 case bitc::METADATA_LOCAL_VAR: {
1914 if (Record.size() != 10)
1915 return Error("Invalid record");
1916
1917 MDValueList.AssignValue(
1918 GET_OR_DISTINCT(MDLocalVariable, Record[0],
1919 (Context, Record[1], getMDOrNull(Record[2]),
1920 getMDString(Record[3]), getMDOrNull(Record[4]),
1921 Record[5], getMDOrNull(Record[6]), Record[7],
1922 Record[8], getMDOrNull(Record[9]))),
1923 NextMDValueNo++);
1924 break;
1925 }
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001926 case bitc::METADATA_EXPRESSION: {
1927 if (Record.size() < 1)
1928 return Error("Invalid record");
1929
1930 MDValueList.AssignValue(
1931 GET_OR_DISTINCT(MDExpression, Record[0],
1932 (Context, makeArrayRef(Record).slice(1))),
1933 NextMDValueNo++);
1934 break;
1935 }
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001936 case bitc::METADATA_OBJC_PROPERTY: {
1937 if (Record.size() != 8)
1938 return Error("Invalid record");
1939
1940 MDValueList.AssignValue(
1941 GET_OR_DISTINCT(MDObjCProperty, Record[0],
1942 (Context, getMDString(Record[1]),
1943 getMDOrNull(Record[2]), Record[3],
1944 getMDString(Record[4]), getMDString(Record[5]),
1945 Record[6], getMDOrNull(Record[7]))),
1946 NextMDValueNo++);
1947 break;
1948 }
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001949 case bitc::METADATA_IMPORTED_ENTITY: {
1950 if (Record.size() != 6)
1951 return Error("Invalid record");
1952
1953 MDValueList.AssignValue(
1954 GET_OR_DISTINCT(MDImportedEntity, Record[0],
1955 (Context, Record[1], getMDOrNull(Record[2]),
1956 getMDOrNull(Record[3]), Record[4],
1957 getMDString(Record[5]))),
1958 NextMDValueNo++);
1959 break;
1960 }
Devang Patel7428d8a2009-07-22 17:43:22 +00001961 case bitc::METADATA_STRING: {
Eli Bendersky5d5e18d2014-06-25 15:41:00 +00001962 std::string String(Record.begin(), Record.end());
1963 llvm::UpgradeMDStringConstant(String);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001964 Metadata *MD = MDString::get(Context, String);
1965 MDValueList.AssignValue(MD, NextMDValueNo++);
Devang Patel7428d8a2009-07-22 17:43:22 +00001966 break;
1967 }
Devang Patelaf206b82009-09-18 19:26:43 +00001968 case bitc::METADATA_KIND: {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001969 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001970 return Error("Invalid record");
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001971
Devang Patelb1a44772009-09-28 21:14:55 +00001972 unsigned Kind = Record[0];
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001973 SmallString<8> Name(Record.begin()+1, Record.end());
1974
Chris Lattnera0566972009-12-29 09:01:33 +00001975 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman43aa8f02010-07-20 21:42:28 +00001976 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001977 return Error("Conflicting METADATA_KIND records");
Devang Patelaf206b82009-09-18 19:26:43 +00001978 break;
1979 }
Devang Patel7428d8a2009-07-22 17:43:22 +00001980 }
1981 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001982#undef GET_OR_DISTINCT
Devang Patel7428d8a2009-07-22 17:43:22 +00001983}
1984
Jan Wen Voungafaced02012-10-11 20:20:40 +00001985/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
Chris Lattner08feb1e2007-04-24 04:04:35 +00001986/// the LSB for dense VBR encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00001987uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00001988 if ((V & 1) == 0)
1989 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001990 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00001991 return -(V >> 1);
1992 // There is no such thing as -0 with integers. "-0" really means MININT.
1993 return 1ULL << 63;
1994}
1995
Chris Lattner44c17072007-04-26 02:46:40 +00001996/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1997/// values and aliases that we can.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001998std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00001999 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2000 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002001 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002002 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002003
Chris Lattner44c17072007-04-26 02:46:40 +00002004 GlobalInitWorklist.swap(GlobalInits);
2005 AliasInitWorklist.swap(AliasInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002006 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002007 FunctionPrologueWorklist.swap(FunctionPrologues);
Chris Lattner44c17072007-04-26 02:46:40 +00002008
2009 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00002010 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002011 if (ValID >= ValueList.size()) {
2012 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00002013 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002014 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002015 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00002016 GlobalInitWorklist.back().first->setInitializer(C);
2017 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002018 return Error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00002019 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002020 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002021 }
2022
2023 while (!AliasInitWorklist.empty()) {
2024 unsigned ValID = AliasInitWorklist.back().second;
2025 if (ValID >= ValueList.size()) {
2026 AliasInits.push_back(AliasInitWorklist.back());
2027 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002028 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Rafael Espindola64c1e182014-06-03 02:41:57 +00002029 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner44c17072007-04-26 02:46:40 +00002030 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002031 return Error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00002032 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002033 AliasInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002034 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002035
2036 while (!FunctionPrefixWorklist.empty()) {
2037 unsigned ValID = FunctionPrefixWorklist.back().second;
2038 if (ValID >= ValueList.size()) {
2039 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2040 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002041 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002042 FunctionPrefixWorklist.back().first->setPrefixData(C);
2043 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002044 return Error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002045 }
2046 FunctionPrefixWorklist.pop_back();
2047 }
2048
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002049 while (!FunctionPrologueWorklist.empty()) {
2050 unsigned ValID = FunctionPrologueWorklist.back().second;
2051 if (ValID >= ValueList.size()) {
2052 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2053 } else {
2054 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2055 FunctionPrologueWorklist.back().first->setPrologueData(C);
2056 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002057 return Error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002058 }
2059 FunctionPrologueWorklist.pop_back();
2060 }
2061
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002062 return std::error_code();
Chris Lattner44c17072007-04-26 02:46:40 +00002063}
2064
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002065static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2066 SmallVector<uint64_t, 8> Words(Vals.size());
2067 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00002068 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002069
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002070 return APInt(TypeBits, Words);
2071}
2072
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002073std::error_code BitcodeReader::ParseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002074 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002075 return Error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002076
2077 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002078
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002079 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00002080 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00002081 unsigned NextCstNo = ValueList.size();
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002082 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002083 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002084
Chris Lattner27d38752013-01-20 02:13:19 +00002085 switch (Entry.Kind) {
2086 case BitstreamEntry::SubBlock: // Handled for us already.
2087 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002088 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002089 case BitstreamEntry::EndBlock:
2090 if (NextCstNo != ValueList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002091 return Error("Invalid ronstant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00002092
Chris Lattner27d38752013-01-20 02:13:19 +00002093 // Once all the constants have been read, go through and resolve forward
2094 // references.
2095 ValueList.ResolveConstantForwardRefs();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002096 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002097 case BitstreamEntry::Record:
2098 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00002099 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002100 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002101
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002102 // Read a record.
2103 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00002104 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002105 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002106 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002107 default: // Default behavior: unknown constant
2108 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00002109 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002110 break;
2111 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2112 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002113 return Error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00002114 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002115 return Error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002116 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00002117 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002118 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00002119 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002120 break;
2121 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002122 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002123 return Error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002124 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00002125 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00002126 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002127 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002128 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002129
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002130 APInt VInt = ReadWideAPInt(Record,
2131 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002132 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002133
Chris Lattner08feb1e2007-04-24 04:04:35 +00002134 break;
2135 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002136 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00002137 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002138 return Error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00002139 if (CurTy->isHalfTy())
Tim Northover29178a32013-01-22 09:46:31 +00002140 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2141 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00002142 else if (CurTy->isFloatTy())
Tim Northover29178a32013-01-22 09:46:31 +00002143 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2144 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002145 else if (CurTy->isDoubleTy())
Tim Northover29178a32013-01-22 09:46:31 +00002146 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2147 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002148 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00002149 // Bits are not stored the same way as a normal i80 APInt, compensate.
2150 uint64_t Rearrange[2];
2151 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2152 Rearrange[1] = Record[0] >> 48;
Tim Northover29178a32013-01-22 09:46:31 +00002153 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2154 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002155 } else if (CurTy->isFP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002156 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2157 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002158 else if (CurTy->isPPC_FP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002159 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2160 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002161 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00002162 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002163 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00002164 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002165
Chris Lattnere14cb882007-05-04 19:11:41 +00002166 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2167 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002168 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002169
Chris Lattnere14cb882007-05-04 19:11:41 +00002170 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00002171 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002172
Chris Lattner229907c2011-07-18 04:54:35 +00002173 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00002174 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002175 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00002176 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00002177 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002178 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2179 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002180 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002181 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00002182 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002183 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2184 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002185 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002186 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00002187 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00002188 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002189 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00002190 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002191 break;
2192 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002193 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00002194 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2195 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002196 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002197
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002198 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002199 V = ConstantDataArray::getString(Context, Elts,
2200 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00002201 break;
2202 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002203 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2204 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002205 return Error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002206
Chris Lattner372dd1e2012-01-30 00:51:16 +00002207 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2208 unsigned Size = Record.size();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002209
Chris Lattner372dd1e2012-01-30 00:51:16 +00002210 if (EltTy->isIntegerTy(8)) {
2211 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2212 if (isa<VectorType>(CurTy))
2213 V = ConstantDataVector::get(Context, Elts);
2214 else
2215 V = ConstantDataArray::get(Context, Elts);
2216 } else if (EltTy->isIntegerTy(16)) {
2217 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2218 if (isa<VectorType>(CurTy))
2219 V = ConstantDataVector::get(Context, Elts);
2220 else
2221 V = ConstantDataArray::get(Context, Elts);
2222 } else if (EltTy->isIntegerTy(32)) {
2223 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2224 if (isa<VectorType>(CurTy))
2225 V = ConstantDataVector::get(Context, Elts);
2226 else
2227 V = ConstantDataArray::get(Context, Elts);
2228 } else if (EltTy->isIntegerTy(64)) {
2229 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2230 if (isa<VectorType>(CurTy))
2231 V = ConstantDataVector::get(Context, Elts);
2232 else
2233 V = ConstantDataArray::get(Context, Elts);
2234 } else if (EltTy->isFloatTy()) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002235 SmallVector<float, 16> Elts(Size);
2236 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002237 if (isa<VectorType>(CurTy))
2238 V = ConstantDataVector::get(Context, Elts);
2239 else
2240 V = ConstantDataArray::get(Context, Elts);
2241 } else if (EltTy->isDoubleTy()) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002242 SmallVector<double, 16> Elts(Size);
2243 std::transform(Record.begin(), Record.end(), Elts.begin(),
2244 BitsToDouble);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002245 if (isa<VectorType>(CurTy))
2246 V = ConstantDataVector::get(Context, Elts);
2247 else
2248 V = ConstantDataArray::get(Context, Elts);
2249 } else {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002250 return Error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00002251 }
2252 break;
2253 }
2254
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002255 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002256 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002257 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002258 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002259 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002260 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00002261 } else {
2262 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2263 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00002264 unsigned Flags = 0;
2265 if (Record.size() >= 4) {
2266 if (Opc == Instruction::Add ||
2267 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002268 Opc == Instruction::Mul ||
2269 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00002270 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2271 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2272 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2273 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002274 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002275 Opc == Instruction::UDiv ||
2276 Opc == Instruction::LShr ||
2277 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00002278 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00002279 Flags |= SDivOperator::IsExact;
2280 }
2281 }
2282 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00002283 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002284 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002285 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002286 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002287 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002288 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002289 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00002290 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002291 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00002292 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002293 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002294 if (!OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002295 return Error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00002296 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002297 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2298 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002299 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002300 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002301 }
Dan Gohman1639c392009-07-27 21:53:46 +00002302 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002303 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
David Blaikieb9263572015-03-13 21:03:36 +00002304 unsigned OpNum = 0;
2305 Type *PointeeType = nullptr;
2306 if (Record.size() % 2)
2307 PointeeType = getTypeByID(Record[OpNum++]);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002308 SmallVector<Constant*, 16> Elts;
David Blaikieb9263572015-03-13 21:03:36 +00002309 while (OpNum != Record.size()) {
2310 Type *ElTy = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002311 if (!ElTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002312 return Error("Invalid record");
David Blaikieb9263572015-03-13 21:03:36 +00002313 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002314 }
David Blaikieb9263572015-03-13 21:03:36 +00002315
Jay Foaded8db7d2011-07-21 14:31:17 +00002316 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
Jay Foad2f5fc8c2011-07-21 15:15:37 +00002317 V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2318 BitCode ==
2319 bitc::CST_CODE_CE_INBOUNDS_GEP);
David Blaikieb9263572015-03-13 21:03:36 +00002320 if (PointeeType &&
2321 PointeeType != cast<GEPOperator>(V)->getSourceElementType())
David Blaikie12cf5d702015-03-16 22:03:50 +00002322 return Error("Explicit gep operator type does not match pointee type "
2323 "of pointer operand");
Chris Lattner890683d2007-04-24 18:15:21 +00002324 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002325 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00002326 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002327 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002328 return Error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00002329
2330 Type *SelectorTy = Type::getInt1Ty(Context);
2331
2332 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
2333 // vector. Otherwise, it must be a single bit.
2334 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2335 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
2336 VTy->getNumElements());
2337
2338 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2339 SelectorTy),
2340 ValueList.getConstantFwdRef(Record[1],CurTy),
2341 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002342 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00002343 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002344 case bitc::CST_CODE_CE_EXTRACTELT
2345 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002346 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002347 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002348 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002349 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002350 if (!OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002351 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002352 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002353 Constant *Op1 = nullptr;
2354 if (Record.size() == 4) {
2355 Type *IdxTy = getTypeByID(Record[2]);
2356 if (!IdxTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002357 return Error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002358 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2359 } else // TODO: Remove with llvm 4.0
2360 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2361 if (!Op1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002362 return Error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002363 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002364 break;
2365 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002366 case bitc::CST_CODE_CE_INSERTELT
2367 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002368 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002369 if (Record.size() < 3 || !OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002370 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002371 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2372 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2373 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002374 Constant *Op2 = nullptr;
2375 if (Record.size() == 4) {
2376 Type *IdxTy = getTypeByID(Record[2]);
2377 if (!IdxTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002378 return Error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002379 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2380 } else // TODO: Remove with llvm 4.0
2381 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2382 if (!Op2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002383 return Error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002384 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002385 break;
2386 }
2387 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002388 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002389 if (Record.size() < 3 || !OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002390 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002391 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2392 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002393 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002394 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002395 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002396 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002397 break;
2398 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00002399 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002400 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2401 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00002402 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002403 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002404 return Error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002405 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2406 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002407 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002408 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00002409 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002410 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00002411 break;
2412 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002413 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002414 if (Record.size() < 4)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002415 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002416 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002417 if (!OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002418 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002419 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2420 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2421
Duncan Sands9dff9be2010-02-15 16:12:20 +00002422 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002423 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00002424 else
Owen Anderson487375e2009-07-29 18:55:55 +00002425 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002426 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00002427 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002428 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00002429 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002430 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002431 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002432 return Error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002433 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00002434 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002435 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002436 unsigned AsmStrSize = Record[1];
2437 if (2+AsmStrSize >= Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002438 return Error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002439 unsigned ConstStrSize = Record[2+AsmStrSize];
2440 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002441 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002442
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002443 for (unsigned i = 0; i != AsmStrSize; ++i)
2444 AsmStr += (char)Record[2+i];
2445 for (unsigned i = 0; i != ConstStrSize; ++i)
2446 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00002447 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002448 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002449 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002450 break;
2451 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002452 // This version adds support for the asm dialect keywords (e.g.,
2453 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002454 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002455 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002456 return Error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002457 std::string AsmStr, ConstrStr;
2458 bool HasSideEffects = Record[0] & 1;
2459 bool IsAlignStack = (Record[0] >> 1) & 1;
2460 unsigned AsmDialect = Record[0] >> 2;
2461 unsigned AsmStrSize = Record[1];
2462 if (2+AsmStrSize >= Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002463 return Error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002464 unsigned ConstStrSize = Record[2+AsmStrSize];
2465 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002466 return Error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002467
2468 for (unsigned i = 0; i != AsmStrSize; ++i)
2469 AsmStr += (char)Record[2+i];
2470 for (unsigned i = 0; i != ConstStrSize; ++i)
2471 ConstrStr += (char)Record[3+AsmStrSize+i];
2472 PointerType *PTy = cast<PointerType>(CurTy);
2473 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2474 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00002475 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002476 break;
2477 }
Chris Lattner5956dc82009-10-28 05:53:48 +00002478 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00002479 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002480 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002481 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002482 if (!FnTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002483 return Error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00002484 Function *Fn =
2485 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00002486 if (!Fn)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002487 return Error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002488
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00002489 // Don't let Fn get dematerialized.
2490 BlockAddressesTaken.insert(Fn);
2491
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002492 // If the function is already parsed we can insert the block address right
2493 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002494 BasicBlock *BB;
2495 unsigned BBID = Record[2];
2496 if (!BBID)
2497 // Invalid reference to entry block.
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002498 return Error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002499 if (!Fn->empty()) {
2500 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002501 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002502 if (BBI == BBE)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002503 return Error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002504 ++BBI;
2505 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002506 BB = BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002507 } else {
2508 // Otherwise insert a placeholder and remember it so it can be inserted
2509 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00002510 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2511 if (FwdBBs.empty())
2512 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00002513 if (FwdBBs.size() < BBID + 1)
2514 FwdBBs.resize(BBID + 1);
2515 if (!FwdBBs[BBID])
2516 FwdBBs[BBID] = BasicBlock::Create(Context);
2517 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002518 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002519 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00002520 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002521 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002522 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002523
Chris Lattner83930552007-05-01 07:01:57 +00002524 ValueList.AssignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00002525 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002526 }
2527}
Chris Lattner1314b992007-04-22 06:23:29 +00002528
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002529std::error_code BitcodeReader::ParseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00002530 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002531 return Error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00002532
Chad Rosierca2567b2011-12-07 21:44:12 +00002533 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002534 SmallVector<uint64_t, 64> Record;
Chad Rosierca2567b2011-12-07 21:44:12 +00002535 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002536 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002537
Chris Lattner27d38752013-01-20 02:13:19 +00002538 switch (Entry.Kind) {
2539 case BitstreamEntry::SubBlock: // Handled for us already.
2540 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002541 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002542 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002543 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002544 case BitstreamEntry::Record:
2545 // The interesting case.
2546 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00002547 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002548
Chad Rosierca2567b2011-12-07 21:44:12 +00002549 // Read a use list record.
2550 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002551 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00002552 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00002553 default: // Default behavior: unknown type.
2554 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002555 case bitc::USELIST_CODE_BB:
2556 IsBB = true;
2557 // fallthrough
2558 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00002559 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002560 if (RecordLength < 3)
2561 // Records should have at least an ID and two indexes.
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002562 return Error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002563 unsigned ID = Record.back();
2564 Record.pop_back();
2565
2566 Value *V;
2567 if (IsBB) {
2568 assert(ID < FunctionBBs.size() && "Basic block not found");
2569 V = FunctionBBs[ID];
2570 } else
2571 V = ValueList[ID];
2572 unsigned NumUses = 0;
2573 SmallDenseMap<const Use *, unsigned, 16> Order;
2574 for (const Use &U : V->uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00002575 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002576 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00002577 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002578 }
2579 if (Order.size() != Record.size() || NumUses > Record.size())
2580 // Mismatches can happen if the functions are being materialized lazily
2581 // (out-of-order), or a value has been upgraded.
2582 break;
2583
2584 V->sortUseList([&](const Use &L, const Use &R) {
2585 return Order.lookup(&L) < Order.lookup(&R);
2586 });
Chad Rosierca2567b2011-12-07 21:44:12 +00002587 break;
2588 }
2589 }
2590 }
2591}
2592
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002593/// When we see the block for metadata, remember where it is and then skip it.
2594/// This lets us lazily deserialize the metadata.
2595std::error_code BitcodeReader::rememberAndSkipMetadata() {
2596 // Save the current stream state.
2597 uint64_t CurBit = Stream.GetCurrentBitNo();
2598 DeferredMetadataInfo.push_back(CurBit);
2599
2600 // Skip over the block for now.
2601 if (Stream.SkipBlock())
2602 return Error("Invalid record");
2603 return std::error_code();
2604}
2605
2606std::error_code BitcodeReader::materializeMetadata() {
2607 for (uint64_t BitPos : DeferredMetadataInfo) {
2608 // Move the bit stream to the saved position.
2609 Stream.JumpToBit(BitPos);
2610 if (std::error_code EC = ParseMetadata())
2611 return EC;
2612 }
2613 DeferredMetadataInfo.clear();
2614 return std::error_code();
2615}
2616
Rafael Espindola468b8682015-04-01 14:44:59 +00002617void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00002618
Chris Lattner85b7b402007-05-01 05:52:21 +00002619/// RememberAndSkipFunctionBody - When we see the block for a function body,
2620/// remember where it is and then skip it. This lets us lazily deserialize the
2621/// functions.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002622std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002623 // Get the function we are talking about.
2624 if (FunctionsWithBodies.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002625 return Error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002626
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002627 Function *Fn = FunctionsWithBodies.back();
2628 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002629
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002630 // Save the current stream state.
2631 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00002632 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002633
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002634 // Skip over the function block for now.
2635 if (Stream.SkipBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002636 return Error("Invalid record");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002637 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002638}
2639
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002640std::error_code BitcodeReader::GlobalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002641 // Patch the initializers for globals and aliases up.
2642 ResolveGlobalAndAliasInits();
2643 if (!GlobalInits.empty() || !AliasInits.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002644 return Error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002645
2646 // Look for intrinsic functions which need to be upgraded at some point
2647 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2648 FI != FE; ++FI) {
2649 Function *NewFn;
2650 if (UpgradeIntrinsicFunction(FI, NewFn))
2651 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
2652 }
2653
2654 // Look for global variables which need to be renamed.
2655 for (Module::global_iterator
2656 GI = TheModule->global_begin(), GE = TheModule->global_end();
Reid Klecknerfceb76f2014-05-16 20:39:27 +00002657 GI != GE;) {
2658 GlobalVariable *GV = GI++;
2659 UpgradeGlobalVariable(GV);
2660 }
2661
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002662 // Force deallocation of memory for these vectors to favor the client that
2663 // want lazy deserialization.
2664 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2665 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002666 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002667}
2668
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002669std::error_code BitcodeReader::ParseModule(bool Resume,
2670 bool ShouldLazyLoadMetadata) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002671 if (Resume)
2672 Stream.JumpToBit(NextUnreadBit);
2673 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002674 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002675
Chris Lattner1314b992007-04-22 06:23:29 +00002676 SmallVector<uint64_t, 64> Record;
2677 std::vector<std::string> SectionTable;
Gordon Henriksend930f912008-08-17 18:44:35 +00002678 std::vector<std::string> GCTable;
Chris Lattner1314b992007-04-22 06:23:29 +00002679
2680 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00002681 while (1) {
2682 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00002683
Chris Lattner27d38752013-01-20 02:13:19 +00002684 switch (Entry.Kind) {
2685 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002686 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002687 case BitstreamEntry::EndBlock:
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002688 return GlobalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00002689
Chris Lattner27d38752013-01-20 02:13:19 +00002690 case BitstreamEntry::SubBlock:
2691 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00002692 default: // Skip unknown content.
2693 if (Stream.SkipBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002694 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002695 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00002696 case bitc::BLOCKINFO_BLOCK_ID:
2697 if (Stream.ReadBlockInfoBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002698 return Error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00002699 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00002700 case bitc::PARAMATTR_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002701 if (std::error_code EC = ParseAttributeBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002702 return EC;
Chris Lattnerfee5a372007-05-04 03:30:17 +00002703 break;
Bill Wendlingba629332013-02-10 23:24:25 +00002704 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002705 if (std::error_code EC = ParseAttributeGroupBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002706 return EC;
Bill Wendlingba629332013-02-10 23:24:25 +00002707 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002708 case bitc::TYPE_BLOCK_ID_NEW:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002709 if (std::error_code EC = ParseTypeTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002710 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00002711 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00002712 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002713 if (std::error_code EC = ParseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002714 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002715 SeenValueSymbolTable = true;
Chris Lattnerccaa4482007-04-23 21:26:05 +00002716 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002717 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002718 if (std::error_code EC = ParseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002719 return EC;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002720 if (std::error_code EC = ResolveGlobalAndAliasInits())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002721 return EC;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002722 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00002723 case bitc::METADATA_BLOCK_ID:
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002724 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2725 if (std::error_code EC = rememberAndSkipMetadata())
2726 return EC;
2727 break;
2728 }
2729 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002730 if (std::error_code EC = ParseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002731 return EC;
Devang Patel7428d8a2009-07-22 17:43:22 +00002732 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002733 case bitc::FUNCTION_BLOCK_ID:
2734 // If this is the first function body we've seen, reverse the
2735 // FunctionsWithBodies list.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002736 if (!SeenFirstFunctionBody) {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002737 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002738 if (std::error_code EC = GlobalCleanup())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002739 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002740 SeenFirstFunctionBody = true;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002741 }
Joe Abbey97b7a172013-02-06 22:14:06 +00002742
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002743 if (std::error_code EC = RememberAndSkipFunctionBody())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002744 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002745 // For streaming bitcode, suspend parsing when we reach the function
2746 // bodies. Subsequent materialization calls will resume it when
2747 // necessary. For streaming, the function bodies must be at the end of
2748 // the bitcode. If the bitcode file is old, the symbol table will be
2749 // at the end instead and will not have been seen yet. In this case,
2750 // just finish the parse now.
2751 if (LazyStreamer && SeenValueSymbolTable) {
2752 NextUnreadBit = Stream.GetCurrentBitNo();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002753 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002754 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002755 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00002756 case bitc::USELIST_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002757 if (std::error_code EC = ParseUseLists())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002758 return EC;
Chad Rosierca2567b2011-12-07 21:44:12 +00002759 break;
Chris Lattner1314b992007-04-22 06:23:29 +00002760 }
2761 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00002762
Chris Lattner27d38752013-01-20 02:13:19 +00002763 case BitstreamEntry::Record:
2764 // The interesting case.
2765 break;
Chris Lattner1314b992007-04-22 06:23:29 +00002766 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002767
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002768
Chris Lattner1314b992007-04-22 06:23:29 +00002769 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00002770 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner1314b992007-04-22 06:23:29 +00002771 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002772 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattner1314b992007-04-22 06:23:29 +00002773 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002774 return Error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002775 // Only version #0 and #1 are supported so far.
2776 unsigned module_version = Record[0];
2777 switch (module_version) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002778 default:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002779 return Error("Invalid value");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002780 case 0:
2781 UseRelativeIDs = false;
2782 break;
2783 case 1:
2784 UseRelativeIDs = true;
2785 break;
2786 }
Chris Lattner1314b992007-04-22 06:23:29 +00002787 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00002788 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002789 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002790 std::string S;
2791 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002792 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002793 TheModule->setTargetTriple(S);
2794 break;
2795 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002796 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002797 std::string S;
2798 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002799 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002800 TheModule->setDataLayout(S);
2801 break;
2802 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002803 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002804 std::string S;
2805 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002806 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002807 TheModule->setModuleInlineAsm(S);
2808 break;
2809 }
Bill Wendling706d3d62012-11-28 08:41:48 +00002810 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2811 // FIXME: Remove in 4.0.
2812 std::string S;
2813 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002814 return Error("Invalid record");
Bill Wendling706d3d62012-11-28 08:41:48 +00002815 // Ignore value.
2816 break;
2817 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002818 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002819 std::string S;
2820 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002821 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002822 SectionTable.push_back(S);
2823 break;
2824 }
Gordon Henriksend930f912008-08-17 18:44:35 +00002825 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00002826 std::string S;
2827 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002828 return Error("Invalid record");
Gordon Henriksend930f912008-08-17 18:44:35 +00002829 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00002830 break;
2831 }
David Majnemerdad0a642014-06-27 18:19:56 +00002832 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2833 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002834 return Error("Invalid record");
David Majnemerdad0a642014-06-27 18:19:56 +00002835 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2836 unsigned ComdatNameSize = Record[1];
2837 std::string ComdatName;
2838 ComdatName.reserve(ComdatNameSize);
2839 for (unsigned i = 0; i != ComdatNameSize; ++i)
2840 ComdatName += (char)Record[2 + i];
2841 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2842 C->setSelectionKind(SK);
2843 ComdatList.push_back(C);
2844 break;
2845 }
Christopher Lamb54dd24c2007-12-11 08:59:05 +00002846 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00002847 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00002848 // unnamed_addr, externally_initialized, dllstorageclass,
2849 // comdat]
Chris Lattner1314b992007-04-22 06:23:29 +00002850 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner4b00d922007-04-23 16:04:05 +00002851 if (Record.size() < 6)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002852 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002853 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002854 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002855 return Error("Invalid record");
Duncan Sands19d0b472010-02-16 11:11:14 +00002856 if (!Ty->isPointerTy())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002857 return Error("Invalid type for value");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00002858 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattner1314b992007-04-22 06:23:29 +00002859 Ty = cast<PointerType>(Ty)->getElementType();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002860
Chris Lattner1314b992007-04-22 06:23:29 +00002861 bool isConstant = Record[1];
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002862 uint64_t RawLinkage = Record[3];
2863 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
JF Bastien30bf96b2015-02-22 19:32:03 +00002864 unsigned Alignment;
2865 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
2866 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00002867 std::string Section;
2868 if (Record[5]) {
2869 if (Record[5]-1 >= SectionTable.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002870 return Error("Invalid ID");
Chris Lattner1314b992007-04-22 06:23:29 +00002871 Section = SectionTable[Record[5]-1];
2872 }
Chris Lattner4b00d922007-04-23 16:04:05 +00002873 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00002874 // Local linkage must have default visibility.
2875 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2876 // FIXME: Change to an error if non-default in 4.0.
Chris Lattner53862f72007-05-06 19:27:46 +00002877 Visibility = GetDecodedVisibility(Record[6]);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00002878
2879 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner53862f72007-05-06 19:27:46 +00002880 if (Record.size() > 7)
Hans Wennborgcbe34b42012-06-23 11:37:03 +00002881 TLM = GetDecodedThreadLocalMode(Record[7]);
Chris Lattner1314b992007-04-22 06:23:29 +00002882
Rafael Espindola45e6c192011-01-08 16:42:36 +00002883 bool UnnamedAddr = false;
2884 if (Record.size() > 8)
2885 UnnamedAddr = Record[8];
2886
Michael Gottesman27e7ef32013-02-05 05:57:38 +00002887 bool ExternallyInitialized = false;
2888 if (Record.size() > 9)
2889 ExternallyInitialized = Record[9];
2890
Chris Lattner1314b992007-04-22 06:23:29 +00002891 GlobalVariable *NewGV =
Craig Topper2617dcc2014-04-15 06:32:26 +00002892 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
Michael Gottesman27e7ef32013-02-05 05:57:38 +00002893 TLM, AddressSpace, ExternallyInitialized);
Chris Lattner1314b992007-04-22 06:23:29 +00002894 NewGV->setAlignment(Alignment);
2895 if (!Section.empty())
2896 NewGV->setSection(Section);
2897 NewGV->setVisibility(Visibility);
Rafael Espindola45e6c192011-01-08 16:42:36 +00002898 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002899
Nico Rieck7157bb72014-01-14 15:22:47 +00002900 if (Record.size() > 10)
2901 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2902 else
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002903 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00002904
Chris Lattnerccaa4482007-04-23 21:26:05 +00002905 ValueList.push_back(NewGV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002906
Chris Lattner47d131b2007-04-24 00:18:21 +00002907 // Remember which value to use for the global initializer.
2908 if (unsigned InitID = Record[2])
2909 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
David Majnemerdad0a642014-06-27 18:19:56 +00002910
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002911 if (Record.size() > 11) {
David Majnemerdad0a642014-06-27 18:19:56 +00002912 if (unsigned ComdatID = Record[11]) {
2913 assert(ComdatID <= ComdatList.size());
2914 NewGV->setComdat(ComdatList[ComdatID - 1]);
2915 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002916 } else if (hasImplicitComdat(RawLinkage)) {
2917 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2918 }
Chris Lattner1314b992007-04-22 06:23:29 +00002919 break;
2920 }
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002921 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Nico Rieck7157bb72014-01-14 15:22:47 +00002922 // alignment, section, visibility, gc, unnamed_addr,
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002923 // prologuedata, dllstorageclass, comdat, prefixdata]
Chris Lattner1314b992007-04-22 06:23:29 +00002924 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002925 if (Record.size() < 8)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002926 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002927 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002928 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002929 return Error("Invalid record");
Duncan Sands19d0b472010-02-16 11:11:14 +00002930 if (!Ty->isPointerTy())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002931 return Error("Invalid type for value");
Chris Lattner229907c2011-07-18 04:54:35 +00002932 FunctionType *FTy =
Chris Lattner1314b992007-04-22 06:23:29 +00002933 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2934 if (!FTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002935 return Error("Invalid type for value");
Chris Lattner1314b992007-04-22 06:23:29 +00002936
Gabor Greife9ecc682008-04-06 20:25:17 +00002937 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2938 "", TheModule);
Chris Lattner1314b992007-04-22 06:23:29 +00002939
Sandeep Patel68c5f472009-09-02 08:44:58 +00002940 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002941 bool isProto = Record[2];
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002942 uint64_t RawLinkage = Record[3];
2943 Func->setLinkage(getDecodedLinkage(RawLinkage));
Devang Patel4c758ea2008-09-25 21:00:45 +00002944 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002945
JF Bastien30bf96b2015-02-22 19:32:03 +00002946 unsigned Alignment;
2947 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
2948 return EC;
2949 Func->setAlignment(Alignment);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002950 if (Record[6]) {
2951 if (Record[6]-1 >= SectionTable.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002952 return Error("Invalid ID");
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002953 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattner1314b992007-04-22 06:23:29 +00002954 }
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00002955 // Local linkage must have default visibility.
2956 if (!Func->hasLocalLinkage())
2957 // FIXME: Change to an error if non-default in 4.0.
2958 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen71183b62007-12-10 03:18:06 +00002959 if (Record.size() > 8 && Record[8]) {
Gordon Henriksend930f912008-08-17 18:44:35 +00002960 if (Record[8]-1 > GCTable.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002961 return Error("Invalid ID");
Gordon Henriksend930f912008-08-17 18:44:35 +00002962 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen71183b62007-12-10 03:18:06 +00002963 }
Rafael Espindola45e6c192011-01-08 16:42:36 +00002964 bool UnnamedAddr = false;
2965 if (Record.size() > 9)
2966 UnnamedAddr = Record[9];
2967 Func->setUnnamedAddr(UnnamedAddr);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002968 if (Record.size() > 10 && Record[10] != 0)
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002969 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
Nico Rieck7157bb72014-01-14 15:22:47 +00002970
2971 if (Record.size() > 11)
2972 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
2973 else
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002974 UpgradeDLLImportExportLinkage(Func, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00002975
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002976 if (Record.size() > 12) {
David Majnemerdad0a642014-06-27 18:19:56 +00002977 if (unsigned ComdatID = Record[12]) {
2978 assert(ComdatID <= ComdatList.size());
2979 Func->setComdat(ComdatList[ComdatID - 1]);
2980 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002981 } else if (hasImplicitComdat(RawLinkage)) {
2982 Func->setComdat(reinterpret_cast<Comdat *>(1));
2983 }
David Majnemerdad0a642014-06-27 18:19:56 +00002984
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002985 if (Record.size() > 13 && Record[13] != 0)
2986 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2987
Chris Lattnerccaa4482007-04-23 21:26:05 +00002988 ValueList.push_back(Func);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002989
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002990 // If this is a function with a body, remember the prototype we are
2991 // creating now, so that we can match up the body with them later.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002992 if (!isProto) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00002993 Func->setIsMaterializable(true);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002994 FunctionsWithBodies.push_back(Func);
Rafael Espindola1b47a282014-10-23 15:20:05 +00002995 if (LazyStreamer)
2996 DeferredFunctionInfo[Func] = 0;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002997 }
Chris Lattner1314b992007-04-22 06:23:29 +00002998 break;
2999 }
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00003000 // ALIAS: [alias type, aliasee val#, linkage]
Nico Rieck7157bb72014-01-14 15:22:47 +00003001 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
Chris Lattner831d4202007-04-26 03:27:58 +00003002 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner44c17072007-04-26 02:46:40 +00003003 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003004 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003005 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003006 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003007 return Error("Invalid record");
Rafael Espindolaa8004452014-05-16 14:22:33 +00003008 auto *PTy = dyn_cast<PointerType>(Ty);
3009 if (!PTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003010 return Error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003011
Rafael Espindolaa8004452014-05-16 14:22:33 +00003012 auto *NewGA =
Rafael Espindolaf1bedd3742014-05-17 21:29:57 +00003013 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +00003014 getDecodedLinkage(Record[2]), "", TheModule);
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00003015 // Old bitcode files didn't have visibility field.
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003016 // Local linkage must have default visibility.
3017 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3018 // FIXME: Change to an error if non-default in 4.0.
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00003019 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003020 if (Record.size() > 4)
3021 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
3022 else
3023 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
Rafael Espindola59f7eba2014-05-28 18:15:43 +00003024 if (Record.size() > 5)
NAKAMURA Takumi32c87ac2014-10-29 23:44:35 +00003025 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00003026 if (Record.size() > 6)
NAKAMURA Takumi32c87ac2014-10-29 23:44:35 +00003027 NewGA->setUnnamedAddr(Record[6]);
Chris Lattner44c17072007-04-26 02:46:40 +00003028 ValueList.push_back(NewGA);
3029 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3030 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003031 }
Chris Lattner831d4202007-04-26 03:27:58 +00003032 /// MODULE_CODE_PURGEVALS: [numvals]
3033 case bitc::MODULE_CODE_PURGEVALS:
3034 // Trim down the value list to the specified size.
3035 if (Record.size() < 1 || Record[0] > ValueList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003036 return Error("Invalid record");
Chris Lattner831d4202007-04-26 03:27:58 +00003037 ValueList.shrinkTo(Record[0]);
3038 break;
3039 }
Chris Lattner1314b992007-04-22 06:23:29 +00003040 Record.clear();
3041 }
Chris Lattner1314b992007-04-22 06:23:29 +00003042}
3043
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003044std::error_code BitcodeReader::ParseBitcodeInto(Module *M,
3045 bool ShouldLazyLoadMetadata) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003046 TheModule = nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003047
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003048 if (std::error_code EC = InitStream())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003049 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003050
Chris Lattner1314b992007-04-22 06:23:29 +00003051 // Sniff for the signature.
3052 if (Stream.Read(8) != 'B' ||
3053 Stream.Read(8) != 'C' ||
3054 Stream.Read(4) != 0x0 ||
3055 Stream.Read(4) != 0xC ||
3056 Stream.Read(4) != 0xE ||
3057 Stream.Read(4) != 0xD)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003058 return Error("Invalid bitcode signature");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003059
Chris Lattner1314b992007-04-22 06:23:29 +00003060 // We expect a number of well-defined blocks, though we don't necessarily
3061 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00003062 while (1) {
3063 if (Stream.AtEndOfStream())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003064 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00003065
Chris Lattner27d38752013-01-20 02:13:19 +00003066 BitstreamEntry Entry =
3067 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbey97b7a172013-02-06 22:14:06 +00003068
Chris Lattner27d38752013-01-20 02:13:19 +00003069 switch (Entry.Kind) {
3070 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003071 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003072 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003073 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00003074
Chris Lattner27d38752013-01-20 02:13:19 +00003075 case BitstreamEntry::SubBlock:
3076 switch (Entry.ID) {
3077 case bitc::BLOCKINFO_BLOCK_ID:
3078 if (Stream.ReadBlockInfoBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003079 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003080 break;
3081 case bitc::MODULE_BLOCK_ID:
3082 // Reject multiple MODULE_BLOCK's in a single bitstream.
3083 if (TheModule)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003084 return Error("Invalid multiple blocks");
Chris Lattner27d38752013-01-20 02:13:19 +00003085 TheModule = M;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003086 if (std::error_code EC = ParseModule(false, ShouldLazyLoadMetadata))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003087 return EC;
3088 if (LazyStreamer)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003089 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003090 break;
3091 default:
3092 if (Stream.SkipBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003093 return Error("Invalid record");
Chris Lattner27d38752013-01-20 02:13:19 +00003094 break;
3095 }
3096 continue;
3097 case BitstreamEntry::Record:
3098 // There should be no records in the top-level of blocks.
Joe Abbey97b7a172013-02-06 22:14:06 +00003099
Chris Lattner27d38752013-01-20 02:13:19 +00003100 // The ranlib in Xcode 4 will align archive members by appending newlines
Chad Rosiera15e3aa2011-08-09 22:23:40 +00003101 // to the end of them. If this file size is a multiple of 4 but not 8, we
3102 // have to read and ignore these final 4 bytes :-(
Chris Lattner27d38752013-01-20 02:13:19 +00003103 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
Rafael Espindolaa97b2382011-05-26 18:59:54 +00003104 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
Bill Wendling318f03f2012-07-19 00:15:11 +00003105 Stream.AtEndOfStream())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003106 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00003107
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003108 return Error("Invalid record");
Rafael Espindolaa97b2382011-05-26 18:59:54 +00003109 }
Chris Lattner1314b992007-04-22 06:23:29 +00003110 }
Chris Lattner1314b992007-04-22 06:23:29 +00003111}
Chris Lattner6694f602007-04-29 07:54:31 +00003112
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003113ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
Bill Wendling0198ce02010-10-06 01:22:42 +00003114 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003115 return Error("Invalid record");
Bill Wendling0198ce02010-10-06 01:22:42 +00003116
3117 SmallVector<uint64_t, 64> Record;
3118
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003119 std::string Triple;
Bill Wendling0198ce02010-10-06 01:22:42 +00003120 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00003121 while (1) {
3122 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003123
Chris Lattner27d38752013-01-20 02:13:19 +00003124 switch (Entry.Kind) {
3125 case BitstreamEntry::SubBlock: // Handled for us already.
3126 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003127 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003128 case BitstreamEntry::EndBlock:
Rafael Espindolae6107792014-07-04 20:05:56 +00003129 return Triple;
Chris Lattner27d38752013-01-20 02:13:19 +00003130 case BitstreamEntry::Record:
3131 // The interesting case.
3132 break;
Bill Wendling0198ce02010-10-06 01:22:42 +00003133 }
3134
3135 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00003136 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling0198ce02010-10-06 01:22:42 +00003137 default: break; // Default behavior, ignore unknown content.
Bill Wendling0198ce02010-10-06 01:22:42 +00003138 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003139 std::string S;
3140 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003141 return Error("Invalid record");
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003142 Triple = S;
Bill Wendling0198ce02010-10-06 01:22:42 +00003143 break;
3144 }
3145 }
3146 Record.clear();
3147 }
Rafael Espindolae6107792014-07-04 20:05:56 +00003148 llvm_unreachable("Exit infinite loop");
Bill Wendling0198ce02010-10-06 01:22:42 +00003149}
3150
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003151ErrorOr<std::string> BitcodeReader::parseTriple() {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003152 if (std::error_code EC = InitStream())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003153 return EC;
Bill Wendling0198ce02010-10-06 01:22:42 +00003154
3155 // Sniff for the signature.
3156 if (Stream.Read(8) != 'B' ||
3157 Stream.Read(8) != 'C' ||
3158 Stream.Read(4) != 0x0 ||
3159 Stream.Read(4) != 0xC ||
3160 Stream.Read(4) != 0xE ||
3161 Stream.Read(4) != 0xD)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003162 return Error("Invalid bitcode signature");
Bill Wendling0198ce02010-10-06 01:22:42 +00003163
3164 // We expect a number of well-defined blocks, though we don't necessarily
3165 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00003166 while (1) {
3167 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003168
Chris Lattner27d38752013-01-20 02:13:19 +00003169 switch (Entry.Kind) {
3170 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003171 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003172 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003173 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00003174
Chris Lattner27d38752013-01-20 02:13:19 +00003175 case BitstreamEntry::SubBlock:
3176 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Rafael Espindolad346cc82014-07-04 13:52:01 +00003177 return parseModuleTriple();
Joe Abbey97b7a172013-02-06 22:14:06 +00003178
Chris Lattner27d38752013-01-20 02:13:19 +00003179 // Ignore other sub-blocks.
Rafael Espindola48da4f42013-11-04 16:16:24 +00003180 if (Stream.SkipBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003181 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003182 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003183
Chris Lattner27d38752013-01-20 02:13:19 +00003184 case BitstreamEntry::Record:
3185 Stream.skipRecord(Entry.ID);
3186 continue;
Bill Wendling0198ce02010-10-06 01:22:42 +00003187 }
3188 }
Bill Wendling0198ce02010-10-06 01:22:42 +00003189}
3190
Devang Patelaf206b82009-09-18 19:26:43 +00003191/// ParseMetadataAttachment - Parse metadata attachments.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003192std::error_code BitcodeReader::ParseMetadataAttachment() {
Devang Patelaf206b82009-09-18 19:26:43 +00003193 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003194 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003195
Devang Patelaf206b82009-09-18 19:26:43 +00003196 SmallVector<uint64_t, 64> Record;
Chris Lattner27d38752013-01-20 02:13:19 +00003197 while (1) {
3198 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003199
Chris Lattner27d38752013-01-20 02:13:19 +00003200 switch (Entry.Kind) {
3201 case BitstreamEntry::SubBlock: // Handled for us already.
3202 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003203 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003204 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003205 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003206 case BitstreamEntry::Record:
3207 // The interesting case.
Devang Patelaf206b82009-09-18 19:26:43 +00003208 break;
3209 }
Chris Lattner27d38752013-01-20 02:13:19 +00003210
Devang Patelaf206b82009-09-18 19:26:43 +00003211 // Read a metadata attachment record.
3212 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00003213 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patelaf206b82009-09-18 19:26:43 +00003214 default: // Default behavior: ignore.
3215 break;
Chris Lattnerb8778552011-06-17 17:50:30 +00003216 case bitc::METADATA_ATTACHMENT: {
Devang Patelaf206b82009-09-18 19:26:43 +00003217 unsigned RecordLength = Record.size();
3218 if (Record.empty() || (RecordLength - 1) % 2 == 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003219 return Error("Invalid record");
Devang Patelaf206b82009-09-18 19:26:43 +00003220 Instruction *Inst = InstructionList[Record[0]];
3221 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patelb1a44772009-09-28 21:14:55 +00003222 unsigned Kind = Record[i];
Dan Gohman43aa8f02010-07-20 21:42:28 +00003223 DenseMap<unsigned, unsigned>::iterator I =
3224 MDKindMap.find(Kind);
3225 if (I == MDKindMap.end())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003226 return Error("Invalid ID");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003227 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3228 if (isa<LocalAsMetadata>(Node))
Duncan P. N. Exon Smith35303fd2014-12-06 02:29:44 +00003229 // Drop the attachment. This used to be legal, but there's no
3230 // upgrade path.
3231 break;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003232 Inst->setMetadata(I->second, cast<MDNode>(Node));
Manman Ren209b17c2013-09-28 00:22:27 +00003233 if (I->second == LLVMContext::MD_tbaa)
3234 InstsWithTBAATag.push_back(Inst);
Devang Patelaf206b82009-09-18 19:26:43 +00003235 }
3236 break;
3237 }
3238 }
3239 }
Devang Patelaf206b82009-09-18 19:26:43 +00003240}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003241
Chris Lattner85b7b402007-05-01 05:52:21 +00003242/// ParseFunctionBody - Lazily parse the specified function body block.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003243std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00003244 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003245 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003246
Nick Lewyckya72e1af2010-02-25 08:30:17 +00003247 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00003248 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman26d837d2010-08-25 20:22:53 +00003249 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003250
Chris Lattner85b7b402007-05-01 05:52:21 +00003251 // Add all the function arguments to the value table.
3252 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3253 ValueList.push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003254
Chris Lattner83930552007-05-01 07:01:57 +00003255 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00003256 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00003257 unsigned CurBBNo = 0;
3258
Chris Lattner07d09ed2010-04-03 02:17:50 +00003259 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003260 auto getLastInstruction = [&]() -> Instruction * {
3261 if (CurBB && !CurBB->empty())
3262 return &CurBB->back();
3263 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3264 !FunctionBBs[CurBBNo - 1]->empty())
3265 return &FunctionBBs[CurBBNo - 1]->back();
3266 return nullptr;
3267 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003268
Chris Lattner85b7b402007-05-01 05:52:21 +00003269 // Read all the records.
3270 SmallVector<uint64_t, 64> Record;
3271 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00003272 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003273
Chris Lattner27d38752013-01-20 02:13:19 +00003274 switch (Entry.Kind) {
3275 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003276 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003277 case BitstreamEntry::EndBlock:
3278 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00003279
Chris Lattner27d38752013-01-20 02:13:19 +00003280 case BitstreamEntry::SubBlock:
3281 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00003282 default: // Skip unknown content.
3283 if (Stream.SkipBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003284 return Error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00003285 break;
3286 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003287 if (std::error_code EC = ParseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003288 return EC;
Chris Lattner83930552007-05-01 07:01:57 +00003289 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00003290 break;
3291 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003292 if (std::error_code EC = ParseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003293 return EC;
Chris Lattner85b7b402007-05-01 05:52:21 +00003294 break;
Devang Patelaf206b82009-09-18 19:26:43 +00003295 case bitc::METADATA_ATTACHMENT_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003296 if (std::error_code EC = ParseMetadataAttachment())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003297 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003298 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00003299 case bitc::METADATA_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003300 if (std::error_code EC = ParseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003301 return EC;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00003302 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003303 case bitc::USELIST_BLOCK_ID:
3304 if (std::error_code EC = ParseUseLists())
3305 return EC;
3306 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00003307 }
3308 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003309
Chris Lattner27d38752013-01-20 02:13:19 +00003310 case BitstreamEntry::Record:
3311 // The interesting case.
3312 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00003313 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003314
Chris Lattner85b7b402007-05-01 05:52:21 +00003315 // Read a record.
3316 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00003317 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00003318 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00003319 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00003320 default: // Default behavior: reject
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003321 return Error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003322 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00003323 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003324 return Error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00003325 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00003326 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003327
3328 // See if anything took the address of blocks in this function.
3329 auto BBFRI = BasicBlockFwdRefs.find(F);
3330 if (BBFRI == BasicBlockFwdRefs.end()) {
3331 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3332 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3333 } else {
3334 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003335 // Check for invalid basic block references.
3336 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003337 return Error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003338 assert(!BBRefs.empty() && "Unexpected empty array");
3339 assert(!BBRefs.front() && "Invalid reference to entry block");
3340 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3341 ++I)
3342 if (I < RE && BBRefs[I]) {
3343 BBRefs[I]->insertInto(F);
3344 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003345 } else {
3346 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3347 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003348
3349 // Erase from the table.
3350 BasicBlockFwdRefs.erase(BBFRI);
3351 }
3352
Chris Lattner83930552007-05-01 07:01:57 +00003353 CurBB = FunctionBBs[0];
3354 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003355 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003356
Chris Lattner07d09ed2010-04-03 02:17:50 +00003357 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3358 // This record indicates that the last instruction is at the same
3359 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003360 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003361
Craig Topper2617dcc2014-04-15 06:32:26 +00003362 if (!I)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003363 return Error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00003364 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003365 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003366 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003367
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00003368 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003369 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00003370 if (!I || Record.size() < 4)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003371 return Error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003372
Chris Lattner07d09ed2010-04-03 02:17:50 +00003373 unsigned Line = Record[0], Col = Record[1];
3374 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003375
Craig Topper2617dcc2014-04-15 06:32:26 +00003376 MDNode *Scope = nullptr, *IA = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003377 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3378 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3379 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3380 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003381 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003382 continue;
3383 }
3384
Chris Lattnere9759c22007-05-06 00:21:25 +00003385 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3386 unsigned OpNum = 0;
3387 Value *LHS, *RHS;
3388 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003389 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00003390 OpNum+1 > Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003391 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003392
Dan Gohman0ebd6962009-07-20 21:19:07 +00003393 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00003394 if (Opc == -1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003395 return Error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003396 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00003397 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00003398 if (OpNum < Record.size()) {
3399 if (Opc == Instruction::Add ||
3400 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003401 Opc == Instruction::Mul ||
3402 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00003403 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00003404 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00003405 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00003406 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00003407 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003408 Opc == Instruction::UDiv ||
3409 Opc == Instruction::LShr ||
3410 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00003411 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00003412 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003413 } else if (isa<FPMathOperator>(I)) {
3414 FastMathFlags FMF;
Michael Ilseman65f14352012-12-09 21:12:04 +00003415 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3416 FMF.setUnsafeAlgebra();
3417 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3418 FMF.setNoNaNs();
3419 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3420 FMF.setNoInfs();
3421 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3422 FMF.setNoSignedZeros();
3423 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3424 FMF.setAllowReciprocal();
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003425 if (FMF.any())
3426 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00003427 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003428
Dan Gohman1b849082009-09-07 23:54:19 +00003429 }
Chris Lattner85b7b402007-05-01 05:52:21 +00003430 break;
3431 }
Chris Lattnere9759c22007-05-06 00:21:25 +00003432 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3433 unsigned OpNum = 0;
3434 Value *Op;
3435 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3436 OpNum+2 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003437 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003438
Chris Lattner229907c2011-07-18 04:54:35 +00003439 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnere9759c22007-05-06 00:21:25 +00003440 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003441 if (Opc == -1 || !ResTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003442 return Error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00003443 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003444 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3445 if (Temp) {
3446 InstructionList.push_back(Temp);
3447 CurBB->getInstList().push_back(Temp);
3448 }
3449 } else {
3450 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3451 }
Devang Patelaf206b82009-09-18 19:26:43 +00003452 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00003453 break;
3454 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00003455 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3456 case bitc::FUNC_CODE_INST_GEP_OLD:
3457 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003458 unsigned OpNum = 0;
David Blaikieb5b5efd2015-02-25 01:08:52 +00003459
3460 Type *Ty;
3461 bool InBounds;
3462
3463 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3464 InBounds = Record[OpNum++];
3465 Ty = getTypeByID(Record[OpNum++]);
3466 } else {
3467 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3468 Ty = nullptr;
3469 }
3470
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003471 Value *BasePtr;
3472 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003473 return Error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00003474
David Blaikie675e8cb2015-03-16 21:35:48 +00003475 if (Ty &&
3476 Ty !=
3477 cast<SequentialType>(BasePtr->getType()->getScalarType())
3478 ->getElementType())
3479 return Error(
3480 "Explicit gep type does not match pointee type of pointer operand");
3481
Chris Lattner5285b5e2007-05-02 05:46:45 +00003482 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003483 while (OpNum != Record.size()) {
3484 Value *Op;
3485 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003486 return Error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003487 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003488 }
3489
David Blaikie096b1da2015-03-14 19:53:33 +00003490 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
David Blaikie675e8cb2015-03-16 21:35:48 +00003491
Devang Patelaf206b82009-09-18 19:26:43 +00003492 InstructionList.push_back(I);
David Blaikieb5b5efd2015-02-25 01:08:52 +00003493 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00003494 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003495 break;
3496 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003497
Dan Gohman1ecaf452008-05-31 00:58:22 +00003498 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3499 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00003500 unsigned OpNum = 0;
3501 Value *Agg;
3502 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003503 return Error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003504
Dan Gohman1ecaf452008-05-31 00:58:22 +00003505 SmallVector<unsigned, 4> EXTRACTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003506 Type *CurTy = Agg->getType();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003507 for (unsigned RecSize = Record.size();
3508 OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003509 bool IsArray = CurTy->isArrayTy();
3510 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003511 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003512
3513 if (!IsStruct && !IsArray)
3514 return Error("EXTRACTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003515 if ((unsigned)Index != Index)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003516 return Error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003517 if (IsStruct && Index >= CurTy->subtypes().size())
3518 return Error("EXTRACTVAL: Invalid struct index");
3519 if (IsArray && Index >= CurTy->getArrayNumElements())
3520 return Error("EXTRACTVAL: Invalid array index");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003521 EXTRACTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003522
3523 if (IsStruct)
3524 CurTy = CurTy->subtypes()[Index];
3525 else
3526 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00003527 }
3528
Jay Foad57aa6362011-07-13 10:26:04 +00003529 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003530 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00003531 break;
3532 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003533
Dan Gohman1ecaf452008-05-31 00:58:22 +00003534 case bitc::FUNC_CODE_INST_INSERTVAL: {
3535 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00003536 unsigned OpNum = 0;
3537 Value *Agg;
3538 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003539 return Error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003540 Value *Val;
3541 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003542 return Error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003543
Dan Gohman1ecaf452008-05-31 00:58:22 +00003544 SmallVector<unsigned, 4> INSERTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003545 Type *CurTy = Agg->getType();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003546 for (unsigned RecSize = Record.size();
3547 OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003548 bool IsArray = CurTy->isArrayTy();
3549 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003550 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003551
3552 if (!IsStruct && !IsArray)
3553 return Error("INSERTVAL: Invalid type");
3554 if (!CurTy->isStructTy() && !CurTy->isArrayTy())
3555 return Error("Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003556 if ((unsigned)Index != Index)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003557 return Error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003558 if (IsStruct && Index >= CurTy->subtypes().size())
3559 return Error("INSERTVAL: Invalid struct index");
3560 if (IsArray && Index >= CurTy->getArrayNumElements())
3561 return Error("INSERTVAL: Invalid array index");
3562
Dan Gohman1ecaf452008-05-31 00:58:22 +00003563 INSERTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003564 if (IsStruct)
3565 CurTy = CurTy->subtypes()[Index];
3566 else
3567 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00003568 }
3569
Jay Foad57aa6362011-07-13 10:26:04 +00003570 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003571 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00003572 break;
3573 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003574
Chris Lattnere9759c22007-05-06 00:21:25 +00003575 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00003576 // obsolete form of select
3577 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00003578 unsigned OpNum = 0;
3579 Value *TrueVal, *FalseVal, *Cond;
3580 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003581 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3582 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003583 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003584
Dan Gohmanc5d28922008-09-16 01:01:33 +00003585 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00003586 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00003587 break;
3588 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003589
Dan Gohmanc5d28922008-09-16 01:01:33 +00003590 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3591 // new form of select
3592 // handles select i1 or select [N x i1]
3593 unsigned OpNum = 0;
3594 Value *TrueVal, *FalseVal, *Cond;
3595 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003596 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00003597 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003598 return Error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00003599
3600 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00003601 if (VectorType* vector_type =
3602 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00003603 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003604 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003605 return Error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00003606 } else {
3607 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003608 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003609 return Error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003610 }
3611
Gabor Greife9ecc682008-04-06 20:25:17 +00003612 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00003613 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003614 break;
3615 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003616
Chris Lattner1fc27f02007-05-02 05:16:49 +00003617 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00003618 unsigned OpNum = 0;
3619 Value *Vec, *Idx;
3620 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003621 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003622 return Error("Invalid record");
Eric Christopherc9742252009-07-25 02:28:41 +00003623 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00003624 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003625 break;
3626 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003627
Chris Lattner1fc27f02007-05-02 05:16:49 +00003628 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00003629 unsigned OpNum = 0;
3630 Value *Vec, *Elt, *Idx;
3631 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003632 popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00003633 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003634 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003635 return Error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00003636 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00003637 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003638 break;
3639 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003640
Chris Lattnere9759c22007-05-06 00:21:25 +00003641 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3642 unsigned OpNum = 0;
3643 Value *Vec1, *Vec2, *Mask;
3644 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003645 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003646 return Error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00003647
Mon P Wang25f01062008-11-10 04:46:22 +00003648 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003649 return Error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00003650 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00003651 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003652 break;
3653 }
Mon P Wang25f01062008-11-10 04:46:22 +00003654
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003655 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3656 // Old form of ICmp/FCmp returning bool
3657 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3658 // both legal on vectors but had different behaviour.
3659 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3660 // FCmp/ICmp returning bool or vector of bool
3661
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003662 unsigned OpNum = 0;
3663 Value *LHS, *RHS;
3664 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003665 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003666 OpNum+1 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003667 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003668
Duncan Sands9dff9be2010-02-15 16:12:20 +00003669 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohmanad1f0a12009-08-25 23:17:54 +00003670 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003671 else
Dan Gohmanad1f0a12009-08-25 23:17:54 +00003672 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00003673 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00003674 break;
3675 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003676
Chris Lattnere53603e2007-05-02 04:27:25 +00003677 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00003678 {
3679 unsigned Size = Record.size();
3680 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00003681 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003682 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00003683 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003684 }
Devang Patelbbfd8742008-02-26 01:29:32 +00003685
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003686 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00003687 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00003688 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003689 return Error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00003690 if (OpNum != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003691 return Error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003692
Chris Lattnerf1c87102011-06-17 18:09:11 +00003693 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003694 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003695 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00003696 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003697 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00003698 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003699 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003700 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003701 if (!TrueDest)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003702 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003703
Devang Patelaf206b82009-09-18 19:26:43 +00003704 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00003705 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003706 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00003707 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003708 else {
3709 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003710 Value *Cond = getValue(Record, 2, NextValueNo,
3711 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00003712 if (!FalseDest || !Cond)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003713 return Error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00003714 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003715 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003716 }
3717 break;
3718 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00003719 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003720 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003721 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00003722 // "New" SwitchInst format with case ranges. The changes to write this
3723 // format were reverted but we still recognize bitcode that uses it.
3724 // Hopefully someday we will have support for case ranges and can use
3725 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003726
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003727 Type *OpTy = getTypeByID(Record[1]);
3728 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3729
Jan Wen Voungafaced02012-10-11 20:20:40 +00003730 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003731 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003732 if (!OpTy || !Cond || !Default)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003733 return Error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003734
3735 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003736
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003737 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3738 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003739
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003740 unsigned CurIdx = 5;
3741 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00003742 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003743 unsigned NumItems = Record[CurIdx++];
3744 for (unsigned ci = 0; ci != NumItems; ++ci) {
3745 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003746
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003747 APInt Low;
3748 unsigned ActiveWords = 1;
3749 if (ValueBitWidth > 64)
3750 ActiveWords = Record[CurIdx++];
Benjamin Kramer9704ed02012-05-28 14:10:31 +00003751 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3752 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003753 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00003754
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003755 if (!isSingleNumber) {
3756 ActiveWords = 1;
3757 if (ValueBitWidth > 64)
3758 ActiveWords = Record[CurIdx++];
3759 APInt High =
Benjamin Kramer9704ed02012-05-28 14:10:31 +00003760 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3761 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003762 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00003763
3764 // FIXME: It is not clear whether values in the range should be
3765 // compared as signed or unsigned values. The partially
3766 // implemented changes that used this format in the past used
3767 // unsigned comparisons.
3768 for ( ; Low.ule(High); ++Low)
3769 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003770 } else
Bob Wilsone4077362013-09-09 19:14:35 +00003771 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003772 }
3773 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00003774 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3775 cve = CaseVals.end(); cvi != cve; ++cvi)
3776 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003777 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003778 I = SI;
3779 break;
3780 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003781
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003782 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003783
Chris Lattner5285b5e2007-05-02 05:46:45 +00003784 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003785 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003786 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003787 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003788 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003789 if (!OpTy || !Cond || !Default)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003790 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003791 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00003792 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00003793 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003794 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003795 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00003796 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3797 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003798 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00003799 delete SI;
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003800 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003801 }
3802 SI->addCase(CaseVal, DestBB);
3803 }
3804 I = SI;
3805 break;
3806 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003807 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00003808 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003809 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003810 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003811 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00003812 if (!OpTy || !Address)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003813 return Error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00003814 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003815 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00003816 InstructionList.push_back(IBI);
3817 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3818 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3819 IBI->addDestination(DestBB);
3820 } else {
3821 delete IBI;
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003822 return Error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00003823 }
3824 }
3825 I = IBI;
3826 break;
3827 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003828
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00003829 case bitc::FUNC_CODE_INST_INVOKE: {
3830 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003831 if (Record.size() < 4)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003832 return Error("Invalid record");
Bill Wendlinge94d8432012-12-07 23:16:57 +00003833 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003834 unsigned CCInfo = Record[1];
3835 BasicBlock *NormalBB = getBasicBlock(Record[2]);
3836 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003837
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003838 unsigned OpNum = 4;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003839 Value *Callee;
3840 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003841 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003842
Chris Lattner229907c2011-07-18 04:54:35 +00003843 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
Craig Topper2617dcc2014-04-15 06:32:26 +00003844 FunctionType *FTy = !CalleeTy ? nullptr :
Chris Lattner5285b5e2007-05-02 05:46:45 +00003845 dyn_cast<FunctionType>(CalleeTy->getElementType());
3846
3847 // Check that the right number of fixed parameters are here.
Craig Topper2617dcc2014-04-15 06:32:26 +00003848 if (!FTy || !NormalBB || !UnwindBB ||
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003849 Record.size() < OpNum+FTy->getNumParams())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003850 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003851
Chris Lattner5285b5e2007-05-02 05:46:45 +00003852 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003853 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00003854 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3855 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00003856 if (!Ops.back())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003857 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003858 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003859
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003860 if (!FTy->isVarArg()) {
3861 if (Record.size() != OpNum)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003862 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003863 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003864 // Read type/value pairs for varargs params.
3865 while (OpNum != Record.size()) {
3866 Value *Op;
3867 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003868 return Error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003869 Ops.push_back(Op);
3870 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003871 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003872
Jay Foad5bd375a2011-07-15 08:37:34 +00003873 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patelaf206b82009-09-18 19:26:43 +00003874 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00003875 cast<InvokeInst>(I)->setCallingConv(
3876 static_cast<CallingConv::ID>(CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00003877 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003878 break;
3879 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00003880 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3881 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00003882 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00003883 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003884 return Error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00003885 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00003886 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00003887 break;
3888 }
Chris Lattnere53603e2007-05-02 04:27:25 +00003889 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00003890 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00003891 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00003892 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00003893 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00003894 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003895 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003896 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003897 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003898 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003899
Jay Foad52131342011-03-30 11:28:46 +00003900 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00003901 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003902
Chris Lattnere14cb882007-05-04 19:11:41 +00003903 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00003904 Value *V;
3905 // With the new function encoding, it is possible that operands have
3906 // negative IDs (for forward references). Use a signed VBR
3907 // representation to keep the encoding small.
3908 if (UseRelativeIDs)
3909 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3910 else
3911 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00003912 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003913 if (!V || !BB)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003914 return Error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00003915 PN->addIncoming(V, BB);
3916 }
3917 I = PN;
3918 break;
3919 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003920
Bill Wendlingfae14752011-08-12 20:24:12 +00003921 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3922 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3923 unsigned Idx = 0;
3924 if (Record.size() < 4)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003925 return Error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00003926 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003927 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003928 return Error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00003929 Value *PersFn = nullptr;
Bill Wendlingfae14752011-08-12 20:24:12 +00003930 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003931 return Error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00003932
3933 bool IsCleanup = !!Record[Idx++];
3934 unsigned NumClauses = Record[Idx++];
3935 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
3936 LP->setCleanup(IsCleanup);
3937 for (unsigned J = 0; J != NumClauses; ++J) {
3938 LandingPadInst::ClauseType CT =
3939 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3940 Value *Val;
3941
3942 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3943 delete LP;
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003944 return Error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00003945 }
3946
3947 assert((CT != LandingPadInst::Catch ||
3948 !isa<ArrayType>(Val->getType())) &&
3949 "Catch clause has a invalid type!");
3950 assert((CT != LandingPadInst::Filter ||
3951 isa<ArrayType>(Val->getType())) &&
3952 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00003953 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00003954 }
3955
3956 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00003957 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00003958 break;
3959 }
3960
Chris Lattnerf1c87102011-06-17 18:09:11 +00003961 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3962 if (Record.size() != 4)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003963 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003964 PointerType *Ty =
Chris Lattnerc332bba2007-05-03 18:58:09 +00003965 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
Chris Lattner229907c2011-07-18 04:54:35 +00003966 Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerf1c87102011-06-17 18:09:11 +00003967 Value *Size = getFnValueByID(Record[2], OpTy);
JF Bastien30bf96b2015-02-22 19:32:03 +00003968 uint64_t AlignRecord = Record[3];
3969 const uint64_t InAllocaMask = uint64_t(1) << 5;
3970 bool InAlloca = AlignRecord & InAllocaMask;
3971 unsigned Align;
3972 if (std::error_code EC =
3973 parseAlignmentValue(AlignRecord & ~InAllocaMask, Align)) {
3974 return EC;
3975 }
Rafael Espindola48da4f42013-11-04 16:16:24 +00003976 if (!Ty || !Size)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003977 return Error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00003978 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, Align);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00003979 AI->setUsedWithInAlloca(InAlloca);
3980 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00003981 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00003982 break;
3983 }
Chris Lattner9f600c52007-05-03 22:04:19 +00003984 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003985 unsigned OpNum = 0;
3986 Value *Op;
3987 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00003988 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003989 return Error("Invalid record");
David Blaikie85035652015-02-25 01:07:20 +00003990
3991 Type *Ty = nullptr;
3992 if (OpNum + 3 == Record.size())
3993 Ty = getTypeByID(Record[OpNum++]);
3994
JF Bastien30bf96b2015-02-22 19:32:03 +00003995 unsigned Align;
3996 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
3997 return EC;
3998 I = new LoadInst(Op, "", Record[OpNum+1], Align);
David Blaikie85035652015-02-25 01:07:20 +00003999
David Blaikiec695cc72015-03-16 21:48:46 +00004000 if (Ty && Ty != I->getType())
4001 return Error("Explicit load type does not match pointee type of "
4002 "pointer operand");
David Blaikie85035652015-02-25 01:07:20 +00004003
Devang Patelaf206b82009-09-18 19:26:43 +00004004 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00004005 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00004006 }
Eli Friedman59b66882011-08-09 23:02:53 +00004007 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4008 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4009 unsigned OpNum = 0;
4010 Value *Op;
4011 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004012 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004013 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004014
David Blaikie85035652015-02-25 01:07:20 +00004015 Type *Ty = nullptr;
4016 if (OpNum + 5 == Record.size())
4017 Ty = getTypeByID(Record[OpNum++]);
4018
Eli Friedman59b66882011-08-09 23:02:53 +00004019 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4020 if (Ordering == NotAtomic || Ordering == Release ||
4021 Ordering == AcquireRelease)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004022 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004023 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004024 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004025 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4026
JF Bastien30bf96b2015-02-22 19:32:03 +00004027 unsigned Align;
4028 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4029 return EC;
4030 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
David Blaikie85035652015-02-25 01:07:20 +00004031
Yaron Kerend602c352015-02-28 15:29:17 +00004032 (void)Ty;
David Blaikie85035652015-02-25 01:07:20 +00004033 assert((!Ty || Ty == I->getType()) &&
4034 "Explicit type doesn't match pointee type of the first operand");
4035
Eli Friedman59b66882011-08-09 23:02:53 +00004036 InstructionList.push_back(I);
4037 break;
4038 }
Chris Lattnerc44070802011-06-17 18:17:37 +00004039 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004040 unsigned OpNum = 0;
4041 Value *Val, *Ptr;
4042 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004043 popValue(Record, OpNum, NextValueNo,
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004044 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4045 OpNum+2 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004046 return Error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00004047 unsigned Align;
4048 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4049 return EC;
4050 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
Devang Patelaf206b82009-09-18 19:26:43 +00004051 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004052 break;
4053 }
Eli Friedman59b66882011-08-09 23:02:53 +00004054 case bitc::FUNC_CODE_INST_STOREATOMIC: {
4055 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4056 unsigned OpNum = 0;
4057 Value *Val, *Ptr;
4058 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004059 popValue(Record, OpNum, NextValueNo,
Eli Friedman59b66882011-08-09 23:02:53 +00004060 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4061 OpNum+4 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004062 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004063
4064 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman222b5a42011-09-19 19:41:28 +00004065 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman59b66882011-08-09 23:02:53 +00004066 Ordering == AcquireRelease)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004067 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004068 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4069 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004070 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004071
JF Bastien30bf96b2015-02-22 19:32:03 +00004072 unsigned Align;
4073 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4074 return EC;
4075 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
Eli Friedman59b66882011-08-09 23:02:53 +00004076 InstructionList.push_back(I);
4077 break;
4078 }
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004079 case bitc::FUNC_CODE_INST_CMPXCHG: {
Tim Northovere94a5182014-03-11 10:48:52 +00004080 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
Tim Northover420a2162014-06-13 14:24:07 +00004081 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004082 unsigned OpNum = 0;
4083 Value *Ptr, *Cmp, *New;
4084 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004085 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004086 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004087 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004088 cast<PointerType>(Ptr->getType())->getElementType(), New) ||
Tim Northover420a2162014-06-13 14:24:07 +00004089 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004090 return Error("Invalid record");
Tim Northovere94a5182014-03-11 10:48:52 +00004091 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
4092 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004093 return Error("Invalid record");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004094 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
Tim Northovere94a5182014-03-11 10:48:52 +00004095
4096 AtomicOrdering FailureOrdering;
4097 if (Record.size() < 7)
4098 FailureOrdering =
4099 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4100 else
4101 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
4102
4103 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4104 SynchScope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004105 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00004106
4107 if (Record.size() < 8) {
4108 // Before weak cmpxchgs existed, the instruction simply returned the
4109 // value loaded from memory, so bitcode files from that era will be
4110 // expecting the first component of a modern cmpxchg.
4111 CurBB->getInstList().push_back(I);
4112 I = ExtractValueInst::Create(I, 0);
4113 } else {
4114 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4115 }
4116
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004117 InstructionList.push_back(I);
4118 break;
4119 }
4120 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4121 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4122 unsigned OpNum = 0;
4123 Value *Ptr, *Val;
4124 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004125 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004126 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4127 OpNum+4 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004128 return Error("Invalid record");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004129 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
4130 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4131 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004132 return Error("Invalid record");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004133 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman59b66882011-08-09 23:02:53 +00004134 if (Ordering == NotAtomic || Ordering == Unordered)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004135 return Error("Invalid record");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004136 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4137 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4138 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4139 InstructionList.push_back(I);
4140 break;
4141 }
Eli Friedmanfee02c62011-07-25 23:16:38 +00004142 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4143 if (2 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004144 return Error("Invalid record");
Eli Friedmanfee02c62011-07-25 23:16:38 +00004145 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
4146 if (Ordering == NotAtomic || Ordering == Unordered ||
4147 Ordering == Monotonic)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004148 return Error("Invalid record");
Eli Friedmanfee02c62011-07-25 23:16:38 +00004149 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
4150 I = new FenceInst(Context, Ordering, SynchScope);
4151 InstructionList.push_back(I);
4152 break;
4153 }
Chris Lattnerc44070802011-06-17 18:17:37 +00004154 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004155 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4156 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004157 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004158
Bill Wendlinge94d8432012-12-07 23:16:57 +00004159 AttributeSet PAL = getAttributes(Record[0]);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00004160 unsigned CCInfo = Record[1];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004161
Chris Lattner4c0a6d62007-05-08 05:38:01 +00004162 unsigned OpNum = 2;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004163 Value *Callee;
4164 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004165 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004166
Chris Lattner229907c2011-07-18 04:54:35 +00004167 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Craig Topper2617dcc2014-04-15 06:32:26 +00004168 FunctionType *FTy = nullptr;
Chris Lattner9f600c52007-05-03 22:04:19 +00004169 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004170 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004171 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004172
Chris Lattner9f600c52007-05-03 22:04:19 +00004173 SmallVector<Value*, 16> Args;
4174 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004175 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004176 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00004177 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00004178 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00004179 Args.push_back(getValue(Record, OpNum, NextValueNo,
4180 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004181 if (!Args.back())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004182 return Error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004183 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004184
Chris Lattner9f600c52007-05-03 22:04:19 +00004185 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00004186 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004187 if (OpNum != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004188 return Error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004189 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004190 while (OpNum != Record.size()) {
4191 Value *Op;
4192 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004193 return Error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004194 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00004195 }
4196 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004197
Jay Foad5bd375a2011-07-15 08:37:34 +00004198 I = CallInst::Create(Callee, Args);
Devang Patelaf206b82009-09-18 19:26:43 +00004199 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00004200 cast<CallInst>(I)->setCallingConv(
Reid Kleckner5772b772014-04-24 20:14:34 +00004201 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4202 CallInst::TailCallKind TCK = CallInst::TCK_None;
4203 if (CCInfo & 1)
4204 TCK = CallInst::TCK_Tail;
4205 if (CCInfo & (1 << 14))
4206 TCK = CallInst::TCK_MustTail;
4207 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00004208 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner9f600c52007-05-03 22:04:19 +00004209 break;
4210 }
4211 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4212 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004213 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004214 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004215 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00004216 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00004217 if (!OpTy || !Op || !ResTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004218 return Error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004219 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00004220 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00004221 break;
4222 }
Chris Lattner83930552007-05-01 07:01:57 +00004223 }
4224
4225 // Add instruction to end of current BB. If there is no current BB, reject
4226 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00004227 if (!CurBB) {
Chris Lattner83930552007-05-01 07:01:57 +00004228 delete I;
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004229 return Error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00004230 }
4231 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004232
Chris Lattner83930552007-05-01 07:01:57 +00004233 // If this was a terminator instruction, move to the next block.
4234 if (isa<TerminatorInst>(I)) {
4235 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00004236 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00004237 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004238
Chris Lattner83930552007-05-01 07:01:57 +00004239 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00004240 if (I && !I->getType()->isVoidTy())
Chris Lattner83930552007-05-01 07:01:57 +00004241 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00004242 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004243
Chris Lattner27d38752013-01-20 02:13:19 +00004244OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00004245
Chris Lattner83930552007-05-01 07:01:57 +00004246 // Check the function list for unresolved values.
4247 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004248 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00004249 // We found at least one unresolved value. Nuke them all to avoid leaks.
4250 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00004251 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00004252 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00004253 delete A;
4254 }
4255 }
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004256 return Error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00004257 }
Chris Lattner83930552007-05-01 07:01:57 +00004258 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004259
Dan Gohman9b9ff462010-08-25 20:23:38 +00004260 // FIXME: Check for unresolved forward-declared metadata references
4261 // and clean up leaks.
4262
Chris Lattner85b7b402007-05-01 05:52:21 +00004263 // Trim the value list down to the size it was before we parsed this function.
4264 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman26d837d2010-08-25 20:22:53 +00004265 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00004266 std::vector<BasicBlock*>().swap(FunctionBBs);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004267 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004268}
4269
Rafael Espindola7d712032013-11-05 17:16:08 +00004270/// Find the function body in the bitcode stream
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004271std::error_code BitcodeReader::FindFunctionInStream(
4272 Function *F,
4273 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004274 while (DeferredFunctionInfoIterator->second == 0) {
4275 if (Stream.AtEndOfStream())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004276 return Error("Could not find function in stream");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004277 // ParseModule will parse the next body in the stream and set its
4278 // position in the DeferredFunctionInfo map.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004279 if (std::error_code EC = ParseModule(true))
Rafael Espindola7d712032013-11-05 17:16:08 +00004280 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004281 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004282 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004283}
4284
Chris Lattner9eeada92007-05-18 04:02:46 +00004285//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004286// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00004287//===----------------------------------------------------------------------===//
4288
Rafael Espindolac3f9b5a2014-06-23 21:53:12 +00004289void BitcodeReader::releaseBuffer() { Buffer.release(); }
Chris Lattner9eeada92007-05-18 04:02:46 +00004290
Rafael Espindola5a52e6d2014-10-24 22:50:48 +00004291std::error_code BitcodeReader::materialize(GlobalValue *GV) {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004292 if (std::error_code EC = materializeMetadata())
4293 return EC;
4294
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004295 Function *F = dyn_cast<Function>(GV);
4296 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004297 if (!F || !F->isMaterializable())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004298 return std::error_code();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004299
4300 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00004301 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004302 // If its position is recorded as 0, its body is somewhere in the stream
4303 // but we haven't seen it yet.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004304 if (DFII->second == 0 && LazyStreamer)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004305 if (std::error_code EC = FindFunctionInStream(F, DFII))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004306 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004307
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004308 // Move the bit stream to the saved position of the deferred function body.
4309 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004310
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004311 if (std::error_code EC = ParseFunctionBody(F))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004312 return EC;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00004313 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00004314
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00004315 if (StripDebugInfo)
4316 stripDebugInfo(*F);
4317
Chandler Carruth7132e002007-08-04 01:51:18 +00004318 // Upgrade any old intrinsic calls in the function.
4319 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
4320 E = UpgradedIntrinsics.end(); I != E; ++I) {
4321 if (I->first != I->second) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00004322 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4323 UI != UE;) {
Chandler Carruth7132e002007-08-04 01:51:18 +00004324 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4325 UpgradeIntrinsicCall(CI, I->second);
4326 }
4327 }
4328 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004329
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004330 // Bring in any functions that this function forward-referenced via
4331 // blockaddresses.
4332 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00004333}
4334
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004335bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4336 const Function *F = dyn_cast<Function>(GV);
4337 if (!F || F->isDeclaration())
4338 return false;
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004339
4340 // Dematerializing F would leave dangling references that wouldn't be
4341 // reconnected on re-materialization.
4342 if (BlockAddressesTaken.count(F))
4343 return false;
4344
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004345 return DeferredFunctionInfo.count(const_cast<Function*>(F));
4346}
4347
4348void BitcodeReader::Dematerialize(GlobalValue *GV) {
4349 Function *F = dyn_cast<Function>(GV);
4350 // If this function isn't dematerializable, this is a noop.
4351 if (!F || !isDematerializable(F))
Chris Lattner9eeada92007-05-18 04:02:46 +00004352 return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004353
Chris Lattner9eeada92007-05-18 04:02:46 +00004354 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004355
Chris Lattner9eeada92007-05-18 04:02:46 +00004356 // Just forget the function body, we can remat it later.
Petar Jovanovic7480e4d2014-09-23 12:54:19 +00004357 F->dropAllReferences();
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00004358 F->setIsMaterializable(true);
Chris Lattner9eeada92007-05-18 04:02:46 +00004359}
4360
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004361std::error_code BitcodeReader::MaterializeModule(Module *M) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004362 assert(M == TheModule &&
4363 "Can only Materialize the Module this BitcodeReader is attached to.");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004364
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004365 if (std::error_code EC = materializeMetadata())
4366 return EC;
4367
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004368 // Promise to materialize all forward references.
4369 WillMaterializeAllForwardRefs = true;
4370
Chris Lattner06310bf2009-06-16 05:15:21 +00004371 // Iterate over the module, deserializing any functions that are still on
4372 // disk.
4373 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004374 F != E; ++F) {
Rafael Espindola246c4fb2014-11-01 16:46:18 +00004375 if (std::error_code EC = materialize(F))
4376 return EC;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004377 }
Derek Schuff92ef9752012-02-29 00:07:09 +00004378 // At this point, if there are any function bodies, the current bit is
4379 // pointing to the END_BLOCK record after them. Now make sure the rest
4380 // of the bits in the module have been read.
4381 if (NextUnreadBit)
4382 ParseModule(true);
4383
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004384 // Check that all block address forward references got resolved (as we
4385 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004386 if (!BasicBlockFwdRefs.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004387 return Error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004388
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004389 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4390 // delete the old functions to clean up. We can't do this unless the entire
4391 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00004392 // with calls to the old function.
4393 for (std::vector<std::pair<Function*, Function*> >::iterator I =
4394 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
4395 if (I->first != I->second) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00004396 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4397 UI != UE;) {
Chandler Carruth7132e002007-08-04 01:51:18 +00004398 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4399 UpgradeIntrinsicCall(CI, I->second);
4400 }
Chris Lattner647cffb2009-04-01 01:43:03 +00004401 if (!I->first->use_empty())
4402 I->first->replaceAllUsesWith(I->second);
Chandler Carruth7132e002007-08-04 01:51:18 +00004403 I->first->eraseFromParent();
4404 }
4405 }
4406 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patel80ae3492009-08-28 23:24:31 +00004407
Manman Ren209b17c2013-09-28 00:22:27 +00004408 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4409 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4410
Manman Ren8b4306c2013-12-02 21:29:56 +00004411 UpgradeDebugInfo(*M);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004412 return std::error_code();
Chris Lattner9eeada92007-05-18 04:02:46 +00004413}
4414
Rafael Espindola2fa1e432014-12-03 07:18:23 +00004415std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4416 return IdentifiedStructTypes;
4417}
4418
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004419std::error_code BitcodeReader::InitStream() {
Rafael Espindola48da4f42013-11-04 16:16:24 +00004420 if (LazyStreamer)
4421 return InitLazyStream();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004422 return InitStreamFromBuffer();
4423}
4424
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004425std::error_code BitcodeReader::InitStreamFromBuffer() {
Roman Divacky4717a8d2012-09-06 15:42:13 +00004426 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004427 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4428
Rafael Espindola27435252014-07-29 21:01:24 +00004429 if (Buffer->getBufferSize() & 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004430 return Error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004431
4432 // If we have a wrapper header, parse it and ignore the non-bc file contents.
4433 // The magic number is 0x0B17C0DE stored in little endian.
4434 if (isBitcodeWrapper(BufPtr, BufEnd))
4435 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004436 return Error("Invalid bitcode wrapper header");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004437
4438 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00004439 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004440
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004441 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004442}
4443
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004444std::error_code BitcodeReader::InitLazyStream() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004445 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4446 // see it.
Yaron Keren06d69302014-12-18 10:03:35 +00004447 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
Rafael Espindola7d727b52014-12-18 05:08:43 +00004448 StreamingMemoryObject &Bytes = *OwnedBytes;
Yaron Keren06d69302014-12-18 10:03:35 +00004449 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00004450 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004451
4452 unsigned char buf[16];
Rafael Espindola7d727b52014-12-18 05:08:43 +00004453 if (Bytes.readBytes(buf, 16, 0) != 16)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004454 return Error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004455
4456 if (!isBitcode(buf, buf + 16))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004457 return Error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004458
4459 if (isBitcodeWrapper(buf, buf + 4)) {
4460 const unsigned char *bitcodeStart = buf;
4461 const unsigned char *bitcodeEnd = buf + 16;
4462 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
Rafael Espindola7d727b52014-12-18 05:08:43 +00004463 Bytes.dropLeadingBytes(bitcodeStart - buf);
4464 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004465 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004466 return std::error_code();
Rafael Espindola48da4f42013-11-04 16:16:24 +00004467}
4468
4469namespace {
Rafael Espindola25188c92014-06-12 01:45:43 +00004470class BitcodeErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +00004471 const char *name() const LLVM_NOEXCEPT override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00004472 return "llvm.bitcode";
4473 }
Craig Topper73156022014-03-02 09:09:27 +00004474 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00004475 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004476 switch (E) {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00004477 case BitcodeError::InvalidBitcodeSignature:
Rafael Espindola48da4f42013-11-04 16:16:24 +00004478 return "Invalid bitcode signature";
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004479 case BitcodeError::CorruptedBitcode:
4480 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00004481 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00004482 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00004483 }
4484};
4485}
4486
Chris Bieneman770163e2014-09-19 20:29:02 +00004487static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4488
Rafael Espindolac3f2e732014-07-29 20:22:46 +00004489const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00004490 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004491}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004492
Chris Lattner6694f602007-04-29 07:54:31 +00004493//===----------------------------------------------------------------------===//
4494// External interface
4495//===----------------------------------------------------------------------===//
4496
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00004497/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00004498///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00004499/// This isn't always used in a lazy context. In particular, it's also used by
4500/// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
4501/// in forward-referenced functions from block address references.
4502///
4503/// \param[in] WillMaterializeAll Set to \c true if the caller promises to
4504/// materialize everything -- in particular, if this isn't truly lazy.
Rafael Espindolae2c1d772014-08-26 22:00:09 +00004505static ErrorOr<Module *>
Rafael Espindola68812152014-09-03 17:31:46 +00004506getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004507 LLVMContext &Context, bool WillMaterializeAll,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004508 DiagnosticHandlerFunction DiagnosticHandler,
4509 bool ShouldLazyLoadMetadata = false) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004510 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004511 BitcodeReader *R =
4512 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004513 M->setMaterializer(R);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004514
4515 auto cleanupOnError = [&](std::error_code EC) {
Rafael Espindola8fb31112014-06-18 20:07:35 +00004516 R->releaseBuffer(); // Never take ownership on error.
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004517 delete M; // Also deletes R.
Rafael Espindola5b6c1e82014-01-13 18:31:04 +00004518 return EC;
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004519 };
Rafael Espindolab7993462012-01-02 07:49:53 +00004520
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004521 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
4522 if (std::error_code EC = R->ParseBitcodeInto(M, ShouldLazyLoadMetadata))
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004523 return cleanupOnError(EC);
4524
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00004525 if (!WillMaterializeAll)
4526 // Resolve forward references from blockaddresses.
4527 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4528 return cleanupOnError(EC);
Rafael Espindolab7993462012-01-02 07:49:53 +00004529
Rafael Espindolae2c1d772014-08-26 22:00:09 +00004530 Buffer.release(); // The BitcodeReader owns it now.
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004531 return M;
Chris Lattner6694f602007-04-29 07:54:31 +00004532}
4533
Rafael Espindolae2c1d772014-08-26 22:00:09 +00004534ErrorOr<Module *>
Rafael Espindola68812152014-09-03 17:31:46 +00004535llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004536 LLVMContext &Context,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004537 DiagnosticHandlerFunction DiagnosticHandler,
4538 bool ShouldLazyLoadMetadata) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004539 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004540 DiagnosticHandler, ShouldLazyLoadMetadata);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00004541}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004542
Rafael Espindola7d727b52014-12-18 05:08:43 +00004543ErrorOr<std::unique_ptr<Module>>
4544llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004545 LLVMContext &Context,
4546 DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindola7d727b52014-12-18 05:08:43 +00004547 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004548 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004549 M->setMaterializer(R);
Rafael Espindola7d727b52014-12-18 05:08:43 +00004550 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
4551 return EC;
4552 return std::move(M);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004553}
4554
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004555ErrorOr<Module *>
4556llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4557 DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00004558 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004559 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
4560 std::move(Buf), Context, true, DiagnosticHandler);
Rafael Espindola8f31e212014-01-15 01:08:23 +00004561 if (!ModuleOrErr)
4562 return ModuleOrErr;
Rafael Espindola5b6c1e82014-01-13 18:31:04 +00004563 Module *M = ModuleOrErr.get();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004564 // Read in the entire module, and destroy the BitcodeReader.
Rafael Espindolad96d5532014-08-26 21:49:01 +00004565 if (std::error_code EC = M->materializeAllPermanently()) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004566 delete M;
Rafael Espindola8f31e212014-01-15 01:08:23 +00004567 return EC;
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004568 }
Bill Wendling0198ce02010-10-06 01:22:42 +00004569
Chad Rosierca2567b2011-12-07 21:44:12 +00004570 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4571 // written. We must defer until the Module has been fully materialized.
4572
Chris Lattner6694f602007-04-29 07:54:31 +00004573 return M;
4574}
Bill Wendling0198ce02010-10-06 01:22:42 +00004575
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004576std::string
4577llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4578 DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00004579 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004580 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4581 DiagnosticHandler);
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004582 ErrorOr<std::string> Triple = R->parseTriple();
Rafael Espindolad346cc82014-07-04 13:52:01 +00004583 if (Triple.getError())
4584 return "";
4585 return Triple.get();
Bill Wendling0198ce02010-10-06 01:22:42 +00004586}