blob: e0800916c8cd6d0c8caa5b57b2aaa8fd30959a96 [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);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000233 ~BitcodeReader() override { FreeState(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000234
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;
Eric Christopher97cb5652015-05-15 18:20:14 +0000243 std::error_code materializeModule(Module *M) override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000244 std::vector<StructType *> getIdentifiedStructTypes() const override;
Eric Christopher97cb5652015-05-15 18:20:14 +0000245 void dematerialize(GlobalValue *GV) override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000246
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;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000302 }
David Blaikiedbe6e0f2015-04-17 06:40:14 +0000303 if (Slot == Record.size())
304 return true;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000305
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();
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +0000373 std::error_code ParseMetadataAttachment(Function &F);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000374 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}
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000610
Chris Lattner229907c2011-07-18 04:54:35 +0000611static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000612 bool IsFP = Ty->isFPOrFPVectorTy();
613 // BinOps are only valid for int/fp or vector of int/fp types
614 if (!IsFP && !Ty->isIntOrIntVectorTy())
615 return -1;
616
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000617 switch (Val) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000618 default:
619 return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000620 case bitc::BINOP_ADD:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000621 return IsFP ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000622 case bitc::BINOP_SUB:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000623 return IsFP ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000624 case bitc::BINOP_MUL:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000625 return IsFP ? Instruction::FMul : Instruction::Mul;
626 case bitc::BINOP_UDIV:
627 return IsFP ? -1 : Instruction::UDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000628 case bitc::BINOP_SDIV:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000629 return IsFP ? Instruction::FDiv : Instruction::SDiv;
630 case bitc::BINOP_UREM:
631 return IsFP ? -1 : Instruction::URem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000632 case bitc::BINOP_SREM:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000633 return IsFP ? Instruction::FRem : Instruction::SRem;
634 case bitc::BINOP_SHL:
635 return IsFP ? -1 : Instruction::Shl;
636 case bitc::BINOP_LSHR:
637 return IsFP ? -1 : Instruction::LShr;
638 case bitc::BINOP_ASHR:
639 return IsFP ? -1 : Instruction::AShr;
640 case bitc::BINOP_AND:
641 return IsFP ? -1 : Instruction::And;
642 case bitc::BINOP_OR:
643 return IsFP ? -1 : Instruction::Or;
644 case bitc::BINOP_XOR:
645 return IsFP ? -1 : Instruction::Xor;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000646 }
647}
648
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000649static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
650 switch (Val) {
651 default: return AtomicRMWInst::BAD_BINOP;
652 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
653 case bitc::RMW_ADD: return AtomicRMWInst::Add;
654 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
655 case bitc::RMW_AND: return AtomicRMWInst::And;
656 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
657 case bitc::RMW_OR: return AtomicRMWInst::Or;
658 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
659 case bitc::RMW_MAX: return AtomicRMWInst::Max;
660 case bitc::RMW_MIN: return AtomicRMWInst::Min;
661 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
662 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
663 }
664}
665
Eli Friedmanfee02c62011-07-25 23:16:38 +0000666static AtomicOrdering GetDecodedOrdering(unsigned Val) {
667 switch (Val) {
668 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
669 case bitc::ORDERING_UNORDERED: return Unordered;
670 case bitc::ORDERING_MONOTONIC: return Monotonic;
671 case bitc::ORDERING_ACQUIRE: return Acquire;
672 case bitc::ORDERING_RELEASE: return Release;
673 case bitc::ORDERING_ACQREL: return AcquireRelease;
674 default: // Map unknown orderings to sequentially-consistent.
675 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
676 }
677}
678
679static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
680 switch (Val) {
681 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
682 default: // Map unknown scopes to cross-thread.
683 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
684 }
685}
686
David Majnemerdad0a642014-06-27 18:19:56 +0000687static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
688 switch (Val) {
689 default: // Map unknown selection kinds to any.
690 case bitc::COMDAT_SELECTION_KIND_ANY:
691 return Comdat::Any;
692 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
693 return Comdat::ExactMatch;
694 case bitc::COMDAT_SELECTION_KIND_LARGEST:
695 return Comdat::Largest;
696 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
697 return Comdat::NoDuplicates;
698 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
699 return Comdat::SameSize;
700 }
701}
702
Nico Rieck7157bb72014-01-14 15:22:47 +0000703static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
704 switch (Val) {
705 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
706 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
707 }
708}
709
Gabor Greiff6caff662008-05-10 08:32:32 +0000710namespace llvm {
Chris Lattner1663cca2007-04-24 05:48:56 +0000711namespace {
712 /// @brief A class for maintaining the slot number definition
713 /// as a placeholder for the actual definition for forward constants defs.
714 class ConstantPlaceHolder : public ConstantExpr {
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000715 void operator=(const ConstantPlaceHolder &) = delete;
Gabor Greife9ecc682008-04-06 20:25:17 +0000716 public:
717 // allocate space for exactly one operand
718 void *operator new(size_t s) {
719 return User::operator new(s, 1);
720 }
Chris Lattner229907c2011-07-18 04:54:35 +0000721 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
Gabor Greiff6caff662008-05-10 08:32:32 +0000722 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000723 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
Chris Lattner1663cca2007-04-24 05:48:56 +0000724 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000725
Chris Lattner74429932008-08-21 02:34:16 +0000726 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
Chris Lattner74429932008-08-21 02:34:16 +0000727 static bool classof(const Value *V) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000728 return isa<ConstantExpr>(V) &&
Chris Lattner74429932008-08-21 02:34:16 +0000729 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
730 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000731
732
Gabor Greiff6caff662008-05-10 08:32:32 +0000733 /// Provide fast operand accessors
Richard Trieue3d126c2014-11-21 02:42:08 +0000734 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Chris Lattner1663cca2007-04-24 05:48:56 +0000735 };
736}
737
Chris Lattner2d8cd802009-03-31 22:55:09 +0000738// FIXME: can we inherit this from ConstantExpr?
Gabor Greiff6caff662008-05-10 08:32:32 +0000739template <>
Jay Foadc8adf5f2011-01-11 15:07:38 +0000740struct OperandTraits<ConstantPlaceHolder> :
741 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greiff6caff662008-05-10 08:32:32 +0000742};
Richard Trieue3d126c2014-11-21 02:42:08 +0000743DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
Gabor Greiff6caff662008-05-10 08:32:32 +0000744}
745
Chris Lattner2d8cd802009-03-31 22:55:09 +0000746
747void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
748 if (Idx == size()) {
749 push_back(V);
750 return;
751 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000752
Chris Lattner2d8cd802009-03-31 22:55:09 +0000753 if (Idx >= size())
754 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000755
Chris Lattner2d8cd802009-03-31 22:55:09 +0000756 WeakVH &OldV = ValuePtrs[Idx];
Craig Topper2617dcc2014-04-15 06:32:26 +0000757 if (!OldV) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000758 OldV = V;
759 return;
760 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000761
Chris Lattner2d8cd802009-03-31 22:55:09 +0000762 // Handle constants and non-constants (e.g. instrs) differently for
763 // efficiency.
764 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
765 ResolveConstants.push_back(std::make_pair(PHC, Idx));
766 OldV = V;
767 } else {
768 // If there was a forward reference to this value, replace it.
769 Value *PrevVal = OldV;
770 OldV->replaceAllUsesWith(V);
771 delete PrevVal;
Gabor Greiff6caff662008-05-10 08:32:32 +0000772 }
773}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000774
Gabor Greiff6caff662008-05-10 08:32:32 +0000775
Chris Lattner1663cca2007-04-24 05:48:56 +0000776Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattner229907c2011-07-18 04:54:35 +0000777 Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000778 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000779 resize(Idx + 1);
Chris Lattner1663cca2007-04-24 05:48:56 +0000780
Chris Lattner2d8cd802009-03-31 22:55:09 +0000781 if (Value *V = ValuePtrs[Idx]) {
Chris Lattner83930552007-05-01 07:01:57 +0000782 assert(Ty == V->getType() && "Type mismatch in constant table!");
783 return cast<Constant>(V);
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000784 }
Chris Lattner1663cca2007-04-24 05:48:56 +0000785
786 // Create and return a placeholder, which will later be RAUW'd.
Owen Andersone9f98042009-07-07 20:18:58 +0000787 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000788 ValuePtrs[Idx] = C;
Chris Lattner1663cca2007-04-24 05:48:56 +0000789 return C;
790}
791
Chris Lattner229907c2011-07-18 04:54:35 +0000792Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Filipe Cabecinhasbad07792015-04-30 00:52:42 +0000793 // Bail out for a clearly invalid value. This would make us call resize(0)
794 if (Idx == UINT_MAX)
795 return nullptr;
796
Chris Lattner2d8cd802009-03-31 22:55:09 +0000797 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000798 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000799
Chris Lattner2d8cd802009-03-31 22:55:09 +0000800 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhasb435d0f2015-04-28 20:18:47 +0000801 // If the types don't match, it's invalid.
802 if (Ty && Ty != V->getType())
803 return nullptr;
Chris Lattner83930552007-05-01 07:01:57 +0000804 return V;
805 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000806
Chris Lattner1fc27f02007-05-02 05:16:49 +0000807 // No type specified, must be invalid reference.
Craig Topper2617dcc2014-04-15 06:32:26 +0000808 if (!Ty) return nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000809
Chris Lattner83930552007-05-01 07:01:57 +0000810 // Create and return a placeholder, which will later be RAUW'd.
811 Value *V = new Argument(Ty);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000812 ValuePtrs[Idx] = V;
Chris Lattner83930552007-05-01 07:01:57 +0000813 return V;
814}
815
Chris Lattner74429932008-08-21 02:34:16 +0000816/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
817/// resolves any forward references. The idea behind this is that we sometimes
818/// get constants (such as large arrays) which reference *many* forward ref
819/// constants. Replacing each of these causes a lot of thrashing when
820/// building/reuniquing the constant. Instead of doing this, we look at all the
821/// uses and rewrite all the place holders at once for any constant that uses
822/// a placeholder.
823void BitcodeReaderValueList::ResolveConstantForwardRefs() {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000824 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattner74429932008-08-21 02:34:16 +0000825 // binary search.
826 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000827
Chris Lattner74429932008-08-21 02:34:16 +0000828 SmallVector<Constant*, 64> NewOps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000829
Chris Lattner74429932008-08-21 02:34:16 +0000830 while (!ResolveConstants.empty()) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000831 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattner74429932008-08-21 02:34:16 +0000832 Constant *Placeholder = ResolveConstants.back().first;
833 ResolveConstants.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000834
Chris Lattner74429932008-08-21 02:34:16 +0000835 // Loop over all users of the placeholder, updating them to reference the
836 // new value. If they reference more than one placeholder, update them all
837 // at once.
838 while (!Placeholder->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000839 auto UI = Placeholder->user_begin();
Gabor Greif2c0ab482010-07-09 16:01:21 +0000840 User *U = *UI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000841
Chris Lattner74429932008-08-21 02:34:16 +0000842 // If the using object isn't uniqued, just update the operands. This
843 // handles instructions and initializers for global variables.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000844 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattner479c5d92008-08-21 17:31:45 +0000845 UI.getUse().set(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +0000846 continue;
847 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000848
Chris Lattner74429932008-08-21 02:34:16 +0000849 // Otherwise, we have a constant that uses the placeholder. Replace that
850 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000851 Constant *UserC = cast<Constant>(U);
Chris Lattner74429932008-08-21 02:34:16 +0000852 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
853 I != E; ++I) {
854 Value *NewOp;
855 if (!isa<ConstantPlaceHolder>(*I)) {
856 // Not a placeholder reference.
857 NewOp = *I;
858 } else if (*I == Placeholder) {
859 // Common case is that it just references this one placeholder.
860 NewOp = RealVal;
861 } else {
862 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000863 ResolveConstantsTy::iterator It =
864 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattner74429932008-08-21 02:34:16 +0000865 std::pair<Constant*, unsigned>(cast<Constant>(*I),
866 0));
867 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000868 NewOp = operator[](It->second);
Chris Lattner74429932008-08-21 02:34:16 +0000869 }
870
871 NewOps.push_back(cast<Constant>(NewOp));
872 }
873
874 // Make the new constant.
875 Constant *NewC;
876 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad83be3612011-06-22 09:24:39 +0000877 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000878 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnercc19efa2011-06-20 04:01:31 +0000879 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000880 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner69229312011-02-15 00:14:00 +0000881 NewC = ConstantVector::get(NewOps);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000882 } else {
883 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foad5c984e562011-04-13 13:46:01 +0000884 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000885 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000886
Chris Lattner74429932008-08-21 02:34:16 +0000887 UserC->replaceAllUsesWith(NewC);
888 UserC->destroyConstant();
889 NewOps.clear();
890 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000891
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000892 // Update all ValueHandles, they should be the only users at this point.
893 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +0000894 delete Placeholder;
895 }
896}
897
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000898void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +0000899 if (Idx == size()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000900 push_back(MD);
Devang Patel05eb6172009-08-04 06:00:18 +0000901 return;
902 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000903
Devang Patel05eb6172009-08-04 06:00:18 +0000904 if (Idx >= size())
905 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000906
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000907 TrackingMDRef &OldMD = MDValuePtrs[Idx];
908 if (!OldMD) {
909 OldMD.reset(MD);
Devang Patel05eb6172009-08-04 06:00:18 +0000910 return;
911 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000912
Devang Patel05eb6172009-08-04 06:00:18 +0000913 // If there was a forward reference to this value, replace it.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000914 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000915 PrevMD->replaceAllUsesWith(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000916 --NumFwdRefs;
Devang Patel05eb6172009-08-04 06:00:18 +0000917}
918
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000919Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +0000920 if (Idx >= size())
921 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000922
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000923 if (Metadata *MD = MDValuePtrs[Idx])
924 return MD;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000925
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +0000926 // Track forward refs to be resolved later.
927 if (AnyFwdRefs) {
928 MinFwdRef = std::min(MinFwdRef, Idx);
929 MaxFwdRef = std::max(MaxFwdRef, Idx);
930 } else {
931 AnyFwdRefs = true;
932 MinFwdRef = MaxFwdRef = Idx;
933 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000934 ++NumFwdRefs;
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +0000935
936 // Create and return a placeholder, which will later be RAUW'd.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000937 Metadata *MD = MDNode::getTemporary(Context, None).release();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000938 MDValuePtrs[Idx].reset(MD);
939 return MD;
940}
941
942void BitcodeReaderMDValueList::tryToResolveCycles() {
943 if (!AnyFwdRefs)
944 // Nothing to do.
945 return;
946
947 if (NumFwdRefs)
948 // Still forward references... can't resolve cycles.
949 return;
950
951 // Resolve any cycles.
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +0000952 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
953 auto &MD = MDValuePtrs[I];
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +0000954 auto *N = dyn_cast_or_null<MDNode>(MD);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +0000955 if (!N)
956 continue;
957
958 assert(!N->isTemporary() && "Unexpected forward reference");
959 N->resolveCycles();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000960 }
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +0000961
962 // Make sure we return early again until there's another forward ref.
963 AnyFwdRefs = false;
Devang Patel05eb6172009-08-04 06:00:18 +0000964}
Chris Lattner1314b992007-04-22 06:23:29 +0000965
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000966Type *BitcodeReader::getTypeByID(unsigned ID) {
967 // The type table size is always specified correctly.
968 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +0000969 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +0000970
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000971 if (Type *Ty = TypeList[ID])
972 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000973
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000974 // If we have a forward reference, the only possible case is when it is to a
975 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +0000976 return TypeList[ID] = createIdentifiedStructType(Context);
977}
978
979StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
980 StringRef Name) {
981 auto *Ret = StructType::create(Context, Name);
982 IdentifiedStructTypes.push_back(Ret);
983 return Ret;
984}
985
986StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
987 auto *Ret = StructType::create(Context);
988 IdentifiedStructTypes.push_back(Ret);
989 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +0000990}
991
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000992
Chris Lattnerfee5a372007-05-04 03:30:17 +0000993//===----------------------------------------------------------------------===//
994// Functions for parsing blocks from the bitcode file
995//===----------------------------------------------------------------------===//
996
Bill Wendling56aeccc2013-02-04 23:32:23 +0000997
998/// \brief This fills an AttrBuilder object with the LLVM attributes that have
999/// been decoded from the given integer. This function must stay in sync with
1000/// 'encodeLLVMAttributesForBitcode'.
1001static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1002 uint64_t EncodedAttrs) {
1003 // FIXME: Remove in 4.0.
1004
1005 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1006 // the bits above 31 down by 11 bits.
1007 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1008 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1009 "Alignment must be a power of two.");
1010
1011 if (Alignment)
1012 B.addAlignmentAttr(Alignment);
Kostya Serebryanyd688bab2013-02-11 08:13:54 +00001013 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
Bill Wendling56aeccc2013-02-04 23:32:23 +00001014 (EncodedAttrs & 0xffff));
1015}
1016
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001017std::error_code BitcodeReader::ParseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001018 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001019 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001020
Devang Patela05633e2008-09-26 22:53:05 +00001021 if (!MAttributes.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001022 return Error("Invalid multiple blocks");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001023
Chris Lattnerfee5a372007-05-04 03:30:17 +00001024 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001025
Bill Wendling71173cb2013-01-27 00:36:48 +00001026 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001027
Chris Lattnerfee5a372007-05-04 03:30:17 +00001028 // Read all the records.
1029 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001030 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001031
Chris Lattner27d38752013-01-20 02:13:19 +00001032 switch (Entry.Kind) {
1033 case BitstreamEntry::SubBlock: // Handled for us already.
1034 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001035 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001036 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001037 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001038 case BitstreamEntry::Record:
1039 // The interesting case.
1040 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001041 }
Joe Abbey97b7a172013-02-06 22:14:06 +00001042
Chris Lattnerfee5a372007-05-04 03:30:17 +00001043 // Read a record.
1044 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001045 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +00001046 default: // Default behavior: ignore.
1047 break;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001048 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1049 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +00001050 if (Record.size() & 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001051 return Error("Invalid record");
Chris Lattnerfee5a372007-05-04 03:30:17 +00001052
Chris Lattnerfee5a372007-05-04 03:30:17 +00001053 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +00001054 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001055 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling60011b82013-01-29 01:43:29 +00001056 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +00001057 }
Devang Patela05633e2008-09-26 22:53:05 +00001058
Bill Wendlinge94d8432012-12-07 23:16:57 +00001059 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +00001060 Attrs.clear();
1061 break;
1062 }
Bill Wendling0dc08912013-02-12 08:13:50 +00001063 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1064 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1065 Attrs.push_back(MAttributeGroups[Record[i]]);
1066
1067 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1068 Attrs.clear();
1069 break;
1070 }
Duncan Sands04eb67e2007-11-20 14:09:29 +00001071 }
Chris Lattnerfee5a372007-05-04 03:30:17 +00001072 }
1073}
1074
Reid Klecknere9f36af2013-11-12 01:31:00 +00001075// Returns Attribute::None on unrecognized codes.
1076static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
1077 switch (Code) {
1078 default:
1079 return Attribute::None;
1080 case bitc::ATTR_KIND_ALIGNMENT:
1081 return Attribute::Alignment;
1082 case bitc::ATTR_KIND_ALWAYS_INLINE:
1083 return Attribute::AlwaysInline;
1084 case bitc::ATTR_KIND_BUILTIN:
1085 return Attribute::Builtin;
1086 case bitc::ATTR_KIND_BY_VAL:
1087 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +00001088 case bitc::ATTR_KIND_IN_ALLOCA:
1089 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001090 case bitc::ATTR_KIND_COLD:
1091 return Attribute::Cold;
1092 case bitc::ATTR_KIND_INLINE_HINT:
1093 return Attribute::InlineHint;
1094 case bitc::ATTR_KIND_IN_REG:
1095 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +00001096 case bitc::ATTR_KIND_JUMP_TABLE:
1097 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001098 case bitc::ATTR_KIND_MIN_SIZE:
1099 return Attribute::MinSize;
1100 case bitc::ATTR_KIND_NAKED:
1101 return Attribute::Naked;
1102 case bitc::ATTR_KIND_NEST:
1103 return Attribute::Nest;
1104 case bitc::ATTR_KIND_NO_ALIAS:
1105 return Attribute::NoAlias;
1106 case bitc::ATTR_KIND_NO_BUILTIN:
1107 return Attribute::NoBuiltin;
1108 case bitc::ATTR_KIND_NO_CAPTURE:
1109 return Attribute::NoCapture;
1110 case bitc::ATTR_KIND_NO_DUPLICATE:
1111 return Attribute::NoDuplicate;
1112 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1113 return Attribute::NoImplicitFloat;
1114 case bitc::ATTR_KIND_NO_INLINE:
1115 return Attribute::NoInline;
1116 case bitc::ATTR_KIND_NON_LAZY_BIND:
1117 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001118 case bitc::ATTR_KIND_NON_NULL:
1119 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001120 case bitc::ATTR_KIND_DEREFERENCEABLE:
1121 return Attribute::Dereferenceable;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001122 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1123 return Attribute::DereferenceableOrNull;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001124 case bitc::ATTR_KIND_NO_RED_ZONE:
1125 return Attribute::NoRedZone;
1126 case bitc::ATTR_KIND_NO_RETURN:
1127 return Attribute::NoReturn;
1128 case bitc::ATTR_KIND_NO_UNWIND:
1129 return Attribute::NoUnwind;
1130 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1131 return Attribute::OptimizeForSize;
1132 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1133 return Attribute::OptimizeNone;
1134 case bitc::ATTR_KIND_READ_NONE:
1135 return Attribute::ReadNone;
1136 case bitc::ATTR_KIND_READ_ONLY:
1137 return Attribute::ReadOnly;
1138 case bitc::ATTR_KIND_RETURNED:
1139 return Attribute::Returned;
1140 case bitc::ATTR_KIND_RETURNS_TWICE:
1141 return Attribute::ReturnsTwice;
1142 case bitc::ATTR_KIND_S_EXT:
1143 return Attribute::SExt;
1144 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1145 return Attribute::StackAlignment;
1146 case bitc::ATTR_KIND_STACK_PROTECT:
1147 return Attribute::StackProtect;
1148 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1149 return Attribute::StackProtectReq;
1150 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1151 return Attribute::StackProtectStrong;
1152 case bitc::ATTR_KIND_STRUCT_RET:
1153 return Attribute::StructRet;
1154 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1155 return Attribute::SanitizeAddress;
1156 case bitc::ATTR_KIND_SANITIZE_THREAD:
1157 return Attribute::SanitizeThread;
1158 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1159 return Attribute::SanitizeMemory;
1160 case bitc::ATTR_KIND_UW_TABLE:
1161 return Attribute::UWTable;
1162 case bitc::ATTR_KIND_Z_EXT:
1163 return Attribute::ZExt;
1164 }
1165}
1166
JF Bastien30bf96b2015-02-22 19:32:03 +00001167std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1168 unsigned &Alignment) {
1169 // Note: Alignment in bitcode files is incremented by 1, so that zero
1170 // can be used for default alignment.
1171 if (Exponent > Value::MaxAlignmentExponent + 1)
1172 return Error("Invalid alignment value");
1173 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1174 return std::error_code();
1175}
1176
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001177std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
1178 Attribute::AttrKind *Kind) {
Reid Klecknere9f36af2013-11-12 01:31:00 +00001179 *Kind = GetAttrFromCode(Code);
1180 if (*Kind == Attribute::None)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001181 return Error(BitcodeError::CorruptedBitcode,
1182 "Unknown attribute kind (" + Twine(Code) + ")");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001183 return std::error_code();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001184}
1185
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001186std::error_code BitcodeReader::ParseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +00001187 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001188 return Error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001189
1190 if (!MAttributeGroups.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001191 return Error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +00001192
1193 SmallVector<uint64_t, 64> Record;
1194
1195 // Read all the records.
1196 while (1) {
1197 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1198
1199 switch (Entry.Kind) {
1200 case BitstreamEntry::SubBlock: // Handled for us already.
1201 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001202 return Error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +00001203 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001204 return std::error_code();
Bill Wendlingba629332013-02-10 23:24:25 +00001205 case BitstreamEntry::Record:
1206 // The interesting case.
1207 break;
1208 }
1209
1210 // Read a record.
1211 Record.clear();
1212 switch (Stream.readRecord(Entry.ID, Record)) {
1213 default: // Default behavior: ignore.
1214 break;
1215 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1216 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001217 return Error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001218
Bill Wendlinge46707e2013-02-11 22:32:29 +00001219 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +00001220 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1221
1222 AttrBuilder B;
1223 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1224 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001225 Attribute::AttrKind Kind;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001226 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001227 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001228
1229 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +00001230 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001231 Attribute::AttrKind Kind;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001232 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001233 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001234 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001235 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001236 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001237 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001238 else if (Kind == Attribute::Dereferenceable)
1239 B.addDereferenceableAttr(Record[++i]);
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001240 else if (Kind == Attribute::DereferenceableOrNull)
1241 B.addDereferenceableOrNullAttr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +00001242 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +00001243 assert((Record[i] == 3 || Record[i] == 4) &&
1244 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +00001245 bool HasValue = (Record[i++] == 4);
1246 SmallString<64> KindStr;
1247 SmallString<64> ValStr;
1248
1249 while (Record[i] != 0 && i != e)
1250 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001251 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001252
1253 if (HasValue) {
1254 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +00001255 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +00001256 while (Record[i] != 0 && i != e)
1257 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001258 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001259 }
1260
1261 B.addAttribute(KindStr.str(), ValStr.str());
1262 }
1263 }
1264
Bill Wendlinge46707e2013-02-11 22:32:29 +00001265 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +00001266 break;
1267 }
1268 }
1269 }
1270}
1271
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001272std::error_code BitcodeReader::ParseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001273 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001274 return Error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +00001275
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001276 return ParseTypeTableBody();
1277}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001278
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001279std::error_code BitcodeReader::ParseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +00001280 if (!TypeList.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001281 return Error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +00001282
1283 SmallVector<uint64_t, 64> Record;
1284 unsigned NumRecords = 0;
1285
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001286 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +00001287
Chris Lattner1314b992007-04-22 06:23:29 +00001288 // Read all the records for this type table.
1289 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001290 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001291
Chris Lattner27d38752013-01-20 02:13:19 +00001292 switch (Entry.Kind) {
1293 case BitstreamEntry::SubBlock: // Handled for us already.
1294 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001295 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001296 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +00001297 if (NumRecords != TypeList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001298 return Error("Malformed block");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001299 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001300 case BitstreamEntry::Record:
1301 // The interesting case.
1302 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001303 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001304
Chris Lattner1314b992007-04-22 06:23:29 +00001305 // Read a record.
1306 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001307 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001308 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001309 default:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001310 return Error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +00001311 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1312 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1313 // type list. This allows us to reserve space.
1314 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001315 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001316 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001317 continue;
Chris Lattner1314b992007-04-22 06:23:29 +00001318 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +00001319 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001320 break;
Dan Gohman518cda42011-12-17 00:04:22 +00001321 case bitc::TYPE_CODE_HALF: // HALF
1322 ResultTy = Type::getHalfTy(Context);
1323 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001324 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +00001325 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001326 break;
1327 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +00001328 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001329 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001330 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +00001331 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001332 break;
1333 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001334 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001335 break;
1336 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001337 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001338 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001339 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +00001340 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001341 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001342 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +00001343 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001344 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +00001345 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1346 ResultTy = Type::getX86_MMXTy(Context);
1347 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001348 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
Chris Lattner1314b992007-04-22 06:23:29 +00001349 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001350 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001351
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001352 uint64_t NumBits = Record[0];
1353 if (NumBits < IntegerType::MIN_INT_BITS ||
1354 NumBits > IntegerType::MAX_INT_BITS)
1355 return Error("Bitwidth for integer type out of range");
1356 ResultTy = IntegerType::get(Context, NumBits);
Chris Lattner1314b992007-04-22 06:23:29 +00001357 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001358 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001359 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001360 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +00001361 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001362 return Error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001363 unsigned AddressSpace = 0;
1364 if (Record.size() == 2)
1365 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001366 ResultTy = getTypeByID(Record[0]);
Filipe Cabecinhasd8a1bcd2015-04-29 02:27:28 +00001367 if (!ResultTy ||
1368 !PointerType::isValidElementType(ResultTy))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001369 return Error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001370 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +00001371 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001372 }
Nuno Lopes561dae02012-05-23 15:19:39 +00001373 case bitc::TYPE_CODE_FUNCTION_OLD: {
1374 // FIXME: attrid is dead, remove it in LLVM 4.0
1375 // FUNCTION: [vararg, attrid, retty, paramty x N]
1376 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001377 return Error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +00001378 SmallVector<Type*, 8> ArgTys;
1379 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1380 if (Type *T = getTypeByID(Record[i]))
1381 ArgTys.push_back(T);
1382 else
1383 break;
1384 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001385
Nuno Lopes561dae02012-05-23 15:19:39 +00001386 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001387 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001388 return Error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +00001389
1390 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1391 break;
1392 }
Chad Rosier95898722011-11-03 00:14:01 +00001393 case bitc::TYPE_CODE_FUNCTION: {
1394 // FUNCTION: [vararg, retty, paramty x N]
1395 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001396 return Error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001397 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +00001398 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1399 if (Type *T = getTypeByID(Record[i]))
1400 ArgTys.push_back(T);
1401 else
1402 break;
1403 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001404
Chad Rosier95898722011-11-03 00:14:01 +00001405 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001406 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001407 return Error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +00001408
1409 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1410 break;
1411 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001412 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +00001413 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001414 return Error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001415 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001416 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1417 if (Type *T = getTypeByID(Record[i]))
1418 EltTys.push_back(T);
1419 else
1420 break;
1421 }
1422 if (EltTys.size() != Record.size()-1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001423 return Error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001424 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001425 break;
1426 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001427 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1428 if (ConvertToString(Record, 0, TypeName))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001429 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001430 continue;
1431
1432 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1433 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001434 return Error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001435
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001436 if (NumRecords >= TypeList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001437 return Error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001438
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001439 // Check to see if this was forward referenced, if so fill in the temp.
1440 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1441 if (Res) {
1442 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001443 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001444 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001445 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001446 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001447
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001448 SmallVector<Type*, 8> EltTys;
1449 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1450 if (Type *T = getTypeByID(Record[i]))
1451 EltTys.push_back(T);
1452 else
1453 break;
1454 }
1455 if (EltTys.size() != Record.size()-1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001456 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001457 Res->setBody(EltTys, Record[0]);
1458 ResultTy = Res;
1459 break;
1460 }
1461 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1462 if (Record.size() != 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001463 return Error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001464
1465 if (NumRecords >= TypeList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001466 return Error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001467
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001468 // Check to see if this was forward referenced, if so fill in the temp.
1469 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1470 if (Res) {
1471 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001472 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001473 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001474 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001475 TypeName.clear();
1476 ResultTy = Res;
1477 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001478 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001479 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1480 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001481 return Error("Invalid record");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001482 ResultTy = getTypeByID(Record[1]);
1483 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001484 return Error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001485 ResultTy = ArrayType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001486 break;
1487 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1488 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001489 return Error("Invalid record");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001490 ResultTy = getTypeByID(Record[1]);
1491 if (!ResultTy || !StructType::isValidElementType(ResultTy))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001492 return Error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001493 ResultTy = VectorType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001494 break;
1495 }
1496
1497 if (NumRecords >= TypeList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001498 return Error("Invalid TYPE table");
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001499 if (TypeList[NumRecords])
1500 return Error(
1501 "Invalid TYPE table: Only named structs can be forward referenced");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001502 assert(ResultTy && "Didn't read a type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001503 TypeList[NumRecords++] = ResultTy;
1504 }
1505}
1506
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001507std::error_code BitcodeReader::ParseValueSymbolTable() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001508 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001509 return Error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001510
1511 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001512
David Majnemer3087b222015-01-20 05:58:07 +00001513 Triple TT(TheModule->getTargetTriple());
1514
Chris Lattnerccaa4482007-04-23 21:26:05 +00001515 // Read all the records for this value table.
1516 SmallString<128> ValueName;
1517 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001518 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001519
Chris Lattner27d38752013-01-20 02:13:19 +00001520 switch (Entry.Kind) {
1521 case BitstreamEntry::SubBlock: // Handled for us already.
1522 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001523 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001524 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001525 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001526 case BitstreamEntry::Record:
1527 // The interesting case.
1528 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001529 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001530
Chris Lattnerccaa4482007-04-23 21:26:05 +00001531 // Read a record.
1532 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001533 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001534 default: // Default behavior: unknown type.
1535 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00001536 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattnerccaa4482007-04-23 21:26:05 +00001537 if (ConvertToString(Record, 1, ValueName))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001538 return Error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001539 unsigned ValueID = Record[0];
Karthik Bhat82540e92014-03-27 12:08:23 +00001540 if (ValueID >= ValueList.size() || !ValueList[ValueID])
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001541 return Error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001542 Value *V = ValueList[ValueID];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001543
Daniel Dunbard786b512009-07-26 00:34:27 +00001544 V->setName(StringRef(ValueName.data(), ValueName.size()));
Rafael Espindola12ca34f2015-01-19 15:16:06 +00001545 if (auto *GO = dyn_cast<GlobalObject>(V)) {
David Majnemer3087b222015-01-20 05:58:07 +00001546 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1547 if (TT.isOSBinFormatMachO())
1548 GO->setComdat(nullptr);
1549 else
1550 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1551 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00001552 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001553 ValueName.clear();
1554 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00001555 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00001556 case bitc::VST_CODE_BBENTRY: {
Chris Lattner6be58c62007-05-03 22:18:21 +00001557 if (ConvertToString(Record, 1, ValueName))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001558 return Error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00001559 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001560 if (!BB)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001561 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001562
Daniel Dunbard786b512009-07-26 00:34:27 +00001563 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00001564 ValueName.clear();
1565 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001566 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00001567 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001568 }
1569}
1570
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001571static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1572
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001573std::error_code BitcodeReader::ParseMetadata() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00001574 IsMetadataMaterialized = true;
Devang Patel89923232010-01-11 18:52:33 +00001575 unsigned NextMDValueNo = MDValueList.size();
Devang Patel7428d8a2009-07-22 17:43:22 +00001576
1577 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001578 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001579
Devang Patel7428d8a2009-07-22 17:43:22 +00001580 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001581
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001582 auto getMD =
1583 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1584 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1585 if (ID)
1586 return getMD(ID - 1);
1587 return nullptr;
1588 };
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001589 auto getMDString = [&](unsigned ID) -> MDString *{
1590 // This requires that the ID is not really a forward reference. In
1591 // particular, the MDString must already have been resolved.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001592 return cast_or_null<MDString>(getMDOrNull(ID));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001593 };
1594
1595#define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1596 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1597
Devang Patel7428d8a2009-07-22 17:43:22 +00001598 // Read all the records.
1599 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001600 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001601
Chris Lattner27d38752013-01-20 02:13:19 +00001602 switch (Entry.Kind) {
1603 case BitstreamEntry::SubBlock: // Handled for us already.
1604 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001605 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001606 case BitstreamEntry::EndBlock:
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001607 MDValueList.tryToResolveCycles();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001608 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001609 case BitstreamEntry::Record:
1610 // The interesting case.
1611 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00001612 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001613
Devang Patel7428d8a2009-07-22 17:43:22 +00001614 // Read a record.
1615 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001616 unsigned Code = Stream.readRecord(Entry.ID, Record);
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001617 bool IsDistinct = false;
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00001618 switch (Code) {
Devang Patel7428d8a2009-07-22 17:43:22 +00001619 default: // Default behavior: ignore.
1620 break;
Devang Patel27c87ff2009-07-29 22:34:41 +00001621 case bitc::METADATA_NAME: {
Chris Lattner8d140532013-01-20 02:54:05 +00001622 // Read name of the named metadata.
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001623 SmallString<8> Name(Record.begin(), Record.end());
Devang Patel27c87ff2009-07-29 22:34:41 +00001624 Record.clear();
1625 Code = Stream.ReadCode();
1626
Chris Lattnerb8778552011-06-17 17:50:30 +00001627 // METADATA_NAME is always followed by METADATA_NAMED_NODE.
Chris Lattner27d38752013-01-20 02:13:19 +00001628 unsigned NextBitCode = Stream.readRecord(Code, Record);
Chris Lattnerb8778552011-06-17 17:50:30 +00001629 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
Devang Patel27c87ff2009-07-29 22:34:41 +00001630
1631 // Read named metadata elements.
1632 unsigned Size = Record.size();
Dan Gohman2637cc12010-07-21 23:38:33 +00001633 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patel27c87ff2009-07-29 22:34:41 +00001634 for (unsigned i = 0; i != Size; ++i) {
Karthik Bhat82540e92014-03-27 12:08:23 +00001635 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
Craig Topper2617dcc2014-04-15 06:32:26 +00001636 if (!MD)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001637 return Error("Invalid record");
Dan Gohman2637cc12010-07-21 23:38:33 +00001638 NMD->addOperand(MD);
Devang Patel27c87ff2009-07-29 22:34:41 +00001639 }
Devang Patel27c87ff2009-07-29 22:34:41 +00001640 break;
1641 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00001642 case bitc::METADATA_OLD_FN_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00001643 // FIXME: Remove in 4.0.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001644 // This is a LocalAsMetadata record, the only type of function-local
1645 // metadata.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001646 if (Record.size() % 2 == 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001647 return Error("Invalid record");
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001648
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001649 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1650 // to be legal, but there's no upgrade path.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001651 auto dropRecord = [&] {
1652 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++);
1653 };
1654 if (Record.size() != 2) {
1655 dropRecord();
1656 break;
1657 }
1658
1659 Type *Ty = getTypeByID(Record[0]);
1660 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1661 dropRecord();
1662 break;
1663 }
1664
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001665 MDValueList.AssignValue(
1666 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1667 NextMDValueNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001668 break;
1669 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00001670 case bitc::METADATA_OLD_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00001671 // FIXME: Remove in 4.0.
Dan Gohman1e0213a2010-07-13 19:33:27 +00001672 if (Record.size() % 2 == 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001673 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001674
Devang Patele059ba6e2009-07-23 01:07:34 +00001675 unsigned Size = Record.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001676 SmallVector<Metadata *, 8> Elts;
Devang Patele059ba6e2009-07-23 01:07:34 +00001677 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00001678 Type *Ty = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00001679 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001680 return Error("Invalid record");
Chris Lattnerfdd87902009-10-05 05:54:46 +00001681 if (Ty->isMetadataTy())
Devang Patel05eb6172009-08-04 06:00:18 +00001682 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001683 else if (!Ty->isVoidTy()) {
1684 auto *MD =
1685 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1686 assert(isa<ConstantAsMetadata>(MD) &&
1687 "Expected non-function-local metadata");
1688 Elts.push_back(MD);
1689 } else
Craig Topper2617dcc2014-04-15 06:32:26 +00001690 Elts.push_back(nullptr);
Devang Patele059ba6e2009-07-23 01:07:34 +00001691 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001692 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
Devang Patele059ba6e2009-07-23 01:07:34 +00001693 break;
1694 }
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001695 case bitc::METADATA_VALUE: {
1696 if (Record.size() != 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001697 return Error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001698
1699 Type *Ty = getTypeByID(Record[0]);
1700 if (Ty->isMetadataTy() || Ty->isVoidTy())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001701 return Error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001702
1703 MDValueList.AssignValue(
1704 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1705 NextMDValueNo++);
1706 break;
1707 }
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001708 case bitc::METADATA_DISTINCT_NODE:
1709 IsDistinct = true;
1710 // fallthrough...
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001711 case bitc::METADATA_NODE: {
1712 SmallVector<Metadata *, 8> Elts;
1713 Elts.reserve(Record.size());
1714 for (unsigned ID : Record)
1715 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001716 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1717 : MDNode::get(Context, Elts),
1718 NextMDValueNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001719 break;
1720 }
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001721 case bitc::METADATA_LOCATION: {
1722 if (Record.size() != 5)
1723 return Error("Invalid record");
1724
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001725 unsigned Line = Record[1];
1726 unsigned Column = Record[2];
1727 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1728 Metadata *InlinedAt =
1729 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00001730 MDValueList.AssignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001731 GET_OR_DISTINCT(DILocation, Record[0],
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00001732 (Context, Line, Column, Scope, InlinedAt)),
1733 NextMDValueNo++);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001734 break;
1735 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001736 case bitc::METADATA_GENERIC_DEBUG: {
1737 if (Record.size() < 4)
1738 return Error("Invalid record");
1739
1740 unsigned Tag = Record[1];
1741 unsigned Version = Record[2];
1742
1743 if (Tag >= 1u << 16 || Version != 0)
1744 return Error("Invalid record");
1745
1746 auto *Header = getMDString(Record[3]);
1747 SmallVector<Metadata *, 8> DwarfOps;
1748 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1749 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1750 : nullptr);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001751 MDValueList.AssignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001752 (Context, Tag, Header, DwarfOps)),
1753 NextMDValueNo++);
1754 break;
1755 }
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001756 case bitc::METADATA_SUBRANGE: {
1757 if (Record.size() != 3)
1758 return Error("Invalid record");
1759
1760 MDValueList.AssignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001761 GET_OR_DISTINCT(DISubrange, Record[0],
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001762 (Context, Record[1], unrotateSign(Record[2]))),
1763 NextMDValueNo++);
1764 break;
1765 }
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001766 case bitc::METADATA_ENUMERATOR: {
1767 if (Record.size() != 3)
1768 return Error("Invalid record");
1769
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001770 MDValueList.AssignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001771 (Context, unrotateSign(Record[1]),
1772 getMDString(Record[2]))),
1773 NextMDValueNo++);
1774 break;
1775 }
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001776 case bitc::METADATA_BASIC_TYPE: {
1777 if (Record.size() != 6)
1778 return Error("Invalid record");
1779
1780 MDValueList.AssignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001781 GET_OR_DISTINCT(DIBasicType, Record[0],
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001782 (Context, Record[1], getMDString(Record[2]),
1783 Record[3], Record[4], Record[5])),
1784 NextMDValueNo++);
1785 break;
1786 }
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001787 case bitc::METADATA_DERIVED_TYPE: {
1788 if (Record.size() != 12)
1789 return Error("Invalid record");
1790
1791 MDValueList.AssignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001792 GET_OR_DISTINCT(DIDerivedType, Record[0],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001793 (Context, Record[1], getMDString(Record[2]),
1794 getMDOrNull(Record[3]), Record[4],
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001795 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1796 Record[7], Record[8], Record[9], Record[10],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001797 getMDOrNull(Record[11]))),
1798 NextMDValueNo++);
1799 break;
1800 }
1801 case bitc::METADATA_COMPOSITE_TYPE: {
1802 if (Record.size() != 16)
1803 return Error("Invalid record");
1804
1805 MDValueList.AssignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001806 GET_OR_DISTINCT(DICompositeType, Record[0],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001807 (Context, Record[1], getMDString(Record[2]),
1808 getMDOrNull(Record[3]), Record[4],
1809 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1810 Record[7], Record[8], Record[9], Record[10],
1811 getMDOrNull(Record[11]), Record[12],
1812 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1813 getMDString(Record[15]))),
1814 NextMDValueNo++);
1815 break;
1816 }
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001817 case bitc::METADATA_SUBROUTINE_TYPE: {
1818 if (Record.size() != 3)
1819 return Error("Invalid record");
1820
1821 MDValueList.AssignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001822 GET_OR_DISTINCT(DISubroutineType, Record[0],
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001823 (Context, Record[1], getMDOrNull(Record[2]))),
1824 NextMDValueNo++);
1825 break;
1826 }
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001827 case bitc::METADATA_FILE: {
1828 if (Record.size() != 3)
1829 return Error("Invalid record");
1830
1831 MDValueList.AssignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001832 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001833 getMDString(Record[2]))),
1834 NextMDValueNo++);
1835 break;
1836 }
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001837 case bitc::METADATA_COMPILE_UNIT: {
1838 if (Record.size() != 14)
1839 return Error("Invalid record");
1840
1841 MDValueList.AssignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001842 GET_OR_DISTINCT(DICompileUnit, Record[0],
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001843 (Context, Record[1], getMDOrNull(Record[2]),
1844 getMDString(Record[3]), Record[4],
1845 getMDString(Record[5]), Record[6],
1846 getMDString(Record[7]), Record[8],
1847 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1848 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1849 getMDOrNull(Record[13]))),
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001850 NextMDValueNo++);
1851 break;
1852 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001853 case bitc::METADATA_SUBPROGRAM: {
1854 if (Record.size() != 19)
1855 return Error("Invalid record");
1856
1857 MDValueList.AssignValue(
1858 GET_OR_DISTINCT(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001859 DISubprogram, Record[0],
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001860 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1861 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1862 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1863 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1864 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1865 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1866 NextMDValueNo++);
1867 break;
1868 }
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001869 case bitc::METADATA_LEXICAL_BLOCK: {
1870 if (Record.size() != 5)
1871 return Error("Invalid record");
1872
1873 MDValueList.AssignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001874 GET_OR_DISTINCT(DILexicalBlock, Record[0],
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001875 (Context, getMDOrNull(Record[1]),
1876 getMDOrNull(Record[2]), Record[3], Record[4])),
1877 NextMDValueNo++);
1878 break;
1879 }
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001880 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1881 if (Record.size() != 4)
1882 return Error("Invalid record");
1883
1884 MDValueList.AssignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001885 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001886 (Context, getMDOrNull(Record[1]),
1887 getMDOrNull(Record[2]), Record[3])),
1888 NextMDValueNo++);
1889 break;
1890 }
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001891 case bitc::METADATA_NAMESPACE: {
1892 if (Record.size() != 5)
1893 return Error("Invalid record");
1894
1895 MDValueList.AssignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001896 GET_OR_DISTINCT(DINamespace, Record[0],
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001897 (Context, getMDOrNull(Record[1]),
1898 getMDOrNull(Record[2]), getMDString(Record[3]),
1899 Record[4])),
1900 NextMDValueNo++);
1901 break;
1902 }
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001903 case bitc::METADATA_TEMPLATE_TYPE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00001904 if (Record.size() != 3)
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001905 return Error("Invalid record");
1906
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001907 MDValueList.AssignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00001908 Record[0],
1909 (Context, getMDString(Record[1]),
1910 getMDOrNull(Record[2]))),
1911 NextMDValueNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001912 break;
1913 }
1914 case bitc::METADATA_TEMPLATE_VALUE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00001915 if (Record.size() != 5)
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001916 return Error("Invalid record");
1917
1918 MDValueList.AssignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001919 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00001920 (Context, Record[1], getMDString(Record[2]),
1921 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001922 NextMDValueNo++);
1923 break;
1924 }
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001925 case bitc::METADATA_GLOBAL_VAR: {
1926 if (Record.size() != 11)
1927 return Error("Invalid record");
1928
1929 MDValueList.AssignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001930 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00001931 (Context, getMDOrNull(Record[1]),
1932 getMDString(Record[2]), getMDString(Record[3]),
1933 getMDOrNull(Record[4]), Record[5],
1934 getMDOrNull(Record[6]), Record[7], Record[8],
1935 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
1936 NextMDValueNo++);
1937 break;
1938 }
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001939 case bitc::METADATA_LOCAL_VAR: {
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00001940 // 10th field is for the obseleted 'inlinedAt:' field.
1941 if (Record.size() != 9 && Record.size() != 10)
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001942 return Error("Invalid record");
1943
1944 MDValueList.AssignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001945 GET_OR_DISTINCT(DILocalVariable, Record[0],
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001946 (Context, Record[1], getMDOrNull(Record[2]),
1947 getMDString(Record[3]), getMDOrNull(Record[4]),
1948 Record[5], getMDOrNull(Record[6]), Record[7],
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00001949 Record[8])),
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00001950 NextMDValueNo++);
1951 break;
1952 }
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001953 case bitc::METADATA_EXPRESSION: {
1954 if (Record.size() < 1)
1955 return Error("Invalid record");
1956
1957 MDValueList.AssignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001958 GET_OR_DISTINCT(DIExpression, Record[0],
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00001959 (Context, makeArrayRef(Record).slice(1))),
1960 NextMDValueNo++);
1961 break;
1962 }
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001963 case bitc::METADATA_OBJC_PROPERTY: {
1964 if (Record.size() != 8)
1965 return Error("Invalid record");
1966
1967 MDValueList.AssignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001968 GET_OR_DISTINCT(DIObjCProperty, Record[0],
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00001969 (Context, getMDString(Record[1]),
1970 getMDOrNull(Record[2]), Record[3],
1971 getMDString(Record[4]), getMDString(Record[5]),
1972 Record[6], getMDOrNull(Record[7]))),
1973 NextMDValueNo++);
1974 break;
1975 }
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001976 case bitc::METADATA_IMPORTED_ENTITY: {
1977 if (Record.size() != 6)
1978 return Error("Invalid record");
1979
1980 MDValueList.AssignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001981 GET_OR_DISTINCT(DIImportedEntity, Record[0],
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00001982 (Context, Record[1], getMDOrNull(Record[2]),
1983 getMDOrNull(Record[3]), Record[4],
1984 getMDString(Record[5]))),
1985 NextMDValueNo++);
1986 break;
1987 }
Devang Patel7428d8a2009-07-22 17:43:22 +00001988 case bitc::METADATA_STRING: {
Eli Bendersky5d5e18d2014-06-25 15:41:00 +00001989 std::string String(Record.begin(), Record.end());
1990 llvm::UpgradeMDStringConstant(String);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001991 Metadata *MD = MDString::get(Context, String);
1992 MDValueList.AssignValue(MD, NextMDValueNo++);
Devang Patel7428d8a2009-07-22 17:43:22 +00001993 break;
1994 }
Devang Patelaf206b82009-09-18 19:26:43 +00001995 case bitc::METADATA_KIND: {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001996 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001997 return Error("Invalid record");
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001998
Devang Patelb1a44772009-09-28 21:14:55 +00001999 unsigned Kind = Record[0];
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002000 SmallString<8> Name(Record.begin()+1, Record.end());
2001
Chris Lattnera0566972009-12-29 09:01:33 +00002002 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman43aa8f02010-07-20 21:42:28 +00002003 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002004 return Error("Conflicting METADATA_KIND records");
Devang Patelaf206b82009-09-18 19:26:43 +00002005 break;
2006 }
Devang Patel7428d8a2009-07-22 17:43:22 +00002007 }
2008 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002009#undef GET_OR_DISTINCT
Devang Patel7428d8a2009-07-22 17:43:22 +00002010}
2011
Jan Wen Voungafaced02012-10-11 20:20:40 +00002012/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
Chris Lattner08feb1e2007-04-24 04:04:35 +00002013/// the LSB for dense VBR encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002014uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00002015 if ((V & 1) == 0)
2016 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002017 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00002018 return -(V >> 1);
2019 // There is no such thing as -0 with integers. "-0" really means MININT.
2020 return 1ULL << 63;
2021}
2022
Chris Lattner44c17072007-04-26 02:46:40 +00002023/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
2024/// values and aliases that we can.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002025std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00002026 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2027 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002028 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002029 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002030
Chris Lattner44c17072007-04-26 02:46:40 +00002031 GlobalInitWorklist.swap(GlobalInits);
2032 AliasInitWorklist.swap(AliasInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002033 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002034 FunctionPrologueWorklist.swap(FunctionPrologues);
Chris Lattner44c17072007-04-26 02:46:40 +00002035
2036 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00002037 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002038 if (ValID >= ValueList.size()) {
2039 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00002040 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002041 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002042 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00002043 GlobalInitWorklist.back().first->setInitializer(C);
2044 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002045 return Error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00002046 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002047 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002048 }
2049
2050 while (!AliasInitWorklist.empty()) {
2051 unsigned ValID = AliasInitWorklist.back().second;
2052 if (ValID >= ValueList.size()) {
2053 AliasInits.push_back(AliasInitWorklist.back());
2054 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002055 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Rafael Espindola64c1e182014-06-03 02:41:57 +00002056 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner44c17072007-04-26 02:46:40 +00002057 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002058 return Error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00002059 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002060 AliasInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002061 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002062
2063 while (!FunctionPrefixWorklist.empty()) {
2064 unsigned ValID = FunctionPrefixWorklist.back().second;
2065 if (ValID >= ValueList.size()) {
2066 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2067 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002068 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002069 FunctionPrefixWorklist.back().first->setPrefixData(C);
2070 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002071 return Error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002072 }
2073 FunctionPrefixWorklist.pop_back();
2074 }
2075
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002076 while (!FunctionPrologueWorklist.empty()) {
2077 unsigned ValID = FunctionPrologueWorklist.back().second;
2078 if (ValID >= ValueList.size()) {
2079 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2080 } else {
2081 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2082 FunctionPrologueWorklist.back().first->setPrologueData(C);
2083 else
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002084 return Error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002085 }
2086 FunctionPrologueWorklist.pop_back();
2087 }
2088
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002089 return std::error_code();
Chris Lattner44c17072007-04-26 02:46:40 +00002090}
2091
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002092static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2093 SmallVector<uint64_t, 8> Words(Vals.size());
2094 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00002095 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002096
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002097 return APInt(TypeBits, Words);
2098}
2099
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002100std::error_code BitcodeReader::ParseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002101 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002102 return Error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002103
2104 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002105
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002106 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00002107 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00002108 unsigned NextCstNo = ValueList.size();
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002109 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002110 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002111
Chris Lattner27d38752013-01-20 02:13:19 +00002112 switch (Entry.Kind) {
2113 case BitstreamEntry::SubBlock: // Handled for us already.
2114 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002115 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002116 case BitstreamEntry::EndBlock:
2117 if (NextCstNo != ValueList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002118 return Error("Invalid ronstant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00002119
Chris Lattner27d38752013-01-20 02:13:19 +00002120 // Once all the constants have been read, go through and resolve forward
2121 // references.
2122 ValueList.ResolveConstantForwardRefs();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002123 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002124 case BitstreamEntry::Record:
2125 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00002126 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002127 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002128
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002129 // Read a record.
2130 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00002131 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002132 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002133 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002134 default: // Default behavior: unknown constant
2135 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00002136 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002137 break;
2138 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2139 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002140 return Error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00002141 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002142 return Error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002143 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00002144 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002145 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00002146 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002147 break;
2148 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002149 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002150 return Error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002151 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00002152 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00002153 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002154 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002155 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002156
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002157 APInt VInt = ReadWideAPInt(Record,
2158 cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002159 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002160
Chris Lattner08feb1e2007-04-24 04:04:35 +00002161 break;
2162 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002163 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00002164 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002165 return Error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00002166 if (CurTy->isHalfTy())
Tim Northover29178a32013-01-22 09:46:31 +00002167 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2168 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00002169 else if (CurTy->isFloatTy())
Tim Northover29178a32013-01-22 09:46:31 +00002170 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2171 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002172 else if (CurTy->isDoubleTy())
Tim Northover29178a32013-01-22 09:46:31 +00002173 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2174 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002175 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00002176 // Bits are not stored the same way as a normal i80 APInt, compensate.
2177 uint64_t Rearrange[2];
2178 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2179 Rearrange[1] = Record[0] >> 48;
Tim Northover29178a32013-01-22 09:46:31 +00002180 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2181 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002182 } else if (CurTy->isFP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002183 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2184 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002185 else if (CurTy->isPPC_FP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002186 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2187 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002188 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00002189 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002190 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00002191 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002192
Chris Lattnere14cb882007-05-04 19:11:41 +00002193 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2194 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002195 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002196
Chris Lattnere14cb882007-05-04 19:11:41 +00002197 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00002198 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002199
Chris Lattner229907c2011-07-18 04:54:35 +00002200 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00002201 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002202 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00002203 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00002204 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002205 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2206 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002207 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002208 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00002209 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002210 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2211 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002212 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002213 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00002214 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00002215 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002216 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00002217 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002218 break;
2219 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002220 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00002221 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2222 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002223 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002224
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002225 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002226 V = ConstantDataArray::getString(Context, Elts,
2227 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00002228 break;
2229 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002230 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2231 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002232 return Error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002233
Chris Lattner372dd1e2012-01-30 00:51:16 +00002234 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2235 unsigned Size = Record.size();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002236
Chris Lattner372dd1e2012-01-30 00:51:16 +00002237 if (EltTy->isIntegerTy(8)) {
2238 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2239 if (isa<VectorType>(CurTy))
2240 V = ConstantDataVector::get(Context, Elts);
2241 else
2242 V = ConstantDataArray::get(Context, Elts);
2243 } else if (EltTy->isIntegerTy(16)) {
2244 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2245 if (isa<VectorType>(CurTy))
2246 V = ConstantDataVector::get(Context, Elts);
2247 else
2248 V = ConstantDataArray::get(Context, Elts);
2249 } else if (EltTy->isIntegerTy(32)) {
2250 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2251 if (isa<VectorType>(CurTy))
2252 V = ConstantDataVector::get(Context, Elts);
2253 else
2254 V = ConstantDataArray::get(Context, Elts);
2255 } else if (EltTy->isIntegerTy(64)) {
2256 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2257 if (isa<VectorType>(CurTy))
2258 V = ConstantDataVector::get(Context, Elts);
2259 else
2260 V = ConstantDataArray::get(Context, Elts);
2261 } else if (EltTy->isFloatTy()) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002262 SmallVector<float, 16> Elts(Size);
2263 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002264 if (isa<VectorType>(CurTy))
2265 V = ConstantDataVector::get(Context, Elts);
2266 else
2267 V = ConstantDataArray::get(Context, Elts);
2268 } else if (EltTy->isDoubleTy()) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002269 SmallVector<double, 16> Elts(Size);
2270 std::transform(Record.begin(), Record.end(), Elts.begin(),
2271 BitsToDouble);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002272 if (isa<VectorType>(CurTy))
2273 V = ConstantDataVector::get(Context, Elts);
2274 else
2275 V = ConstantDataArray::get(Context, Elts);
2276 } else {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002277 return Error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00002278 }
2279 break;
2280 }
2281
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002282 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002283 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002284 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002285 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002286 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002287 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00002288 } else {
2289 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2290 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00002291 unsigned Flags = 0;
2292 if (Record.size() >= 4) {
2293 if (Opc == Instruction::Add ||
2294 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002295 Opc == Instruction::Mul ||
2296 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00002297 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2298 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2299 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2300 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002301 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002302 Opc == Instruction::UDiv ||
2303 Opc == Instruction::LShr ||
2304 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00002305 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00002306 Flags |= SDivOperator::IsExact;
2307 }
2308 }
2309 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00002310 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002311 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002312 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002313 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002314 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002315 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002316 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00002317 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002318 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00002319 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002320 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002321 if (!OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002322 return Error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00002323 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002324 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2325 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002326 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002327 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002328 }
Dan Gohman1639c392009-07-27 21:53:46 +00002329 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002330 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
David Blaikieb9263572015-03-13 21:03:36 +00002331 unsigned OpNum = 0;
2332 Type *PointeeType = nullptr;
2333 if (Record.size() % 2)
2334 PointeeType = getTypeByID(Record[OpNum++]);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002335 SmallVector<Constant*, 16> Elts;
David Blaikieb9263572015-03-13 21:03:36 +00002336 while (OpNum != Record.size()) {
2337 Type *ElTy = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002338 if (!ElTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002339 return Error("Invalid record");
David Blaikieb9263572015-03-13 21:03:36 +00002340 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002341 }
David Blaikieb9263572015-03-13 21:03:36 +00002342
David Blaikieb9263572015-03-13 21:03:36 +00002343 if (PointeeType &&
David Blaikie4a2e73b2015-04-02 18:55:32 +00002344 PointeeType !=
2345 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2346 ->getElementType())
David Blaikie12cf5d702015-03-16 22:03:50 +00002347 return Error("Explicit gep operator type does not match pointee type "
2348 "of pointer operand");
David Blaikie4a2e73b2015-04-02 18:55:32 +00002349
2350 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2351 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2352 BitCode ==
2353 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattner890683d2007-04-24 18:15:21 +00002354 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002355 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00002356 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002357 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002358 return Error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00002359
2360 Type *SelectorTy = Type::getInt1Ty(Context);
2361
2362 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
2363 // vector. Otherwise, it must be a single bit.
2364 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2365 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
2366 VTy->getNumElements());
2367
2368 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2369 SelectorTy),
2370 ValueList.getConstantFwdRef(Record[1],CurTy),
2371 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002372 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00002373 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002374 case bitc::CST_CODE_CE_EXTRACTELT
2375 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002376 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002377 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002378 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002379 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002380 if (!OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002381 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002382 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002383 Constant *Op1 = nullptr;
2384 if (Record.size() == 4) {
2385 Type *IdxTy = getTypeByID(Record[2]);
2386 if (!IdxTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002387 return Error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002388 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2389 } else // TODO: Remove with llvm 4.0
2390 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2391 if (!Op1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002392 return Error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002393 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002394 break;
2395 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002396 case bitc::CST_CODE_CE_INSERTELT
2397 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002398 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002399 if (Record.size() < 3 || !OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002400 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002401 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2402 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2403 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002404 Constant *Op2 = nullptr;
2405 if (Record.size() == 4) {
2406 Type *IdxTy = getTypeByID(Record[2]);
2407 if (!IdxTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002408 return Error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002409 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2410 } else // TODO: Remove with llvm 4.0
2411 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2412 if (!Op2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002413 return Error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002414 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002415 break;
2416 }
2417 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002418 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002419 if (Record.size() < 3 || !OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002420 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002421 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2422 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002423 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002424 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002425 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002426 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002427 break;
2428 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00002429 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002430 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2431 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00002432 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002433 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002434 return Error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002435 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2436 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002437 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002438 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00002439 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002440 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00002441 break;
2442 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002443 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002444 if (Record.size() < 4)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002445 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002446 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002447 if (!OpTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002448 return Error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002449 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2450 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2451
Duncan Sands9dff9be2010-02-15 16:12:20 +00002452 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002453 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00002454 else
Owen Anderson487375e2009-07-29 18:55:55 +00002455 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002456 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00002457 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002458 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00002459 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002460 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002461 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002462 return Error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002463 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00002464 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002465 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002466 unsigned AsmStrSize = Record[1];
2467 if (2+AsmStrSize >= Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002468 return Error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002469 unsigned ConstStrSize = Record[2+AsmStrSize];
2470 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002471 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002472
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002473 for (unsigned i = 0; i != AsmStrSize; ++i)
2474 AsmStr += (char)Record[2+i];
2475 for (unsigned i = 0; i != ConstStrSize; ++i)
2476 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00002477 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002478 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002479 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002480 break;
2481 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002482 // This version adds support for the asm dialect keywords (e.g.,
2483 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002484 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002485 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002486 return Error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002487 std::string AsmStr, ConstrStr;
2488 bool HasSideEffects = Record[0] & 1;
2489 bool IsAlignStack = (Record[0] >> 1) & 1;
2490 unsigned AsmDialect = Record[0] >> 2;
2491 unsigned AsmStrSize = Record[1];
2492 if (2+AsmStrSize >= Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002493 return Error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002494 unsigned ConstStrSize = Record[2+AsmStrSize];
2495 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002496 return Error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002497
2498 for (unsigned i = 0; i != AsmStrSize; ++i)
2499 AsmStr += (char)Record[2+i];
2500 for (unsigned i = 0; i != ConstStrSize; ++i)
2501 ConstrStr += (char)Record[3+AsmStrSize+i];
2502 PointerType *PTy = cast<PointerType>(CurTy);
2503 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2504 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00002505 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002506 break;
2507 }
Chris Lattner5956dc82009-10-28 05:53:48 +00002508 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00002509 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002510 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002511 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002512 if (!FnTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002513 return Error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00002514 Function *Fn =
2515 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00002516 if (!Fn)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002517 return Error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002518
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00002519 // Don't let Fn get dematerialized.
2520 BlockAddressesTaken.insert(Fn);
2521
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002522 // If the function is already parsed we can insert the block address right
2523 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002524 BasicBlock *BB;
2525 unsigned BBID = Record[2];
2526 if (!BBID)
2527 // Invalid reference to entry block.
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002528 return Error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002529 if (!Fn->empty()) {
2530 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002531 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002532 if (BBI == BBE)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002533 return Error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002534 ++BBI;
2535 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002536 BB = BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002537 } else {
2538 // Otherwise insert a placeholder and remember it so it can be inserted
2539 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00002540 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2541 if (FwdBBs.empty())
2542 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00002543 if (FwdBBs.size() < BBID + 1)
2544 FwdBBs.resize(BBID + 1);
2545 if (!FwdBBs[BBID])
2546 FwdBBs[BBID] = BasicBlock::Create(Context);
2547 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002548 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002549 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00002550 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002551 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002552 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002553
Chris Lattner83930552007-05-01 07:01:57 +00002554 ValueList.AssignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00002555 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002556 }
2557}
Chris Lattner1314b992007-04-22 06:23:29 +00002558
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002559std::error_code BitcodeReader::ParseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00002560 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002561 return Error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00002562
Chad Rosierca2567b2011-12-07 21:44:12 +00002563 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002564 SmallVector<uint64_t, 64> Record;
Chad Rosierca2567b2011-12-07 21:44:12 +00002565 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002566 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002567
Chris Lattner27d38752013-01-20 02:13:19 +00002568 switch (Entry.Kind) {
2569 case BitstreamEntry::SubBlock: // Handled for us already.
2570 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002571 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002572 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002573 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002574 case BitstreamEntry::Record:
2575 // The interesting case.
2576 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00002577 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002578
Chad Rosierca2567b2011-12-07 21:44:12 +00002579 // Read a use list record.
2580 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002581 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00002582 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00002583 default: // Default behavior: unknown type.
2584 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002585 case bitc::USELIST_CODE_BB:
2586 IsBB = true;
2587 // fallthrough
2588 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00002589 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002590 if (RecordLength < 3)
2591 // Records should have at least an ID and two indexes.
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002592 return Error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002593 unsigned ID = Record.back();
2594 Record.pop_back();
2595
2596 Value *V;
2597 if (IsBB) {
2598 assert(ID < FunctionBBs.size() && "Basic block not found");
2599 V = FunctionBBs[ID];
2600 } else
2601 V = ValueList[ID];
2602 unsigned NumUses = 0;
2603 SmallDenseMap<const Use *, unsigned, 16> Order;
2604 for (const Use &U : V->uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00002605 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002606 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00002607 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002608 }
2609 if (Order.size() != Record.size() || NumUses > Record.size())
2610 // Mismatches can happen if the functions are being materialized lazily
2611 // (out-of-order), or a value has been upgraded.
2612 break;
2613
2614 V->sortUseList([&](const Use &L, const Use &R) {
2615 return Order.lookup(&L) < Order.lookup(&R);
2616 });
Chad Rosierca2567b2011-12-07 21:44:12 +00002617 break;
2618 }
2619 }
2620 }
2621}
2622
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002623/// When we see the block for metadata, remember where it is and then skip it.
2624/// This lets us lazily deserialize the metadata.
2625std::error_code BitcodeReader::rememberAndSkipMetadata() {
2626 // Save the current stream state.
2627 uint64_t CurBit = Stream.GetCurrentBitNo();
2628 DeferredMetadataInfo.push_back(CurBit);
2629
2630 // Skip over the block for now.
2631 if (Stream.SkipBlock())
2632 return Error("Invalid record");
2633 return std::error_code();
2634}
2635
2636std::error_code BitcodeReader::materializeMetadata() {
2637 for (uint64_t BitPos : DeferredMetadataInfo) {
2638 // Move the bit stream to the saved position.
2639 Stream.JumpToBit(BitPos);
2640 if (std::error_code EC = ParseMetadata())
2641 return EC;
2642 }
2643 DeferredMetadataInfo.clear();
2644 return std::error_code();
2645}
2646
Rafael Espindola468b8682015-04-01 14:44:59 +00002647void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00002648
Chris Lattner85b7b402007-05-01 05:52:21 +00002649/// RememberAndSkipFunctionBody - When we see the block for a function body,
2650/// remember where it is and then skip it. This lets us lazily deserialize the
2651/// functions.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002652std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002653 // Get the function we are talking about.
2654 if (FunctionsWithBodies.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002655 return Error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002656
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002657 Function *Fn = FunctionsWithBodies.back();
2658 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002659
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002660 // Save the current stream state.
2661 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00002662 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002663
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002664 // Skip over the function block for now.
2665 if (Stream.SkipBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002666 return Error("Invalid record");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002667 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002668}
2669
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002670std::error_code BitcodeReader::GlobalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002671 // Patch the initializers for globals and aliases up.
2672 ResolveGlobalAndAliasInits();
2673 if (!GlobalInits.empty() || !AliasInits.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002674 return Error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002675
2676 // Look for intrinsic functions which need to be upgraded at some point
2677 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2678 FI != FE; ++FI) {
2679 Function *NewFn;
2680 if (UpgradeIntrinsicFunction(FI, NewFn))
2681 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
2682 }
2683
2684 // Look for global variables which need to be renamed.
2685 for (Module::global_iterator
2686 GI = TheModule->global_begin(), GE = TheModule->global_end();
Reid Klecknerfceb76f2014-05-16 20:39:27 +00002687 GI != GE;) {
2688 GlobalVariable *GV = GI++;
2689 UpgradeGlobalVariable(GV);
2690 }
2691
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002692 // Force deallocation of memory for these vectors to favor the client that
2693 // want lazy deserialization.
2694 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2695 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002696 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002697}
2698
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002699std::error_code BitcodeReader::ParseModule(bool Resume,
2700 bool ShouldLazyLoadMetadata) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002701 if (Resume)
2702 Stream.JumpToBit(NextUnreadBit);
2703 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002704 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002705
Chris Lattner1314b992007-04-22 06:23:29 +00002706 SmallVector<uint64_t, 64> Record;
2707 std::vector<std::string> SectionTable;
Gordon Henriksend930f912008-08-17 18:44:35 +00002708 std::vector<std::string> GCTable;
Chris Lattner1314b992007-04-22 06:23:29 +00002709
2710 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00002711 while (1) {
2712 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00002713
Chris Lattner27d38752013-01-20 02:13:19 +00002714 switch (Entry.Kind) {
2715 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002716 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002717 case BitstreamEntry::EndBlock:
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002718 return GlobalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00002719
Chris Lattner27d38752013-01-20 02:13:19 +00002720 case BitstreamEntry::SubBlock:
2721 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00002722 default: // Skip unknown content.
2723 if (Stream.SkipBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002724 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002725 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00002726 case bitc::BLOCKINFO_BLOCK_ID:
2727 if (Stream.ReadBlockInfoBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002728 return Error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00002729 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00002730 case bitc::PARAMATTR_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002731 if (std::error_code EC = ParseAttributeBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002732 return EC;
Chris Lattnerfee5a372007-05-04 03:30:17 +00002733 break;
Bill Wendlingba629332013-02-10 23:24:25 +00002734 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002735 if (std::error_code EC = ParseAttributeGroupBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002736 return EC;
Bill Wendlingba629332013-02-10 23:24:25 +00002737 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002738 case bitc::TYPE_BLOCK_ID_NEW:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002739 if (std::error_code EC = ParseTypeTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002740 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00002741 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00002742 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002743 if (std::error_code EC = ParseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002744 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002745 SeenValueSymbolTable = true;
Chris Lattnerccaa4482007-04-23 21:26:05 +00002746 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002747 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002748 if (std::error_code EC = ParseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002749 return EC;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002750 if (std::error_code EC = ResolveGlobalAndAliasInits())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002751 return EC;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002752 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00002753 case bitc::METADATA_BLOCK_ID:
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002754 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2755 if (std::error_code EC = rememberAndSkipMetadata())
2756 return EC;
2757 break;
2758 }
2759 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002760 if (std::error_code EC = ParseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002761 return EC;
Devang Patel7428d8a2009-07-22 17:43:22 +00002762 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002763 case bitc::FUNCTION_BLOCK_ID:
2764 // If this is the first function body we've seen, reverse the
2765 // FunctionsWithBodies list.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002766 if (!SeenFirstFunctionBody) {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002767 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002768 if (std::error_code EC = GlobalCleanup())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002769 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002770 SeenFirstFunctionBody = true;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002771 }
Joe Abbey97b7a172013-02-06 22:14:06 +00002772
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002773 if (std::error_code EC = RememberAndSkipFunctionBody())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002774 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002775 // For streaming bitcode, suspend parsing when we reach the function
2776 // bodies. Subsequent materialization calls will resume it when
2777 // necessary. For streaming, the function bodies must be at the end of
2778 // the bitcode. If the bitcode file is old, the symbol table will be
2779 // at the end instead and will not have been seen yet. In this case,
2780 // just finish the parse now.
2781 if (LazyStreamer && SeenValueSymbolTable) {
2782 NextUnreadBit = Stream.GetCurrentBitNo();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002783 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002784 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002785 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00002786 case bitc::USELIST_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002787 if (std::error_code EC = ParseUseLists())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002788 return EC;
Chad Rosierca2567b2011-12-07 21:44:12 +00002789 break;
Chris Lattner1314b992007-04-22 06:23:29 +00002790 }
2791 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00002792
Chris Lattner27d38752013-01-20 02:13:19 +00002793 case BitstreamEntry::Record:
2794 // The interesting case.
2795 break;
Chris Lattner1314b992007-04-22 06:23:29 +00002796 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002797
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002798
Chris Lattner1314b992007-04-22 06:23:29 +00002799 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00002800 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner1314b992007-04-22 06:23:29 +00002801 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002802 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattner1314b992007-04-22 06:23:29 +00002803 if (Record.size() < 1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002804 return Error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002805 // Only version #0 and #1 are supported so far.
2806 unsigned module_version = Record[0];
2807 switch (module_version) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002808 default:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002809 return Error("Invalid value");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002810 case 0:
2811 UseRelativeIDs = false;
2812 break;
2813 case 1:
2814 UseRelativeIDs = true;
2815 break;
2816 }
Chris Lattner1314b992007-04-22 06:23:29 +00002817 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00002818 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002819 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002820 std::string S;
2821 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002822 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002823 TheModule->setTargetTriple(S);
2824 break;
2825 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002826 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002827 std::string S;
2828 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002829 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002830 TheModule->setDataLayout(S);
2831 break;
2832 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002833 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002834 std::string S;
2835 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002836 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002837 TheModule->setModuleInlineAsm(S);
2838 break;
2839 }
Bill Wendling706d3d62012-11-28 08:41:48 +00002840 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2841 // FIXME: Remove in 4.0.
2842 std::string S;
2843 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002844 return Error("Invalid record");
Bill Wendling706d3d62012-11-28 08:41:48 +00002845 // Ignore value.
2846 break;
2847 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002848 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002849 std::string S;
2850 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002851 return Error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002852 SectionTable.push_back(S);
2853 break;
2854 }
Gordon Henriksend930f912008-08-17 18:44:35 +00002855 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00002856 std::string S;
2857 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002858 return Error("Invalid record");
Gordon Henriksend930f912008-08-17 18:44:35 +00002859 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00002860 break;
2861 }
David Majnemerdad0a642014-06-27 18:19:56 +00002862 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2863 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002864 return Error("Invalid record");
David Majnemerdad0a642014-06-27 18:19:56 +00002865 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2866 unsigned ComdatNameSize = Record[1];
2867 std::string ComdatName;
2868 ComdatName.reserve(ComdatNameSize);
2869 for (unsigned i = 0; i != ComdatNameSize; ++i)
2870 ComdatName += (char)Record[2 + i];
2871 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2872 C->setSelectionKind(SK);
2873 ComdatList.push_back(C);
2874 break;
2875 }
Christopher Lamb54dd24c2007-12-11 08:59:05 +00002876 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00002877 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00002878 // unnamed_addr, externally_initialized, dllstorageclass,
2879 // comdat]
Chris Lattner1314b992007-04-22 06:23:29 +00002880 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner4b00d922007-04-23 16:04:05 +00002881 if (Record.size() < 6)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002882 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002883 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002884 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002885 return Error("Invalid record");
David Blaikie1a848da2015-04-27 19:58:56 +00002886 bool isConstant = Record[1] & 1;
2887 bool explicitType = Record[1] & 2;
2888 unsigned AddressSpace;
2889 if (explicitType) {
2890 AddressSpace = Record[1] >> 2;
2891 } else {
2892 if (!Ty->isPointerTy())
2893 return Error("Invalid type for value");
2894 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2895 Ty = cast<PointerType>(Ty)->getElementType();
2896 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002897
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002898 uint64_t RawLinkage = Record[3];
2899 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
JF Bastien30bf96b2015-02-22 19:32:03 +00002900 unsigned Alignment;
2901 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
2902 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00002903 std::string Section;
2904 if (Record[5]) {
2905 if (Record[5]-1 >= SectionTable.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002906 return Error("Invalid ID");
Chris Lattner1314b992007-04-22 06:23:29 +00002907 Section = SectionTable[Record[5]-1];
2908 }
Chris Lattner4b00d922007-04-23 16:04:05 +00002909 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00002910 // Local linkage must have default visibility.
2911 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2912 // FIXME: Change to an error if non-default in 4.0.
Chris Lattner53862f72007-05-06 19:27:46 +00002913 Visibility = GetDecodedVisibility(Record[6]);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00002914
2915 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner53862f72007-05-06 19:27:46 +00002916 if (Record.size() > 7)
Hans Wennborgcbe34b42012-06-23 11:37:03 +00002917 TLM = GetDecodedThreadLocalMode(Record[7]);
Chris Lattner1314b992007-04-22 06:23:29 +00002918
Rafael Espindola45e6c192011-01-08 16:42:36 +00002919 bool UnnamedAddr = false;
2920 if (Record.size() > 8)
2921 UnnamedAddr = Record[8];
2922
Michael Gottesman27e7ef32013-02-05 05:57:38 +00002923 bool ExternallyInitialized = false;
2924 if (Record.size() > 9)
2925 ExternallyInitialized = Record[9];
2926
Chris Lattner1314b992007-04-22 06:23:29 +00002927 GlobalVariable *NewGV =
Craig Topper2617dcc2014-04-15 06:32:26 +00002928 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
Michael Gottesman27e7ef32013-02-05 05:57:38 +00002929 TLM, AddressSpace, ExternallyInitialized);
Chris Lattner1314b992007-04-22 06:23:29 +00002930 NewGV->setAlignment(Alignment);
2931 if (!Section.empty())
2932 NewGV->setSection(Section);
2933 NewGV->setVisibility(Visibility);
Rafael Espindola45e6c192011-01-08 16:42:36 +00002934 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002935
Nico Rieck7157bb72014-01-14 15:22:47 +00002936 if (Record.size() > 10)
2937 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
2938 else
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002939 UpgradeDLLImportExportLinkage(NewGV, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00002940
Chris Lattnerccaa4482007-04-23 21:26:05 +00002941 ValueList.push_back(NewGV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002942
Chris Lattner47d131b2007-04-24 00:18:21 +00002943 // Remember which value to use for the global initializer.
2944 if (unsigned InitID = Record[2])
2945 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
David Majnemerdad0a642014-06-27 18:19:56 +00002946
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002947 if (Record.size() > 11) {
David Majnemerdad0a642014-06-27 18:19:56 +00002948 if (unsigned ComdatID = Record[11]) {
2949 assert(ComdatID <= ComdatList.size());
2950 NewGV->setComdat(ComdatList[ComdatID - 1]);
2951 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002952 } else if (hasImplicitComdat(RawLinkage)) {
2953 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2954 }
Chris Lattner1314b992007-04-22 06:23:29 +00002955 break;
2956 }
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002957 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Nico Rieck7157bb72014-01-14 15:22:47 +00002958 // alignment, section, visibility, gc, unnamed_addr,
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002959 // prologuedata, dllstorageclass, comdat, prefixdata]
Chris Lattner1314b992007-04-22 06:23:29 +00002960 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002961 if (Record.size() < 8)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002962 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002963 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002964 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002965 return Error("Invalid record");
David Blaikie561a1572015-04-17 16:28:26 +00002966 if (auto *PTy = dyn_cast<PointerType>(Ty))
2967 Ty = PTy->getElementType();
2968 auto *FTy = dyn_cast<FunctionType>(Ty);
Chris Lattner1314b992007-04-22 06:23:29 +00002969 if (!FTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002970 return Error("Invalid type for value");
Chris Lattner1314b992007-04-22 06:23:29 +00002971
Gabor Greife9ecc682008-04-06 20:25:17 +00002972 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2973 "", TheModule);
Chris Lattner1314b992007-04-22 06:23:29 +00002974
Sandeep Patel68c5f472009-09-02 08:44:58 +00002975 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002976 bool isProto = Record[2];
Rafael Espindola12ca34f2015-01-19 15:16:06 +00002977 uint64_t RawLinkage = Record[3];
2978 Func->setLinkage(getDecodedLinkage(RawLinkage));
Devang Patel4c758ea2008-09-25 21:00:45 +00002979 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002980
JF Bastien30bf96b2015-02-22 19:32:03 +00002981 unsigned Alignment;
2982 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
2983 return EC;
2984 Func->setAlignment(Alignment);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002985 if (Record[6]) {
2986 if (Record[6]-1 >= SectionTable.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002987 return Error("Invalid ID");
Chris Lattner4c0a6d62007-05-08 05:38:01 +00002988 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattner1314b992007-04-22 06:23:29 +00002989 }
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00002990 // Local linkage must have default visibility.
2991 if (!Func->hasLocalLinkage())
2992 // FIXME: Change to an error if non-default in 4.0.
2993 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen71183b62007-12-10 03:18:06 +00002994 if (Record.size() > 8 && Record[8]) {
Filipe Cabecinhasf8a16a92015-04-30 04:09:41 +00002995 if (Record[8]-1 >= GCTable.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00002996 return Error("Invalid ID");
Gordon Henriksend930f912008-08-17 18:44:35 +00002997 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen71183b62007-12-10 03:18:06 +00002998 }
Rafael Espindola45e6c192011-01-08 16:42:36 +00002999 bool UnnamedAddr = false;
3000 if (Record.size() > 9)
3001 UnnamedAddr = Record[9];
3002 Func->setUnnamedAddr(UnnamedAddr);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003003 if (Record.size() > 10 && Record[10] != 0)
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003004 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
Nico Rieck7157bb72014-01-14 15:22:47 +00003005
3006 if (Record.size() > 11)
3007 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
3008 else
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003009 UpgradeDLLImportExportLinkage(Func, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00003010
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003011 if (Record.size() > 12) {
David Majnemerdad0a642014-06-27 18:19:56 +00003012 if (unsigned ComdatID = Record[12]) {
3013 assert(ComdatID <= ComdatList.size());
3014 Func->setComdat(ComdatList[ComdatID - 1]);
3015 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003016 } else if (hasImplicitComdat(RawLinkage)) {
3017 Func->setComdat(reinterpret_cast<Comdat *>(1));
3018 }
David Majnemerdad0a642014-06-27 18:19:56 +00003019
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003020 if (Record.size() > 13 && Record[13] != 0)
3021 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3022
Chris Lattnerccaa4482007-04-23 21:26:05 +00003023 ValueList.push_back(Func);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003024
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003025 // If this is a function with a body, remember the prototype we are
3026 // creating now, so that we can match up the body with them later.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003027 if (!isProto) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00003028 Func->setIsMaterializable(true);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003029 FunctionsWithBodies.push_back(Func);
Rafael Espindola1b47a282014-10-23 15:20:05 +00003030 if (LazyStreamer)
3031 DeferredFunctionInfo[Func] = 0;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003032 }
Chris Lattner1314b992007-04-22 06:23:29 +00003033 break;
3034 }
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00003035 // ALIAS: [alias type, aliasee val#, linkage]
Nico Rieck7157bb72014-01-14 15:22:47 +00003036 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
Chris Lattner831d4202007-04-26 03:27:58 +00003037 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner44c17072007-04-26 02:46:40 +00003038 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003039 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003040 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003041 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003042 return Error("Invalid record");
Rafael Espindolaa8004452014-05-16 14:22:33 +00003043 auto *PTy = dyn_cast<PointerType>(Ty);
3044 if (!PTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003045 return Error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003046
Rafael Espindolaa8004452014-05-16 14:22:33 +00003047 auto *NewGA =
David Blaikief64246b2015-04-29 21:22:39 +00003048 GlobalAlias::create(PTy, getDecodedLinkage(Record[2]), "", TheModule);
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00003049 // Old bitcode files didn't have visibility field.
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003050 // Local linkage must have default visibility.
3051 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3052 // FIXME: Change to an error if non-default in 4.0.
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00003053 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003054 if (Record.size() > 4)
3055 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
3056 else
3057 UpgradeDLLImportExportLinkage(NewGA, Record[2]);
Rafael Espindola59f7eba2014-05-28 18:15:43 +00003058 if (Record.size() > 5)
NAKAMURA Takumi32c87ac2014-10-29 23:44:35 +00003059 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00003060 if (Record.size() > 6)
NAKAMURA Takumi32c87ac2014-10-29 23:44:35 +00003061 NewGA->setUnnamedAddr(Record[6]);
Chris Lattner44c17072007-04-26 02:46:40 +00003062 ValueList.push_back(NewGA);
3063 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3064 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003065 }
Chris Lattner831d4202007-04-26 03:27:58 +00003066 /// MODULE_CODE_PURGEVALS: [numvals]
3067 case bitc::MODULE_CODE_PURGEVALS:
3068 // Trim down the value list to the specified size.
3069 if (Record.size() < 1 || Record[0] > ValueList.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003070 return Error("Invalid record");
Chris Lattner831d4202007-04-26 03:27:58 +00003071 ValueList.shrinkTo(Record[0]);
3072 break;
3073 }
Chris Lattner1314b992007-04-22 06:23:29 +00003074 Record.clear();
3075 }
Chris Lattner1314b992007-04-22 06:23:29 +00003076}
3077
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003078std::error_code BitcodeReader::ParseBitcodeInto(Module *M,
3079 bool ShouldLazyLoadMetadata) {
Craig Topper2617dcc2014-04-15 06:32:26 +00003080 TheModule = nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003081
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003082 if (std::error_code EC = InitStream())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003083 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003084
Chris Lattner1314b992007-04-22 06:23:29 +00003085 // Sniff for the signature.
3086 if (Stream.Read(8) != 'B' ||
3087 Stream.Read(8) != 'C' ||
3088 Stream.Read(4) != 0x0 ||
3089 Stream.Read(4) != 0xC ||
3090 Stream.Read(4) != 0xE ||
3091 Stream.Read(4) != 0xD)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003092 return Error("Invalid bitcode signature");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003093
Chris Lattner1314b992007-04-22 06:23:29 +00003094 // We expect a number of well-defined blocks, though we don't necessarily
3095 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00003096 while (1) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003097 if (Stream.AtEndOfStream()) {
3098 if (TheModule)
3099 return std::error_code();
3100 // We didn't really read a proper Module.
3101 return Error("Malformed IR file");
3102 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003103
Chris Lattner27d38752013-01-20 02:13:19 +00003104 BitstreamEntry Entry =
3105 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbey97b7a172013-02-06 22:14:06 +00003106
Chris Lattner27d38752013-01-20 02:13:19 +00003107 switch (Entry.Kind) {
3108 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003109 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003110 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003111 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00003112
Chris Lattner27d38752013-01-20 02:13:19 +00003113 case BitstreamEntry::SubBlock:
3114 switch (Entry.ID) {
3115 case bitc::BLOCKINFO_BLOCK_ID:
3116 if (Stream.ReadBlockInfoBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003117 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003118 break;
3119 case bitc::MODULE_BLOCK_ID:
3120 // Reject multiple MODULE_BLOCK's in a single bitstream.
3121 if (TheModule)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003122 return Error("Invalid multiple blocks");
Chris Lattner27d38752013-01-20 02:13:19 +00003123 TheModule = M;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003124 if (std::error_code EC = ParseModule(false, ShouldLazyLoadMetadata))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003125 return EC;
3126 if (LazyStreamer)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003127 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003128 break;
3129 default:
3130 if (Stream.SkipBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003131 return Error("Invalid record");
Chris Lattner27d38752013-01-20 02:13:19 +00003132 break;
3133 }
3134 continue;
3135 case BitstreamEntry::Record:
3136 // There should be no records in the top-level of blocks.
Joe Abbey97b7a172013-02-06 22:14:06 +00003137
Chris Lattner27d38752013-01-20 02:13:19 +00003138 // The ranlib in Xcode 4 will align archive members by appending newlines
Chad Rosiera15e3aa2011-08-09 22:23:40 +00003139 // to the end of them. If this file size is a multiple of 4 but not 8, we
3140 // have to read and ignore these final 4 bytes :-(
Chris Lattner27d38752013-01-20 02:13:19 +00003141 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
Rafael Espindolaa97b2382011-05-26 18:59:54 +00003142 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
Bill Wendling318f03f2012-07-19 00:15:11 +00003143 Stream.AtEndOfStream())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003144 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00003145
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003146 return Error("Invalid record");
Rafael Espindolaa97b2382011-05-26 18:59:54 +00003147 }
Chris Lattner1314b992007-04-22 06:23:29 +00003148 }
Chris Lattner1314b992007-04-22 06:23:29 +00003149}
Chris Lattner6694f602007-04-29 07:54:31 +00003150
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003151ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
Bill Wendling0198ce02010-10-06 01:22:42 +00003152 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003153 return Error("Invalid record");
Bill Wendling0198ce02010-10-06 01:22:42 +00003154
3155 SmallVector<uint64_t, 64> Record;
3156
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003157 std::string Triple;
Bill Wendling0198ce02010-10-06 01:22:42 +00003158 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00003159 while (1) {
3160 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003161
Chris Lattner27d38752013-01-20 02:13:19 +00003162 switch (Entry.Kind) {
3163 case BitstreamEntry::SubBlock: // Handled for us already.
3164 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003165 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003166 case BitstreamEntry::EndBlock:
Rafael Espindolae6107792014-07-04 20:05:56 +00003167 return Triple;
Chris Lattner27d38752013-01-20 02:13:19 +00003168 case BitstreamEntry::Record:
3169 // The interesting case.
3170 break;
Bill Wendling0198ce02010-10-06 01:22:42 +00003171 }
3172
3173 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00003174 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling0198ce02010-10-06 01:22:42 +00003175 default: break; // Default behavior, ignore unknown content.
Bill Wendling0198ce02010-10-06 01:22:42 +00003176 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003177 std::string S;
3178 if (ConvertToString(Record, 0, S))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003179 return Error("Invalid record");
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003180 Triple = S;
Bill Wendling0198ce02010-10-06 01:22:42 +00003181 break;
3182 }
3183 }
3184 Record.clear();
3185 }
Rafael Espindolae6107792014-07-04 20:05:56 +00003186 llvm_unreachable("Exit infinite loop");
Bill Wendling0198ce02010-10-06 01:22:42 +00003187}
3188
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003189ErrorOr<std::string> BitcodeReader::parseTriple() {
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003190 if (std::error_code EC = InitStream())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003191 return EC;
Bill Wendling0198ce02010-10-06 01:22:42 +00003192
3193 // Sniff for the signature.
3194 if (Stream.Read(8) != 'B' ||
3195 Stream.Read(8) != 'C' ||
3196 Stream.Read(4) != 0x0 ||
3197 Stream.Read(4) != 0xC ||
3198 Stream.Read(4) != 0xE ||
3199 Stream.Read(4) != 0xD)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003200 return Error("Invalid bitcode signature");
Bill Wendling0198ce02010-10-06 01:22:42 +00003201
3202 // We expect a number of well-defined blocks, though we don't necessarily
3203 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00003204 while (1) {
3205 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003206
Chris Lattner27d38752013-01-20 02:13:19 +00003207 switch (Entry.Kind) {
3208 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003209 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003210 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003211 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00003212
Chris Lattner27d38752013-01-20 02:13:19 +00003213 case BitstreamEntry::SubBlock:
3214 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Rafael Espindolad346cc82014-07-04 13:52:01 +00003215 return parseModuleTriple();
Joe Abbey97b7a172013-02-06 22:14:06 +00003216
Chris Lattner27d38752013-01-20 02:13:19 +00003217 // Ignore other sub-blocks.
Rafael Espindola48da4f42013-11-04 16:16:24 +00003218 if (Stream.SkipBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003219 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003220 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003221
Chris Lattner27d38752013-01-20 02:13:19 +00003222 case BitstreamEntry::Record:
3223 Stream.skipRecord(Entry.ID);
3224 continue;
Bill Wendling0198ce02010-10-06 01:22:42 +00003225 }
3226 }
Bill Wendling0198ce02010-10-06 01:22:42 +00003227}
3228
Devang Patelaf206b82009-09-18 19:26:43 +00003229/// ParseMetadataAttachment - Parse metadata attachments.
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003230std::error_code BitcodeReader::ParseMetadataAttachment(Function &F) {
Devang Patelaf206b82009-09-18 19:26:43 +00003231 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003232 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003233
Devang Patelaf206b82009-09-18 19:26:43 +00003234 SmallVector<uint64_t, 64> Record;
Chris Lattner27d38752013-01-20 02:13:19 +00003235 while (1) {
3236 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003237
Chris Lattner27d38752013-01-20 02:13:19 +00003238 switch (Entry.Kind) {
3239 case BitstreamEntry::SubBlock: // Handled for us already.
3240 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003241 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003242 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003243 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003244 case BitstreamEntry::Record:
3245 // The interesting case.
Devang Patelaf206b82009-09-18 19:26:43 +00003246 break;
3247 }
Chris Lattner27d38752013-01-20 02:13:19 +00003248
Devang Patelaf206b82009-09-18 19:26:43 +00003249 // Read a metadata attachment record.
3250 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00003251 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patelaf206b82009-09-18 19:26:43 +00003252 default: // Default behavior: ignore.
3253 break;
Chris Lattnerb8778552011-06-17 17:50:30 +00003254 case bitc::METADATA_ATTACHMENT: {
Devang Patelaf206b82009-09-18 19:26:43 +00003255 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003256 if (Record.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003257 return Error("Invalid record");
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003258 if (RecordLength % 2 == 0) {
3259 // A function attachment.
3260 for (unsigned I = 0; I != RecordLength; I += 2) {
3261 auto K = MDKindMap.find(Record[I]);
3262 if (K == MDKindMap.end())
3263 return Error("Invalid ID");
3264 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3265 F.setMetadata(K->second, cast<MDNode>(MD));
3266 }
3267 continue;
3268 }
3269
3270 // An instruction attachment.
Devang Patelaf206b82009-09-18 19:26:43 +00003271 Instruction *Inst = InstructionList[Record[0]];
3272 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patelb1a44772009-09-28 21:14:55 +00003273 unsigned Kind = Record[i];
Dan Gohman43aa8f02010-07-20 21:42:28 +00003274 DenseMap<unsigned, unsigned>::iterator I =
3275 MDKindMap.find(Kind);
3276 if (I == MDKindMap.end())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003277 return Error("Invalid ID");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003278 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3279 if (isa<LocalAsMetadata>(Node))
Duncan P. N. Exon Smith35303fd2014-12-06 02:29:44 +00003280 // Drop the attachment. This used to be legal, but there's no
3281 // upgrade path.
3282 break;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003283 Inst->setMetadata(I->second, cast<MDNode>(Node));
Manman Ren209b17c2013-09-28 00:22:27 +00003284 if (I->second == LLVMContext::MD_tbaa)
3285 InstsWithTBAATag.push_back(Inst);
Devang Patelaf206b82009-09-18 19:26:43 +00003286 }
3287 break;
3288 }
3289 }
3290 }
Devang Patelaf206b82009-09-18 19:26:43 +00003291}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003292
Chris Lattner85b7b402007-05-01 05:52:21 +00003293/// ParseFunctionBody - Lazily parse the specified function body block.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003294std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00003295 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003296 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003297
Nick Lewyckya72e1af2010-02-25 08:30:17 +00003298 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00003299 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman26d837d2010-08-25 20:22:53 +00003300 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003301
Chris Lattner85b7b402007-05-01 05:52:21 +00003302 // Add all the function arguments to the value table.
3303 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3304 ValueList.push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003305
Chris Lattner83930552007-05-01 07:01:57 +00003306 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00003307 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00003308 unsigned CurBBNo = 0;
3309
Chris Lattner07d09ed2010-04-03 02:17:50 +00003310 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003311 auto getLastInstruction = [&]() -> Instruction * {
3312 if (CurBB && !CurBB->empty())
3313 return &CurBB->back();
3314 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3315 !FunctionBBs[CurBBNo - 1]->empty())
3316 return &FunctionBBs[CurBBNo - 1]->back();
3317 return nullptr;
3318 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003319
Chris Lattner85b7b402007-05-01 05:52:21 +00003320 // Read all the records.
3321 SmallVector<uint64_t, 64> Record;
3322 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00003323 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003324
Chris Lattner27d38752013-01-20 02:13:19 +00003325 switch (Entry.Kind) {
3326 case BitstreamEntry::Error:
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003327 return Error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003328 case BitstreamEntry::EndBlock:
3329 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00003330
Chris Lattner27d38752013-01-20 02:13:19 +00003331 case BitstreamEntry::SubBlock:
3332 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00003333 default: // Skip unknown content.
3334 if (Stream.SkipBlock())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003335 return Error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00003336 break;
3337 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003338 if (std::error_code EC = ParseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003339 return EC;
Chris Lattner83930552007-05-01 07:01:57 +00003340 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00003341 break;
3342 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003343 if (std::error_code EC = ParseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003344 return EC;
Chris Lattner85b7b402007-05-01 05:52:21 +00003345 break;
Devang Patelaf206b82009-09-18 19:26:43 +00003346 case bitc::METADATA_ATTACHMENT_ID:
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003347 if (std::error_code EC = ParseMetadataAttachment(*F))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003348 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003349 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00003350 case bitc::METADATA_BLOCK_ID:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003351 if (std::error_code EC = ParseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003352 return EC;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00003353 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003354 case bitc::USELIST_BLOCK_ID:
3355 if (std::error_code EC = ParseUseLists())
3356 return EC;
3357 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00003358 }
3359 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003360
Chris Lattner27d38752013-01-20 02:13:19 +00003361 case BitstreamEntry::Record:
3362 // The interesting case.
3363 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00003364 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003365
Chris Lattner85b7b402007-05-01 05:52:21 +00003366 // Read a record.
3367 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00003368 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00003369 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00003370 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00003371 default: // Default behavior: reject
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003372 return Error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003373 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00003374 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003375 return Error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00003376 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00003377 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003378
3379 // See if anything took the address of blocks in this function.
3380 auto BBFRI = BasicBlockFwdRefs.find(F);
3381 if (BBFRI == BasicBlockFwdRefs.end()) {
3382 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3383 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3384 } else {
3385 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003386 // Check for invalid basic block references.
3387 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003388 return Error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003389 assert(!BBRefs.empty() && "Unexpected empty array");
3390 assert(!BBRefs.front() && "Invalid reference to entry block");
3391 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3392 ++I)
3393 if (I < RE && BBRefs[I]) {
3394 BBRefs[I]->insertInto(F);
3395 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003396 } else {
3397 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3398 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003399
3400 // Erase from the table.
3401 BasicBlockFwdRefs.erase(BBFRI);
3402 }
3403
Chris Lattner83930552007-05-01 07:01:57 +00003404 CurBB = FunctionBBs[0];
3405 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003406 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003407
Chris Lattner07d09ed2010-04-03 02:17:50 +00003408 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3409 // This record indicates that the last instruction is at the same
3410 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003411 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003412
Craig Topper2617dcc2014-04-15 06:32:26 +00003413 if (!I)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003414 return Error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00003415 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003416 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003417 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003418
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00003419 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003420 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00003421 if (!I || Record.size() < 4)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003422 return Error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003423
Chris Lattner07d09ed2010-04-03 02:17:50 +00003424 unsigned Line = Record[0], Col = Record[1];
3425 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003426
Craig Topper2617dcc2014-04-15 06:32:26 +00003427 MDNode *Scope = nullptr, *IA = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003428 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3429 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3430 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3431 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003432 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003433 continue;
3434 }
3435
Chris Lattnere9759c22007-05-06 00:21:25 +00003436 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3437 unsigned OpNum = 0;
3438 Value *LHS, *RHS;
3439 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003440 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00003441 OpNum+1 > Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003442 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003443
Dan Gohman0ebd6962009-07-20 21:19:07 +00003444 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00003445 if (Opc == -1)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003446 return Error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003447 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00003448 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00003449 if (OpNum < Record.size()) {
3450 if (Opc == Instruction::Add ||
3451 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003452 Opc == Instruction::Mul ||
3453 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00003454 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00003455 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00003456 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00003457 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00003458 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003459 Opc == Instruction::UDiv ||
3460 Opc == Instruction::LShr ||
3461 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00003462 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00003463 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003464 } else if (isa<FPMathOperator>(I)) {
3465 FastMathFlags FMF;
Michael Ilseman65f14352012-12-09 21:12:04 +00003466 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
3467 FMF.setUnsafeAlgebra();
3468 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
3469 FMF.setNoNaNs();
3470 if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
3471 FMF.setNoInfs();
3472 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
3473 FMF.setNoSignedZeros();
3474 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
3475 FMF.setAllowReciprocal();
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003476 if (FMF.any())
3477 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00003478 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003479
Dan Gohman1b849082009-09-07 23:54:19 +00003480 }
Chris Lattner85b7b402007-05-01 05:52:21 +00003481 break;
3482 }
Chris Lattnere9759c22007-05-06 00:21:25 +00003483 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3484 unsigned OpNum = 0;
3485 Value *Op;
3486 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3487 OpNum+2 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003488 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003489
Chris Lattner229907c2011-07-18 04:54:35 +00003490 Type *ResTy = getTypeByID(Record[OpNum]);
Chris Lattnere9759c22007-05-06 00:21:25 +00003491 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003492 if (Opc == -1 || !ResTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003493 return Error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00003494 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003495 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3496 if (Temp) {
3497 InstructionList.push_back(Temp);
3498 CurBB->getInstList().push_back(Temp);
3499 }
3500 } else {
3501 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3502 }
Devang Patelaf206b82009-09-18 19:26:43 +00003503 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00003504 break;
3505 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00003506 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3507 case bitc::FUNC_CODE_INST_GEP_OLD:
3508 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003509 unsigned OpNum = 0;
David Blaikieb5b5efd2015-02-25 01:08:52 +00003510
3511 Type *Ty;
3512 bool InBounds;
3513
3514 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3515 InBounds = Record[OpNum++];
3516 Ty = getTypeByID(Record[OpNum++]);
3517 } else {
3518 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3519 Ty = nullptr;
3520 }
3521
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003522 Value *BasePtr;
3523 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003524 return Error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00003525
David Blaikie60310f22015-05-08 00:42:26 +00003526 if (!Ty)
3527 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
3528 ->getElementType();
3529 else if (Ty !=
3530 cast<SequentialType>(BasePtr->getType()->getScalarType())
3531 ->getElementType())
David Blaikie675e8cb2015-03-16 21:35:48 +00003532 return Error(
3533 "Explicit gep type does not match pointee type of pointer operand");
3534
Chris Lattner5285b5e2007-05-02 05:46:45 +00003535 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003536 while (OpNum != Record.size()) {
3537 Value *Op;
3538 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003539 return Error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003540 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003541 }
3542
David Blaikie096b1da2015-03-14 19:53:33 +00003543 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
David Blaikie675e8cb2015-03-16 21:35:48 +00003544
Devang Patelaf206b82009-09-18 19:26:43 +00003545 InstructionList.push_back(I);
David Blaikieb5b5efd2015-02-25 01:08:52 +00003546 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00003547 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003548 break;
3549 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003550
Dan Gohman1ecaf452008-05-31 00:58:22 +00003551 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3552 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00003553 unsigned OpNum = 0;
3554 Value *Agg;
3555 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003556 return Error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003557
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003558 unsigned RecSize = Record.size();
3559 if (OpNum == RecSize)
3560 return Error("EXTRACTVAL: Invalid instruction with 0 indices");
3561
Dan Gohman1ecaf452008-05-31 00:58:22 +00003562 SmallVector<unsigned, 4> EXTRACTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003563 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003564 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003565 bool IsArray = CurTy->isArrayTy();
3566 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003567 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003568
3569 if (!IsStruct && !IsArray)
3570 return Error("EXTRACTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003571 if ((unsigned)Index != Index)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003572 return Error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003573 if (IsStruct && Index >= CurTy->subtypes().size())
3574 return Error("EXTRACTVAL: Invalid struct index");
3575 if (IsArray && Index >= CurTy->getArrayNumElements())
3576 return Error("EXTRACTVAL: Invalid array index");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003577 EXTRACTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003578
3579 if (IsStruct)
3580 CurTy = CurTy->subtypes()[Index];
3581 else
3582 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00003583 }
3584
Jay Foad57aa6362011-07-13 10:26:04 +00003585 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003586 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00003587 break;
3588 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003589
Dan Gohman1ecaf452008-05-31 00:58:22 +00003590 case bitc::FUNC_CODE_INST_INSERTVAL: {
3591 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00003592 unsigned OpNum = 0;
3593 Value *Agg;
3594 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003595 return Error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003596 Value *Val;
3597 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003598 return Error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003599
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003600 unsigned RecSize = Record.size();
3601 if (OpNum == RecSize)
3602 return Error("INSERTVAL: Invalid instruction with 0 indices");
3603
Dan Gohman1ecaf452008-05-31 00:58:22 +00003604 SmallVector<unsigned, 4> INSERTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003605 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003606 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003607 bool IsArray = CurTy->isArrayTy();
3608 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003609 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003610
3611 if (!IsStruct && !IsArray)
3612 return Error("INSERTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003613 if ((unsigned)Index != Index)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003614 return Error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003615 if (IsStruct && Index >= CurTy->subtypes().size())
3616 return Error("INSERTVAL: Invalid struct index");
3617 if (IsArray && Index >= CurTy->getArrayNumElements())
3618 return Error("INSERTVAL: Invalid array index");
3619
Dan Gohman1ecaf452008-05-31 00:58:22 +00003620 INSERTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003621 if (IsStruct)
3622 CurTy = CurTy->subtypes()[Index];
3623 else
3624 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00003625 }
3626
Jay Foad57aa6362011-07-13 10:26:04 +00003627 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003628 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00003629 break;
3630 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003631
Chris Lattnere9759c22007-05-06 00:21:25 +00003632 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00003633 // obsolete form of select
3634 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00003635 unsigned OpNum = 0;
3636 Value *TrueVal, *FalseVal, *Cond;
3637 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003638 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3639 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003640 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003641
Dan Gohmanc5d28922008-09-16 01:01:33 +00003642 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00003643 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00003644 break;
3645 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003646
Dan Gohmanc5d28922008-09-16 01:01:33 +00003647 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3648 // new form of select
3649 // handles select i1 or select [N x i1]
3650 unsigned OpNum = 0;
3651 Value *TrueVal, *FalseVal, *Cond;
3652 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003653 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00003654 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003655 return Error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00003656
3657 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00003658 if (VectorType* vector_type =
3659 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00003660 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003661 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003662 return Error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00003663 } else {
3664 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003665 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003666 return Error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003667 }
3668
Gabor Greife9ecc682008-04-06 20:25:17 +00003669 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00003670 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003671 break;
3672 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003673
Chris Lattner1fc27f02007-05-02 05:16:49 +00003674 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00003675 unsigned OpNum = 0;
3676 Value *Vec, *Idx;
3677 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003678 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003679 return Error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003680 if (!Vec->getType()->isVectorTy())
3681 return Error("Invalid type for value");
Eric Christopherc9742252009-07-25 02:28:41 +00003682 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00003683 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003684 break;
3685 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003686
Chris Lattner1fc27f02007-05-02 05:16:49 +00003687 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00003688 unsigned OpNum = 0;
3689 Value *Vec, *Elt, *Idx;
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003690 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3691 return Error("Invalid record");
3692 if (!Vec->getType()->isVectorTy())
3693 return Error("Invalid type for value");
3694 if (popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00003695 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003696 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003697 return Error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00003698 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00003699 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003700 break;
3701 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003702
Chris Lattnere9759c22007-05-06 00:21:25 +00003703 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3704 unsigned OpNum = 0;
3705 Value *Vec1, *Vec2, *Mask;
3706 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003707 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003708 return Error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00003709
Mon P Wang25f01062008-11-10 04:46:22 +00003710 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003711 return Error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003712 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3713 return Error("Invalid type for value");
Chris Lattner1fc27f02007-05-02 05:16:49 +00003714 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00003715 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003716 break;
3717 }
Mon P Wang25f01062008-11-10 04:46:22 +00003718
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003719 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3720 // Old form of ICmp/FCmp returning bool
3721 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3722 // both legal on vectors but had different behaviour.
3723 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3724 // FCmp/ICmp returning bool or vector of bool
3725
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003726 unsigned OpNum = 0;
3727 Value *LHS, *RHS;
3728 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003729 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003730 OpNum+1 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003731 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003732
Duncan Sands9dff9be2010-02-15 16:12:20 +00003733 if (LHS->getType()->isFPOrFPVectorTy())
Dan Gohmanad1f0a12009-08-25 23:17:54 +00003734 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003735 else
Dan Gohmanad1f0a12009-08-25 23:17:54 +00003736 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00003737 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00003738 break;
3739 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003740
Chris Lattnere53603e2007-05-02 04:27:25 +00003741 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00003742 {
3743 unsigned Size = Record.size();
3744 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00003745 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003746 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00003747 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003748 }
Devang Patelbbfd8742008-02-26 01:29:32 +00003749
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003750 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00003751 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00003752 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003753 return Error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00003754 if (OpNum != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003755 return Error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003756
Chris Lattnerf1c87102011-06-17 18:09:11 +00003757 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003758 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003759 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00003760 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003761 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00003762 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003763 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003764 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003765 if (!TrueDest)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003766 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003767
Devang Patelaf206b82009-09-18 19:26:43 +00003768 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00003769 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003770 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00003771 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003772 else {
3773 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003774 Value *Cond = getValue(Record, 2, NextValueNo,
3775 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00003776 if (!FalseDest || !Cond)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003777 return Error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00003778 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003779 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003780 }
3781 break;
3782 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00003783 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003784 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003785 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00003786 // "New" SwitchInst format with case ranges. The changes to write this
3787 // format were reverted but we still recognize bitcode that uses it.
3788 // Hopefully someday we will have support for case ranges and can use
3789 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003790
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003791 Type *OpTy = getTypeByID(Record[1]);
3792 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3793
Jan Wen Voungafaced02012-10-11 20:20:40 +00003794 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003795 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003796 if (!OpTy || !Cond || !Default)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003797 return Error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003798
3799 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003800
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003801 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3802 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003803
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003804 unsigned CurIdx = 5;
3805 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00003806 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003807 unsigned NumItems = Record[CurIdx++];
3808 for (unsigned ci = 0; ci != NumItems; ++ci) {
3809 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003810
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003811 APInt Low;
3812 unsigned ActiveWords = 1;
3813 if (ValueBitWidth > 64)
3814 ActiveWords = Record[CurIdx++];
Benjamin Kramer9704ed02012-05-28 14:10:31 +00003815 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3816 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003817 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00003818
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003819 if (!isSingleNumber) {
3820 ActiveWords = 1;
3821 if (ValueBitWidth > 64)
3822 ActiveWords = Record[CurIdx++];
3823 APInt High =
Benjamin Kramer9704ed02012-05-28 14:10:31 +00003824 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3825 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003826 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00003827
3828 // FIXME: It is not clear whether values in the range should be
3829 // compared as signed or unsigned values. The partially
3830 // implemented changes that used this format in the past used
3831 // unsigned comparisons.
3832 for ( ; Low.ule(High); ++Low)
3833 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003834 } else
Bob Wilsone4077362013-09-09 19:14:35 +00003835 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003836 }
3837 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00003838 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3839 cve = CaseVals.end(); cvi != cve; ++cvi)
3840 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003841 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003842 I = SI;
3843 break;
3844 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003845
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003846 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003847
Chris Lattner5285b5e2007-05-02 05:46:45 +00003848 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003849 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003850 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003851 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003852 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003853 if (!OpTy || !Cond || !Default)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003854 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003855 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00003856 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00003857 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003858 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003859 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00003860 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3861 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003862 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00003863 delete SI;
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003864 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003865 }
3866 SI->addCase(CaseVal, DestBB);
3867 }
3868 I = SI;
3869 break;
3870 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003871 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00003872 if (Record.size() < 2)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003873 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003874 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003875 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00003876 if (!OpTy || !Address)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003877 return Error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00003878 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00003879 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00003880 InstructionList.push_back(IBI);
3881 for (unsigned i = 0, e = NumDests; i != e; ++i) {
3882 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3883 IBI->addDestination(DestBB);
3884 } else {
3885 delete IBI;
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003886 return Error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00003887 }
3888 }
3889 I = IBI;
3890 break;
3891 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003892
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00003893 case bitc::FUNC_CODE_INST_INVOKE: {
3894 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003895 if (Record.size() < 4)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003896 return Error("Invalid record");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00003897 unsigned OpNum = 0;
3898 AttributeSet PAL = getAttributes(Record[OpNum++]);
3899 unsigned CCInfo = Record[OpNum++];
3900 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
3901 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003902
David Blaikie5ea1f7b2015-04-24 18:06:06 +00003903 FunctionType *FTy = nullptr;
3904 if (CCInfo >> 13 & 1 &&
3905 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
3906 return Error("Explicit invoke type is not a function type");
3907
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003908 Value *Callee;
3909 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003910 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003911
Chris Lattner229907c2011-07-18 04:54:35 +00003912 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
David Blaikie5ea1f7b2015-04-24 18:06:06 +00003913 if (!CalleeTy)
3914 return Error("Callee is not a pointer");
3915 if (!FTy) {
3916 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
3917 if (!FTy)
3918 return Error("Callee is not of pointer to function type");
3919 } else if (CalleeTy->getElementType() != FTy)
3920 return Error("Explicit invoke type does not match pointee type of "
3921 "callee operand");
3922 if (Record.size() < FTy->getNumParams() + OpNum)
3923 return Error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003924
Chris Lattner5285b5e2007-05-02 05:46:45 +00003925 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003926 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00003927 Ops.push_back(getValue(Record, OpNum, NextValueNo,
3928 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00003929 if (!Ops.back())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003930 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003931 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003932
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003933 if (!FTy->isVarArg()) {
3934 if (Record.size() != OpNum)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003935 return Error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003936 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003937 // Read type/value pairs for varargs params.
3938 while (OpNum != Record.size()) {
3939 Value *Op;
3940 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003941 return Error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003942 Ops.push_back(Op);
3943 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003944 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003945
Jay Foad5bd375a2011-07-15 08:37:34 +00003946 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patelaf206b82009-09-18 19:26:43 +00003947 InstructionList.push_back(I);
David Blaikie5ea1f7b2015-04-24 18:06:06 +00003948 cast<InvokeInst>(I)
3949 ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00003950 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003951 break;
3952 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00003953 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3954 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00003955 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00003956 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003957 return Error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00003958 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00003959 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00003960 break;
3961 }
Chris Lattnere53603e2007-05-02 04:27:25 +00003962 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00003963 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00003964 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00003965 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00003966 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00003967 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003968 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003969 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003970 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003971 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003972
Jay Foad52131342011-03-30 11:28:46 +00003973 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00003974 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003975
Chris Lattnere14cb882007-05-04 19:11:41 +00003976 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00003977 Value *V;
3978 // With the new function encoding, it is possible that operands have
3979 // negative IDs (for forward references). Use a signed VBR
3980 // representation to keep the encoding small.
3981 if (UseRelativeIDs)
3982 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3983 else
3984 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00003985 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003986 if (!V || !BB)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003987 return Error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00003988 PN->addIncoming(V, BB);
3989 }
3990 I = PN;
3991 break;
3992 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003993
Bill Wendlingfae14752011-08-12 20:24:12 +00003994 case bitc::FUNC_CODE_INST_LANDINGPAD: {
3995 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3996 unsigned Idx = 0;
3997 if (Record.size() < 4)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00003998 return Error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00003999 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004000 if (!Ty)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004001 return Error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00004002 Value *PersFn = nullptr;
Bill Wendlingfae14752011-08-12 20:24:12 +00004003 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004004 return Error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00004005
4006 bool IsCleanup = !!Record[Idx++];
4007 unsigned NumClauses = Record[Idx++];
4008 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
4009 LP->setCleanup(IsCleanup);
4010 for (unsigned J = 0; J != NumClauses; ++J) {
4011 LandingPadInst::ClauseType CT =
4012 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4013 Value *Val;
4014
4015 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4016 delete LP;
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004017 return Error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00004018 }
4019
4020 assert((CT != LandingPadInst::Catch ||
4021 !isa<ArrayType>(Val->getType())) &&
4022 "Catch clause has a invalid type!");
4023 assert((CT != LandingPadInst::Filter ||
4024 isa<ArrayType>(Val->getType())) &&
4025 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004026 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00004027 }
4028
4029 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00004030 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00004031 break;
4032 }
4033
Chris Lattnerf1c87102011-06-17 18:09:11 +00004034 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4035 if (Record.size() != 4)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004036 return Error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00004037 uint64_t AlignRecord = Record[3];
4038 const uint64_t InAllocaMask = uint64_t(1) << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00004039 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4040 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
JF Bastien30bf96b2015-02-22 19:32:03 +00004041 bool InAlloca = AlignRecord & InAllocaMask;
David Blaikiebdb49102015-04-28 16:51:01 +00004042 Type *Ty = getTypeByID(Record[0]);
4043 if ((AlignRecord & ExplicitTypeMask) == 0) {
4044 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4045 if (!PTy)
4046 return Error("Old-style alloca with a non-pointer type");
4047 Ty = PTy->getElementType();
4048 }
4049 Type *OpTy = getTypeByID(Record[1]);
4050 Value *Size = getFnValueByID(Record[2], OpTy);
JF Bastien30bf96b2015-02-22 19:32:03 +00004051 unsigned Align;
4052 if (std::error_code EC =
David Blaikiebdb49102015-04-28 16:51:01 +00004053 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
JF Bastien30bf96b2015-02-22 19:32:03 +00004054 return EC;
4055 }
Rafael Espindola48da4f42013-11-04 16:16:24 +00004056 if (!Ty || !Size)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004057 return Error("Invalid record");
David Blaikiebdb49102015-04-28 16:51:01 +00004058 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00004059 AI->setUsedWithInAlloca(InAlloca);
4060 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00004061 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00004062 break;
4063 }
Chris Lattner9f600c52007-05-03 22:04:19 +00004064 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004065 unsigned OpNum = 0;
4066 Value *Op;
4067 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004068 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004069 return Error("Invalid record");
David Blaikie85035652015-02-25 01:07:20 +00004070
4071 Type *Ty = nullptr;
4072 if (OpNum + 3 == Record.size())
4073 Ty = getTypeByID(Record[OpNum++]);
Filipe Cabecinhas9a19e562015-04-30 01:13:31 +00004074 if (!isa<PointerType>(Op->getType()))
4075 return Error("Load operand is not a pointer type");
David Blaikieb7a029872015-04-17 19:56:21 +00004076 if (!Ty)
4077 Ty = cast<PointerType>(Op->getType())->getElementType();
4078 else if (Ty != cast<PointerType>(Op->getType())->getElementType())
4079 return Error("Explicit load type does not match pointee type of "
4080 "pointer operand");
David Blaikie85035652015-02-25 01:07:20 +00004081
JF Bastien30bf96b2015-02-22 19:32:03 +00004082 unsigned Align;
4083 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4084 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00004085 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
David Blaikie85035652015-02-25 01:07:20 +00004086
Devang Patelaf206b82009-09-18 19:26:43 +00004087 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00004088 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00004089 }
Eli Friedman59b66882011-08-09 23:02:53 +00004090 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4091 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4092 unsigned OpNum = 0;
4093 Value *Op;
4094 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004095 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004096 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004097
David Blaikie85035652015-02-25 01:07:20 +00004098 Type *Ty = nullptr;
4099 if (OpNum + 5 == Record.size())
4100 Ty = getTypeByID(Record[OpNum++]);
4101
Eli Friedman59b66882011-08-09 23:02:53 +00004102 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
4103 if (Ordering == NotAtomic || Ordering == Release ||
4104 Ordering == AcquireRelease)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004105 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004106 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004107 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004108 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4109
JF Bastien30bf96b2015-02-22 19:32:03 +00004110 unsigned Align;
4111 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4112 return EC;
4113 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
David Blaikie85035652015-02-25 01:07:20 +00004114
Yaron Kerend602c352015-02-28 15:29:17 +00004115 (void)Ty;
David Blaikie85035652015-02-25 01:07:20 +00004116 assert((!Ty || Ty == I->getType()) &&
4117 "Explicit type doesn't match pointee type of the first operand");
4118
Eli Friedman59b66882011-08-09 23:02:53 +00004119 InstructionList.push_back(I);
4120 break;
4121 }
David Blaikie612ddbf2015-04-22 04:14:42 +00004122 case bitc::FUNC_CODE_INST_STORE:
4123 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004124 unsigned OpNum = 0;
4125 Value *Val, *Ptr;
4126 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie612ddbf2015-04-22 04:14:42 +00004127 (BitCode == bitc::FUNC_CODE_INST_STORE
4128 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4129 : popValue(Record, OpNum, NextValueNo,
4130 cast<PointerType>(Ptr->getType())->getElementType(),
4131 Val)) ||
4132 OpNum + 2 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004133 return Error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00004134 unsigned Align;
4135 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4136 return EC;
4137 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
Devang Patelaf206b82009-09-18 19:26:43 +00004138 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004139 break;
4140 }
David Blaikie50a06152015-04-22 04:14:46 +00004141 case bitc::FUNC_CODE_INST_STOREATOMIC:
4142 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
Eli Friedman59b66882011-08-09 23:02:53 +00004143 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4144 unsigned OpNum = 0;
4145 Value *Val, *Ptr;
4146 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie50a06152015-04-22 04:14:46 +00004147 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4148 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4149 : popValue(Record, OpNum, NextValueNo,
4150 cast<PointerType>(Ptr->getType())->getElementType(),
4151 Val)) ||
4152 OpNum + 4 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004153 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004154
4155 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman222b5a42011-09-19 19:41:28 +00004156 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman59b66882011-08-09 23:02:53 +00004157 Ordering == AcquireRelease)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004158 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004159 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4160 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004161 return Error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004162
JF Bastien30bf96b2015-02-22 19:32:03 +00004163 unsigned Align;
4164 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4165 return EC;
4166 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
Eli Friedman59b66882011-08-09 23:02:53 +00004167 InstructionList.push_back(I);
4168 break;
4169 }
David Blaikie2a661cd2015-04-28 04:30:29 +00004170 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004171 case bitc::FUNC_CODE_INST_CMPXCHG: {
Tim Northovere94a5182014-03-11 10:48:52 +00004172 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
Tim Northover420a2162014-06-13 14:24:07 +00004173 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004174 unsigned OpNum = 0;
4175 Value *Ptr, *Cmp, *New;
4176 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie2a661cd2015-04-28 04:30:29 +00004177 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4178 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4179 : popValue(Record, OpNum, NextValueNo,
4180 cast<PointerType>(Ptr->getType())->getElementType(),
4181 Cmp)) ||
4182 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4183 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004184 return Error("Invalid record");
Tim Northovere94a5182014-03-11 10:48:52 +00004185 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
4186 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004187 return Error("Invalid record");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004188 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
Tim Northovere94a5182014-03-11 10:48:52 +00004189
4190 AtomicOrdering FailureOrdering;
4191 if (Record.size() < 7)
4192 FailureOrdering =
4193 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4194 else
4195 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
4196
4197 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4198 SynchScope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004199 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00004200
4201 if (Record.size() < 8) {
4202 // Before weak cmpxchgs existed, the instruction simply returned the
4203 // value loaded from memory, so bitcode files from that era will be
4204 // expecting the first component of a modern cmpxchg.
4205 CurBB->getInstList().push_back(I);
4206 I = ExtractValueInst::Create(I, 0);
4207 } else {
4208 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4209 }
4210
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004211 InstructionList.push_back(I);
4212 break;
4213 }
4214 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4215 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4216 unsigned OpNum = 0;
4217 Value *Ptr, *Val;
4218 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004219 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004220 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4221 OpNum+4 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004222 return Error("Invalid record");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004223 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
4224 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4225 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004226 return Error("Invalid record");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004227 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
Eli Friedman59b66882011-08-09 23:02:53 +00004228 if (Ordering == NotAtomic || Ordering == Unordered)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004229 return Error("Invalid record");
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004230 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
4231 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4232 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4233 InstructionList.push_back(I);
4234 break;
4235 }
Eli Friedmanfee02c62011-07-25 23:16:38 +00004236 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4237 if (2 != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004238 return Error("Invalid record");
Eli Friedmanfee02c62011-07-25 23:16:38 +00004239 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
4240 if (Ordering == NotAtomic || Ordering == Unordered ||
4241 Ordering == Monotonic)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004242 return Error("Invalid record");
Eli Friedmanfee02c62011-07-25 23:16:38 +00004243 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
4244 I = new FenceInst(Context, Ordering, SynchScope);
4245 InstructionList.push_back(I);
4246 break;
4247 }
Chris Lattnerc44070802011-06-17 18:17:37 +00004248 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004249 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4250 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004251 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004252
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004253 unsigned OpNum = 0;
4254 AttributeSet PAL = getAttributes(Record[OpNum++]);
4255 unsigned CCInfo = Record[OpNum++];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004256
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004257 FunctionType *FTy = nullptr;
4258 if (CCInfo >> 15 & 1 &&
4259 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4260 return Error("Explicit call type is not a function type");
4261
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004262 Value *Callee;
4263 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004264 return Error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004265
Chris Lattner229907c2011-07-18 04:54:35 +00004266 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004267 if (!OpTy)
4268 return Error("Callee is not a pointer type");
David Blaikie348de692015-04-23 21:36:23 +00004269 if (!FTy) {
4270 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4271 if (!FTy)
4272 return Error("Callee is not of pointer to function type");
4273 } else if (OpTy->getElementType() != FTy)
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004274 return Error("Explicit call type does not match pointee type of "
4275 "callee operand");
4276 if (Record.size() < FTy->getNumParams() + OpNum)
4277 return Error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004278
Chris Lattner9f600c52007-05-03 22:04:19 +00004279 SmallVector<Value*, 16> Args;
4280 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004281 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004282 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00004283 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00004284 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00004285 Args.push_back(getValue(Record, OpNum, NextValueNo,
4286 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004287 if (!Args.back())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004288 return Error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004289 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004290
Chris Lattner9f600c52007-05-03 22:04:19 +00004291 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00004292 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004293 if (OpNum != Record.size())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004294 return Error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004295 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004296 while (OpNum != Record.size()) {
4297 Value *Op;
4298 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004299 return Error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004300 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00004301 }
4302 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004303
David Blaikie348de692015-04-23 21:36:23 +00004304 I = CallInst::Create(FTy, Callee, Args);
Devang Patelaf206b82009-09-18 19:26:43 +00004305 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00004306 cast<CallInst>(I)->setCallingConv(
Reid Kleckner5772b772014-04-24 20:14:34 +00004307 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4308 CallInst::TailCallKind TCK = CallInst::TCK_None;
4309 if (CCInfo & 1)
4310 TCK = CallInst::TCK_Tail;
4311 if (CCInfo & (1 << 14))
4312 TCK = CallInst::TCK_MustTail;
4313 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00004314 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner9f600c52007-05-03 22:04:19 +00004315 break;
4316 }
4317 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4318 if (Record.size() < 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004319 return Error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004320 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004321 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00004322 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00004323 if (!OpTy || !Op || !ResTy)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004324 return Error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004325 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00004326 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00004327 break;
4328 }
Chris Lattner83930552007-05-01 07:01:57 +00004329 }
4330
4331 // Add instruction to end of current BB. If there is no current BB, reject
4332 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00004333 if (!CurBB) {
Chris Lattner83930552007-05-01 07:01:57 +00004334 delete I;
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004335 return Error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00004336 }
4337 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004338
Chris Lattner83930552007-05-01 07:01:57 +00004339 // If this was a terminator instruction, move to the next block.
4340 if (isa<TerminatorInst>(I)) {
4341 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00004342 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00004343 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004344
Chris Lattner83930552007-05-01 07:01:57 +00004345 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00004346 if (I && !I->getType()->isVoidTy())
Chris Lattner83930552007-05-01 07:01:57 +00004347 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00004348 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004349
Chris Lattner27d38752013-01-20 02:13:19 +00004350OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00004351
Chris Lattner83930552007-05-01 07:01:57 +00004352 // Check the function list for unresolved values.
4353 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004354 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00004355 // We found at least one unresolved value. Nuke them all to avoid leaks.
4356 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00004357 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00004358 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00004359 delete A;
4360 }
4361 }
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004362 return Error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00004363 }
Chris Lattner83930552007-05-01 07:01:57 +00004364 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004365
Dan Gohman9b9ff462010-08-25 20:23:38 +00004366 // FIXME: Check for unresolved forward-declared metadata references
4367 // and clean up leaks.
4368
Chris Lattner85b7b402007-05-01 05:52:21 +00004369 // Trim the value list down to the size it was before we parsed this function.
4370 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman26d837d2010-08-25 20:22:53 +00004371 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00004372 std::vector<BasicBlock*>().swap(FunctionBBs);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004373 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004374}
4375
Rafael Espindola7d712032013-11-05 17:16:08 +00004376/// Find the function body in the bitcode stream
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004377std::error_code BitcodeReader::FindFunctionInStream(
4378 Function *F,
4379 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004380 while (DeferredFunctionInfoIterator->second == 0) {
4381 if (Stream.AtEndOfStream())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004382 return Error("Could not find function in stream");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004383 // ParseModule will parse the next body in the stream and set its
4384 // position in the DeferredFunctionInfo map.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004385 if (std::error_code EC = ParseModule(true))
Rafael Espindola7d712032013-11-05 17:16:08 +00004386 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004387 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004388 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004389}
4390
Chris Lattner9eeada92007-05-18 04:02:46 +00004391//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004392// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00004393//===----------------------------------------------------------------------===//
4394
Rafael Espindolac3f9b5a2014-06-23 21:53:12 +00004395void BitcodeReader::releaseBuffer() { Buffer.release(); }
Chris Lattner9eeada92007-05-18 04:02:46 +00004396
Rafael Espindola5a52e6d2014-10-24 22:50:48 +00004397std::error_code BitcodeReader::materialize(GlobalValue *GV) {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004398 if (std::error_code EC = materializeMetadata())
4399 return EC;
4400
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004401 Function *F = dyn_cast<Function>(GV);
4402 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004403 if (!F || !F->isMaterializable())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004404 return std::error_code();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004405
4406 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00004407 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004408 // If its position is recorded as 0, its body is somewhere in the stream
4409 // but we haven't seen it yet.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004410 if (DFII->second == 0 && LazyStreamer)
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004411 if (std::error_code EC = FindFunctionInStream(F, DFII))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004412 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004413
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004414 // Move the bit stream to the saved position of the deferred function body.
4415 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004416
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004417 if (std::error_code EC = ParseFunctionBody(F))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004418 return EC;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00004419 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00004420
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00004421 if (StripDebugInfo)
4422 stripDebugInfo(*F);
4423
Chandler Carruth7132e002007-08-04 01:51:18 +00004424 // Upgrade any old intrinsic calls in the function.
4425 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
4426 E = UpgradedIntrinsics.end(); I != E; ++I) {
4427 if (I->first != I->second) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00004428 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4429 UI != UE;) {
Chandler Carruth7132e002007-08-04 01:51:18 +00004430 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4431 UpgradeIntrinsicCall(CI, I->second);
4432 }
4433 }
4434 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004435
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004436 // Bring in any functions that this function forward-referenced via
4437 // blockaddresses.
4438 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00004439}
4440
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004441bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4442 const Function *F = dyn_cast<Function>(GV);
4443 if (!F || F->isDeclaration())
4444 return false;
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004445
4446 // Dematerializing F would leave dangling references that wouldn't be
4447 // reconnected on re-materialization.
4448 if (BlockAddressesTaken.count(F))
4449 return false;
4450
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004451 return DeferredFunctionInfo.count(const_cast<Function*>(F));
4452}
4453
Eric Christopher97cb5652015-05-15 18:20:14 +00004454void BitcodeReader::dematerialize(GlobalValue *GV) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004455 Function *F = dyn_cast<Function>(GV);
4456 // If this function isn't dematerializable, this is a noop.
4457 if (!F || !isDematerializable(F))
Chris Lattner9eeada92007-05-18 04:02:46 +00004458 return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004459
Chris Lattner9eeada92007-05-18 04:02:46 +00004460 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004461
Chris Lattner9eeada92007-05-18 04:02:46 +00004462 // Just forget the function body, we can remat it later.
Petar Jovanovic7480e4d2014-09-23 12:54:19 +00004463 F->dropAllReferences();
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00004464 F->setIsMaterializable(true);
Chris Lattner9eeada92007-05-18 04:02:46 +00004465}
4466
Eric Christopher97cb5652015-05-15 18:20:14 +00004467std::error_code BitcodeReader::materializeModule(Module *M) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004468 assert(M == TheModule &&
4469 "Can only Materialize the Module this BitcodeReader is attached to.");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004470
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004471 if (std::error_code EC = materializeMetadata())
4472 return EC;
4473
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004474 // Promise to materialize all forward references.
4475 WillMaterializeAllForwardRefs = true;
4476
Chris Lattner06310bf2009-06-16 05:15:21 +00004477 // Iterate over the module, deserializing any functions that are still on
4478 // disk.
4479 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004480 F != E; ++F) {
Rafael Espindola246c4fb2014-11-01 16:46:18 +00004481 if (std::error_code EC = materialize(F))
4482 return EC;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004483 }
Derek Schuff92ef9752012-02-29 00:07:09 +00004484 // At this point, if there are any function bodies, the current bit is
4485 // pointing to the END_BLOCK record after them. Now make sure the rest
4486 // of the bits in the module have been read.
4487 if (NextUnreadBit)
4488 ParseModule(true);
4489
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004490 // Check that all block address forward references got resolved (as we
4491 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004492 if (!BasicBlockFwdRefs.empty())
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004493 return Error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004494
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004495 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4496 // delete the old functions to clean up. We can't do this unless the entire
4497 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00004498 // with calls to the old function.
4499 for (std::vector<std::pair<Function*, Function*> >::iterator I =
4500 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
4501 if (I->first != I->second) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00004502 for (auto UI = I->first->user_begin(), UE = I->first->user_end();
4503 UI != UE;) {
Chandler Carruth7132e002007-08-04 01:51:18 +00004504 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
4505 UpgradeIntrinsicCall(CI, I->second);
4506 }
Chris Lattner647cffb2009-04-01 01:43:03 +00004507 if (!I->first->use_empty())
4508 I->first->replaceAllUsesWith(I->second);
Chandler Carruth7132e002007-08-04 01:51:18 +00004509 I->first->eraseFromParent();
4510 }
4511 }
4512 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
Devang Patel80ae3492009-08-28 23:24:31 +00004513
Manman Ren209b17c2013-09-28 00:22:27 +00004514 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4515 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4516
Manman Ren8b4306c2013-12-02 21:29:56 +00004517 UpgradeDebugInfo(*M);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004518 return std::error_code();
Chris Lattner9eeada92007-05-18 04:02:46 +00004519}
4520
Rafael Espindola2fa1e432014-12-03 07:18:23 +00004521std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4522 return IdentifiedStructTypes;
4523}
4524
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004525std::error_code BitcodeReader::InitStream() {
Rafael Espindola48da4f42013-11-04 16:16:24 +00004526 if (LazyStreamer)
4527 return InitLazyStream();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004528 return InitStreamFromBuffer();
4529}
4530
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004531std::error_code BitcodeReader::InitStreamFromBuffer() {
Roman Divacky4717a8d2012-09-06 15:42:13 +00004532 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004533 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4534
Rafael Espindola27435252014-07-29 21:01:24 +00004535 if (Buffer->getBufferSize() & 3)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004536 return Error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004537
4538 // If we have a wrapper header, parse it and ignore the non-bc file contents.
4539 // The magic number is 0x0B17C0DE stored in little endian.
4540 if (isBitcodeWrapper(BufPtr, BufEnd))
4541 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004542 return Error("Invalid bitcode wrapper header");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004543
4544 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00004545 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004546
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004547 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004548}
4549
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004550std::error_code BitcodeReader::InitLazyStream() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004551 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4552 // see it.
Yaron Keren06d69302014-12-18 10:03:35 +00004553 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
Rafael Espindola7d727b52014-12-18 05:08:43 +00004554 StreamingMemoryObject &Bytes = *OwnedBytes;
Yaron Keren06d69302014-12-18 10:03:35 +00004555 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00004556 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004557
4558 unsigned char buf[16];
Rafael Espindola7d727b52014-12-18 05:08:43 +00004559 if (Bytes.readBytes(buf, 16, 0) != 16)
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004560 return Error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004561
4562 if (!isBitcode(buf, buf + 16))
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004563 return Error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004564
4565 if (isBitcodeWrapper(buf, buf + 4)) {
4566 const unsigned char *bitcodeStart = buf;
4567 const unsigned char *bitcodeEnd = buf + 16;
4568 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
Rafael Espindola7d727b52014-12-18 05:08:43 +00004569 Bytes.dropLeadingBytes(bitcodeStart - buf);
4570 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004571 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004572 return std::error_code();
Rafael Espindola48da4f42013-11-04 16:16:24 +00004573}
4574
4575namespace {
Rafael Espindola25188c92014-06-12 01:45:43 +00004576class BitcodeErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +00004577 const char *name() const LLVM_NOEXCEPT override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00004578 return "llvm.bitcode";
4579 }
Craig Topper73156022014-03-02 09:09:27 +00004580 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00004581 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004582 switch (E) {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00004583 case BitcodeError::InvalidBitcodeSignature:
Rafael Espindola48da4f42013-11-04 16:16:24 +00004584 return "Invalid bitcode signature";
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004585 case BitcodeError::CorruptedBitcode:
4586 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00004587 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00004588 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00004589 }
4590};
4591}
4592
Chris Bieneman770163e2014-09-19 20:29:02 +00004593static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4594
Rafael Espindolac3f2e732014-07-29 20:22:46 +00004595const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00004596 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004597}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004598
Chris Lattner6694f602007-04-29 07:54:31 +00004599//===----------------------------------------------------------------------===//
4600// External interface
4601//===----------------------------------------------------------------------===//
4602
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00004603/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00004604///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00004605/// This isn't always used in a lazy context. In particular, it's also used by
4606/// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
4607/// in forward-referenced functions from block address references.
4608///
4609/// \param[in] WillMaterializeAll Set to \c true if the caller promises to
4610/// materialize everything -- in particular, if this isn't truly lazy.
Rafael Espindolae2c1d772014-08-26 22:00:09 +00004611static ErrorOr<Module *>
Rafael Espindola68812152014-09-03 17:31:46 +00004612getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004613 LLVMContext &Context, bool WillMaterializeAll,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004614 DiagnosticHandlerFunction DiagnosticHandler,
4615 bool ShouldLazyLoadMetadata = false) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004616 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004617 BitcodeReader *R =
4618 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004619 M->setMaterializer(R);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004620
4621 auto cleanupOnError = [&](std::error_code EC) {
Rafael Espindola8fb31112014-06-18 20:07:35 +00004622 R->releaseBuffer(); // Never take ownership on error.
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004623 delete M; // Also deletes R.
Rafael Espindola5b6c1e82014-01-13 18:31:04 +00004624 return EC;
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004625 };
Rafael Espindolab7993462012-01-02 07:49:53 +00004626
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004627 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
4628 if (std::error_code EC = R->ParseBitcodeInto(M, ShouldLazyLoadMetadata))
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004629 return cleanupOnError(EC);
4630
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00004631 if (!WillMaterializeAll)
4632 // Resolve forward references from blockaddresses.
4633 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4634 return cleanupOnError(EC);
Rafael Espindolab7993462012-01-02 07:49:53 +00004635
Rafael Espindolae2c1d772014-08-26 22:00:09 +00004636 Buffer.release(); // The BitcodeReader owns it now.
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004637 return M;
Chris Lattner6694f602007-04-29 07:54:31 +00004638}
4639
Rafael Espindolae2c1d772014-08-26 22:00:09 +00004640ErrorOr<Module *>
Rafael Espindola68812152014-09-03 17:31:46 +00004641llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004642 LLVMContext &Context,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004643 DiagnosticHandlerFunction DiagnosticHandler,
4644 bool ShouldLazyLoadMetadata) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004645 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004646 DiagnosticHandler, ShouldLazyLoadMetadata);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00004647}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004648
Rafael Espindola7d727b52014-12-18 05:08:43 +00004649ErrorOr<std::unique_ptr<Module>>
4650llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004651 LLVMContext &Context,
4652 DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindola7d727b52014-12-18 05:08:43 +00004653 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004654 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004655 M->setMaterializer(R);
Rafael Espindola7d727b52014-12-18 05:08:43 +00004656 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
4657 return EC;
4658 return std::move(M);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004659}
4660
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004661ErrorOr<Module *>
4662llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4663 DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00004664 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004665 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
4666 std::move(Buf), Context, true, DiagnosticHandler);
Rafael Espindola8f31e212014-01-15 01:08:23 +00004667 if (!ModuleOrErr)
4668 return ModuleOrErr;
Rafael Espindola5b6c1e82014-01-13 18:31:04 +00004669 Module *M = ModuleOrErr.get();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004670 // Read in the entire module, and destroy the BitcodeReader.
Rafael Espindolad96d5532014-08-26 21:49:01 +00004671 if (std::error_code EC = M->materializeAllPermanently()) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004672 delete M;
Rafael Espindola8f31e212014-01-15 01:08:23 +00004673 return EC;
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004674 }
Bill Wendling0198ce02010-10-06 01:22:42 +00004675
Chad Rosierca2567b2011-12-07 21:44:12 +00004676 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4677 // written. We must defer until the Module has been fully materialized.
4678
Chris Lattner6694f602007-04-29 07:54:31 +00004679 return M;
4680}
Bill Wendling0198ce02010-10-06 01:22:42 +00004681
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004682std::string
4683llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4684 DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00004685 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004686 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4687 DiagnosticHandler);
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004688 ErrorOr<std::string> Triple = R->parseTriple();
Rafael Espindolad346cc82014-07-04 13:52:01 +00004689 if (Triple.getError())
4690 return "";
4691 return Triple.get();
Bill Wendling0198ce02010-10-06 01:22:42 +00004692}