blob: 11c9b131da7059387605ee0c57822f50ecf1c14d [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"
Teresa Johnson403a7872015-10-04 14:33:43 +000030#include "llvm/IR/FunctionInfo.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000031#include "llvm/IR/ValueHandle.h"
Derek Schuff8b2dcad2012-02-06 22:30:29 +000032#include "llvm/Support/DataStream.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000033#include "llvm/Support/ManagedStatic.h"
Chris Lattner08feb1e2007-04-24 04:04:35 +000034#include "llvm/Support/MathExtras.h"
Chris Lattner6694f602007-04-29 07:54:31 +000035#include "llvm/Support/MemoryBuffer.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000036#include "llvm/Support/raw_ostream.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000037#include <deque>
Chris Lattner1314b992007-04-22 06:23:29 +000038using namespace llvm;
39
Benjamin Kramercced8be2015-03-17 20:40:24 +000040namespace {
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +000041enum {
42 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
43};
44
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +000045/// Indicates which operator an operand allows (for the few operands that may
46/// only reference a certain operator).
47enum OperatorConstraint {
48 OC_None = 0, // No constraint
49 OC_CatchPad, // Must be CatchPadInst
50 OC_CleanupPad // Must be CleanupPadInst
51};
52
Benjamin Kramercced8be2015-03-17 20:40:24 +000053class BitcodeReaderValueList {
54 std::vector<WeakVH> ValuePtrs;
55
Rafael Espindolacbdcb502015-06-15 20:55:37 +000056 /// As we resolve forward-referenced constants, we add information about them
57 /// to this vector. This allows us to resolve them in bulk instead of
58 /// resolving each reference at a time. See the code in
Benjamin Kramercced8be2015-03-17 20:40:24 +000059 /// ResolveConstantForwardRefs for more information about this.
60 ///
61 /// The key of this vector is the placeholder constant, the value is the slot
62 /// number that holds the resolved value.
63 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
64 ResolveConstantsTy ResolveConstants;
65 LLVMContext &Context;
66public:
67 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
68 ~BitcodeReaderValueList() {
69 assert(ResolveConstants.empty() && "Constants not resolved?");
70 }
71
72 // vector compatibility methods
73 unsigned size() const { return ValuePtrs.size(); }
74 void resize(unsigned N) { ValuePtrs.resize(N); }
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +000075 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
Benjamin Kramercced8be2015-03-17 20:40:24 +000076
77 void clear() {
78 assert(ResolveConstants.empty() && "Constants not resolved?");
79 ValuePtrs.clear();
80 }
81
82 Value *operator[](unsigned i) const {
83 assert(i < ValuePtrs.size());
84 return ValuePtrs[i];
85 }
86
87 Value *back() const { return ValuePtrs.back(); }
88 void pop_back() { ValuePtrs.pop_back(); }
89 bool empty() const { return ValuePtrs.empty(); }
90 void shrinkTo(unsigned N) {
91 assert(N <= size() && "Invalid shrinkTo request!");
92 ValuePtrs.resize(N);
93 }
94
95 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +000096 Value *getValueFwdRef(unsigned Idx, Type *Ty,
97 OperatorConstraint OC = OC_None);
Benjamin Kramercced8be2015-03-17 20:40:24 +000098
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +000099 bool assignValue(Value *V, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000100
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000101 /// Once all constants are read, this method bulk resolves any forward
102 /// references.
103 void resolveConstantForwardRefs();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000104};
105
106class BitcodeReaderMDValueList {
107 unsigned NumFwdRefs;
108 bool AnyFwdRefs;
109 unsigned MinFwdRef;
110 unsigned MaxFwdRef;
111 std::vector<TrackingMDRef> MDValuePtrs;
112
113 LLVMContext &Context;
114public:
115 BitcodeReaderMDValueList(LLVMContext &C)
116 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
117
118 // vector compatibility methods
119 unsigned size() const { return MDValuePtrs.size(); }
120 void resize(unsigned N) { MDValuePtrs.resize(N); }
121 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
122 void clear() { MDValuePtrs.clear(); }
123 Metadata *back() const { return MDValuePtrs.back(); }
124 void pop_back() { MDValuePtrs.pop_back(); }
125 bool empty() const { return MDValuePtrs.empty(); }
126
127 Metadata *operator[](unsigned i) const {
128 assert(i < MDValuePtrs.size());
129 return MDValuePtrs[i];
130 }
131
132 void shrinkTo(unsigned N) {
133 assert(N <= size() && "Invalid shrinkTo request!");
134 MDValuePtrs.resize(N);
135 }
136
137 Metadata *getValueFwdRef(unsigned Idx);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000138 void assignValue(Metadata *MD, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000139 void tryToResolveCycles();
140};
141
142class BitcodeReader : public GVMaterializer {
143 LLVMContext &Context;
144 DiagnosticHandlerFunction DiagnosticHandler;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000145 Module *TheModule = nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000146 std::unique_ptr<MemoryBuffer> Buffer;
147 std::unique_ptr<BitstreamReader> StreamFile;
148 BitstreamCursor Stream;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000149 // Next offset to start scanning for lazy parsing of function bodies.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000150 uint64_t NextUnreadBit = 0;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000151 // Last function offset found in the VST.
152 uint64_t LastFunctionBlockBit = 0;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000153 bool SeenValueSymbolTable = false;
Peter Collingbourne128a9762015-10-27 23:01:25 +0000154 uint64_t VSTOffset = 0;
Mehdi Amini5d303282015-10-26 18:37:00 +0000155 // Contains an arbitrary and optional string identifying the bitcode producer
156 std::string ProducerIdentification;
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +0000157 // Number of module level metadata records specified by the
158 // MODULE_CODE_METADATA_VALUES record.
159 unsigned NumModuleMDs = 0;
160 // Support older bitcode without the MODULE_CODE_METADATA_VALUES record.
161 bool SeenModuleValuesRecord = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000162
163 std::vector<Type*> TypeList;
164 BitcodeReaderValueList ValueList;
165 BitcodeReaderMDValueList MDValueList;
166 std::vector<Comdat *> ComdatList;
167 SmallVector<Instruction *, 64> InstructionList;
168
169 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
170 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
171 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
172 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
David Majnemer7fddecc2015-06-17 20:52:32 +0000173 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000174
175 SmallVector<Instruction*, 64> InstsWithTBAATag;
176
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000177 /// The set of attributes by index. Index zero in the file is for null, and
178 /// is thus not represented here. As such all indices are off by one.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000179 std::vector<AttributeSet> MAttributes;
180
Karl Schimpf36440082015-08-31 16:43:55 +0000181 /// The set of attribute groups.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000182 std::map<unsigned, AttributeSet> MAttributeGroups;
183
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000184 /// While parsing a function body, this is a list of the basic blocks for the
185 /// function.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000186 std::vector<BasicBlock*> FunctionBBs;
187
188 // When reading the module header, this list is populated with functions that
189 // have bodies later in the file.
190 std::vector<Function*> FunctionsWithBodies;
191
192 // When intrinsic functions are encountered which require upgrading they are
193 // stored here with their replacement function.
Rafael Espindola4e721212015-07-02 16:22:40 +0000194 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000195 UpgradedIntrinsicMap UpgradedIntrinsics;
196
197 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
198 DenseMap<unsigned, unsigned> MDKindMap;
199
200 // Several operations happen after the module header has been read, but
201 // before function bodies are processed. This keeps track of whether
202 // we've done this yet.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000203 bool SeenFirstFunctionBody = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000204
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000205 /// When function bodies are initially scanned, this map contains info about
206 /// where to find deferred function body in the stream.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000207 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
208
209 /// When Metadata block is initially scanned when parsing the module, we may
210 /// choose to defer parsing of the metadata. This vector contains info about
211 /// which Metadata blocks are deferred.
212 std::vector<uint64_t> DeferredMetadataInfo;
213
214 /// These are basic blocks forward-referenced by block addresses. They are
215 /// inserted lazily into functions when they're loaded. The basic block ID is
216 /// its index into the vector.
217 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
218 std::deque<Function *> BasicBlockFwdRefQueue;
219
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000220 /// Indicates that we are using a new encoding for instruction operands where
221 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
222 /// instruction number, for a more compact encoding. Some instruction
223 /// operands are not relative to the instruction ID: basic block numbers, and
224 /// types. Once the old style function blocks have been phased out, we would
Benjamin Kramercced8be2015-03-17 20:40:24 +0000225 /// not need this flag.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000226 bool UseRelativeIDs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000227
228 /// True if all functions will be materialized, negating the need to process
229 /// (e.g.) blockaddress forward references.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000230 bool WillMaterializeAllForwardRefs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000231
232 /// Functions that have block addresses taken. This is usually empty.
233 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
234
235 /// True if any Metadata block has been materialized.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000236 bool IsMetadataMaterialized = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000237
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000238 bool StripDebugInfo = false;
239
Peter Collingbourned4bff302015-11-05 22:03:56 +0000240 /// Functions that need to be matched with subprograms when upgrading old
241 /// metadata.
242 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
243
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000244 std::vector<std::string> BundleTags;
245
Benjamin Kramercced8be2015-03-17 20:40:24 +0000246public:
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000247 std::error_code error(BitcodeError E, const Twine &Message);
248 std::error_code error(BitcodeError E);
249 std::error_code error(const Twine &Message);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000250
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000251 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
252 DiagnosticHandlerFunction DiagnosticHandler);
Rafael Espindola1aabf982015-06-16 23:29:49 +0000253 BitcodeReader(LLVMContext &Context,
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000254 DiagnosticHandlerFunction DiagnosticHandler);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000255 ~BitcodeReader() override { freeState(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000256
257 std::error_code materializeForwardReferencedFunctions();
258
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000259 void freeState();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000260
261 void releaseBuffer();
262
263 bool isDematerializable(const GlobalValue *GV) const override;
264 std::error_code materialize(GlobalValue *GV) override;
Eric Christopher97cb5652015-05-15 18:20:14 +0000265 std::error_code materializeModule(Module *M) override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000266 std::vector<StructType *> getIdentifiedStructTypes() const override;
Eric Christopher97cb5652015-05-15 18:20:14 +0000267 void dematerialize(GlobalValue *GV) override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000268
Rafael Espindola6ace6852015-06-15 21:02:49 +0000269 /// \brief Main interface to parsing a bitcode buffer.
270 /// \returns true if an error occurred.
Rafael Espindola1aabf982015-06-16 23:29:49 +0000271 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
272 Module *M,
Benjamin Kramercced8be2015-03-17 20:40:24 +0000273 bool ShouldLazyLoadMetadata = false);
274
Rafael Espindola6ace6852015-06-15 21:02:49 +0000275 /// \brief Cheap mechanism to just extract module triple
276 /// \returns true if an error occurred.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000277 ErrorOr<std::string> parseTriple();
278
Mehdi Amini3383ccc2015-11-09 02:46:41 +0000279 /// Cheap mechanism to just extract the identification block out of bitcode.
280 ErrorOr<std::string> parseIdentificationBlock();
281
Benjamin Kramercced8be2015-03-17 20:40:24 +0000282 static uint64_t decodeSignRotatedValue(uint64_t V);
283
284 /// Materialize any deferred Metadata block.
285 std::error_code materializeMetadata() override;
286
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000287 void setStripDebugInfo() override;
288
Benjamin Kramercced8be2015-03-17 20:40:24 +0000289private:
Mehdi Amini5d303282015-10-26 18:37:00 +0000290 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
291 // ProducerIdentification data member, and do some basic enforcement on the
292 // "epoch" encoded in the bitcode.
293 std::error_code parseBitcodeVersion();
294
Benjamin Kramercced8be2015-03-17 20:40:24 +0000295 std::vector<StructType *> IdentifiedStructTypes;
296 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
297 StructType *createIdentifiedStructType(LLVMContext &Context);
298
299 Type *getTypeByID(unsigned ID);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000300 Value *getFnValueByID(unsigned ID, Type *Ty,
301 OperatorConstraint OC = OC_None) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000302 if (Ty && Ty->isMetadataTy())
303 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000304 return ValueList.getValueFwdRef(ID, Ty, OC);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000305 }
306 Metadata *getFnMetadataByID(unsigned ID) {
307 return MDValueList.getValueFwdRef(ID);
308 }
309 BasicBlock *getBasicBlock(unsigned ID) const {
310 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
311 return FunctionBBs[ID];
312 }
313 AttributeSet getAttributes(unsigned i) const {
314 if (i-1 < MAttributes.size())
315 return MAttributes[i-1];
316 return AttributeSet();
317 }
318
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000319 /// Read a value/type pair out of the specified record from slot 'Slot'.
320 /// Increment Slot past the number of slots used in the record. Return true on
321 /// failure.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000322 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
323 unsigned InstNum, Value *&ResVal) {
324 if (Slot == Record.size()) return true;
325 unsigned ValNo = (unsigned)Record[Slot++];
326 // Adjust the ValNo, if it was encoded relative to the InstNum.
327 if (UseRelativeIDs)
328 ValNo = InstNum - ValNo;
329 if (ValNo < InstNum) {
330 // If this is not a forward reference, just return the value we already
331 // have.
332 ResVal = getFnValueByID(ValNo, nullptr);
333 return ResVal == nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000334 }
David Blaikiedbe6e0f2015-04-17 06:40:14 +0000335 if (Slot == Record.size())
336 return true;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000337
338 unsigned TypeNo = (unsigned)Record[Slot++];
339 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
340 return ResVal == nullptr;
341 }
342
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000343 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
344 /// past the number of slots used by the value in the record. Return true if
345 /// there is an error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000346 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000347 unsigned InstNum, Type *Ty, Value *&ResVal,
348 OperatorConstraint OC = OC_None) {
349 if (getValue(Record, Slot, InstNum, Ty, ResVal, OC))
Benjamin Kramercced8be2015-03-17 20:40:24 +0000350 return true;
351 // All values currently take a single record slot.
352 ++Slot;
353 return false;
354 }
355
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000356 /// Like popValue, but does not increment the Slot number.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000357 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000358 unsigned InstNum, Type *Ty, Value *&ResVal,
359 OperatorConstraint OC = OC_None) {
360 ResVal = getValue(Record, Slot, InstNum, Ty, OC);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000361 return ResVal == nullptr;
362 }
363
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000364 /// Version of getValue that returns ResVal directly, or 0 if there is an
365 /// error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000366 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000367 unsigned InstNum, Type *Ty, OperatorConstraint OC = OC_None) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000368 if (Slot == Record.size()) return nullptr;
369 unsigned ValNo = (unsigned)Record[Slot];
370 // Adjust the ValNo, if it was encoded relative to the InstNum.
371 if (UseRelativeIDs)
372 ValNo = InstNum - ValNo;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000373 return getFnValueByID(ValNo, Ty, OC);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000374 }
375
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000376 /// Like getValue, but decodes signed VBRs.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000377 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000378 unsigned InstNum, Type *Ty,
379 OperatorConstraint OC = OC_None) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000380 if (Slot == Record.size()) return nullptr;
381 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
382 // Adjust the ValNo, if it was encoded relative to the InstNum.
383 if (UseRelativeIDs)
384 ValNo = InstNum - ValNo;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000385 return getFnValueByID(ValNo, Ty, OC);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000386 }
387
388 /// Converts alignment exponent (i.e. power of two (or zero)) to the
389 /// corresponding alignment to use. If alignment is too large, returns
390 /// a corresponding error code.
391 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000392 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
Teresa Johnson1493ad92015-10-10 14:18:36 +0000393 std::error_code parseModule(uint64_t ResumeBit,
394 bool ShouldLazyLoadMetadata = false);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000395 std::error_code parseAttributeBlock();
396 std::error_code parseAttributeGroupBlock();
397 std::error_code parseTypeTable();
398 std::error_code parseTypeTableBody();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000399 std::error_code parseOperandBundleTags();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000400
Teresa Johnsonff642b92015-09-17 20:12:00 +0000401 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
402 unsigned NameIndex, Triple &TT);
Peter Collingbourne128a9762015-10-27 23:01:25 +0000403 std::error_code parseValueSymbolTable(uint64_t Offset = 0);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000404 std::error_code parseConstants();
Teresa Johnson1493ad92015-10-10 14:18:36 +0000405 std::error_code rememberAndSkipFunctionBodies();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000406 std::error_code rememberAndSkipFunctionBody();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000407 /// Save the positions of the Metadata blocks and skip parsing the blocks.
408 std::error_code rememberAndSkipMetadata();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000409 std::error_code parseFunctionBody(Function *F);
410 std::error_code globalCleanup();
411 std::error_code resolveGlobalAndAliasInits();
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +0000412 std::error_code parseMetadata(bool ModuleLevel = false);
Teresa Johnson12545072015-11-15 02:00:09 +0000413 std::error_code parseMetadataKinds();
414 std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000415 std::error_code parseMetadataAttachment(Function &F);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000416 ErrorOr<std::string> parseModuleTriple();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000417 std::error_code parseUseLists();
Rafael Espindola1aabf982015-06-16 23:29:49 +0000418 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000419 std::error_code initStreamFromBuffer();
Rafael Espindola1aabf982015-06-16 23:29:49 +0000420 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000421 std::error_code findFunctionInStream(
Benjamin Kramercced8be2015-03-17 20:40:24 +0000422 Function *F,
423 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
424};
Teresa Johnson403a7872015-10-04 14:33:43 +0000425
426/// Class to manage reading and parsing function summary index bitcode
427/// files/sections.
428class FunctionIndexBitcodeReader {
Teresa Johnson403a7872015-10-04 14:33:43 +0000429 DiagnosticHandlerFunction DiagnosticHandler;
430
431 /// Eventually points to the function index built during parsing.
432 FunctionInfoIndex *TheIndex = nullptr;
433
434 std::unique_ptr<MemoryBuffer> Buffer;
435 std::unique_ptr<BitstreamReader> StreamFile;
436 BitstreamCursor Stream;
437
438 /// \brief Used to indicate whether we are doing lazy parsing of summary data.
439 ///
440 /// If false, the summary section is fully parsed into the index during
441 /// the initial parse. Otherwise, if true, the caller is expected to
442 /// invoke \a readFunctionSummary for each summary needed, and the summary
443 /// section is thus parsed lazily.
444 bool IsLazy = false;
445
446 /// Used to indicate whether caller only wants to check for the presence
447 /// of the function summary bitcode section. All blocks are skipped,
448 /// but the SeenFuncSummary boolean is set.
449 bool CheckFuncSummaryPresenceOnly = false;
450
451 /// Indicates whether we have encountered a function summary section
452 /// yet during parsing, used when checking if file contains function
453 /// summary section.
454 bool SeenFuncSummary = false;
455
456 /// \brief Map populated during function summary section parsing, and
457 /// consumed during ValueSymbolTable parsing.
458 ///
459 /// Used to correlate summary records with VST entries. For the per-module
460 /// index this maps the ValueID to the parsed function summary, and
461 /// for the combined index this maps the summary record's bitcode
462 /// offset to the function summary (since in the combined index the
463 /// VST records do not hold value IDs but rather hold the function
464 /// summary record offset).
465 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>> SummaryMap;
466
467 /// Map populated during module path string table parsing, from the
468 /// module ID to a string reference owned by the index's module
469 /// path string table, used to correlate with combined index function
470 /// summary records.
471 DenseMap<uint64_t, StringRef> ModuleIdMap;
472
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000473public:
Teresa Johnson403a7872015-10-04 14:33:43 +0000474 std::error_code error(BitcodeError E, const Twine &Message);
475 std::error_code error(BitcodeError E);
476 std::error_code error(const Twine &Message);
477
Mehdi Amini354f5202015-11-19 05:52:29 +0000478 FunctionIndexBitcodeReader(MemoryBuffer *Buffer,
Teresa Johnson403a7872015-10-04 14:33:43 +0000479 DiagnosticHandlerFunction DiagnosticHandler,
480 bool IsLazy = false,
481 bool CheckFuncSummaryPresenceOnly = false);
Mehdi Amini354f5202015-11-19 05:52:29 +0000482 FunctionIndexBitcodeReader(DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson403a7872015-10-04 14:33:43 +0000483 bool IsLazy = false,
484 bool CheckFuncSummaryPresenceOnly = false);
485 ~FunctionIndexBitcodeReader() { freeState(); }
486
487 void freeState();
488
489 void releaseBuffer();
490
491 /// Check if the parser has encountered a function summary section.
492 bool foundFuncSummary() { return SeenFuncSummary; }
493
494 /// \brief Main interface to parsing a bitcode buffer.
495 /// \returns true if an error occurred.
496 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
497 FunctionInfoIndex *I);
498
499 /// \brief Interface for parsing a function summary lazily.
500 std::error_code parseFunctionSummary(std::unique_ptr<DataStreamer> Streamer,
501 FunctionInfoIndex *I,
502 size_t FunctionSummaryOffset);
503
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000504private:
Teresa Johnson403a7872015-10-04 14:33:43 +0000505 std::error_code parseModule();
506 std::error_code parseValueSymbolTable();
507 std::error_code parseEntireSummary();
508 std::error_code parseModuleStringTable();
509 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
510 std::error_code initStreamFromBuffer();
511 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
512};
Benjamin Kramercced8be2015-03-17 20:40:24 +0000513} // namespace
514
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000515BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
516 DiagnosticSeverity Severity,
517 const Twine &Msg)
518 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
519
520void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
521
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000522static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000523 std::error_code EC, const Twine &Message) {
524 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
525 DiagnosticHandler(DI);
526 return EC;
527}
528
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000529static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000530 std::error_code EC) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000531 return error(DiagnosticHandler, EC, EC.message());
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000532}
533
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000534static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000535 const Twine &Message) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000536 return error(DiagnosticHandler,
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000537 make_error_code(BitcodeError::CorruptedBitcode), Message);
538}
539
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000540std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
Mehdi Amini5d303282015-10-26 18:37:00 +0000541 if (!ProducerIdentification.empty()) {
Filipe Cabecinhasf3e167a2015-11-03 13:48:21 +0000542 return ::error(DiagnosticHandler, make_error_code(E),
543 Message + " (Producer: '" + ProducerIdentification +
544 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
Mehdi Amini5d303282015-10-26 18:37:00 +0000545 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000546 return ::error(DiagnosticHandler, make_error_code(E), Message);
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000547}
548
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000549std::error_code BitcodeReader::error(const Twine &Message) {
Mehdi Amini5d303282015-10-26 18:37:00 +0000550 if (!ProducerIdentification.empty()) {
Mehdi Amini5d303282015-10-26 18:37:00 +0000551 return ::error(DiagnosticHandler,
Filipe Cabecinhasf3e167a2015-11-03 13:48:21 +0000552 make_error_code(BitcodeError::CorruptedBitcode),
553 Message + " (Producer: '" + ProducerIdentification +
554 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
Mehdi Amini5d303282015-10-26 18:37:00 +0000555 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000556 return ::error(DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000557 make_error_code(BitcodeError::CorruptedBitcode), Message);
558}
559
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000560std::error_code BitcodeReader::error(BitcodeError E) {
561 return ::error(DiagnosticHandler, make_error_code(E));
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000562}
563
564static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
565 LLVMContext &C) {
566 if (F)
567 return F;
568 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
569}
570
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000571BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000572 DiagnosticHandlerFunction DiagnosticHandler)
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000573 : Context(Context),
574 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
Rafael Espindola1c863ca2015-06-22 18:06:15 +0000575 Buffer(Buffer), ValueList(Context), MDValueList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000576
Rafael Espindola1aabf982015-06-16 23:29:49 +0000577BitcodeReader::BitcodeReader(LLVMContext &Context,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000578 DiagnosticHandlerFunction DiagnosticHandler)
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000579 : Context(Context),
580 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
Rafael Espindola1c863ca2015-06-22 18:06:15 +0000581 Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000582
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000583std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
584 if (WillMaterializeAllForwardRefs)
585 return std::error_code();
586
587 // Prevent recursion.
588 WillMaterializeAllForwardRefs = true;
589
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000590 while (!BasicBlockFwdRefQueue.empty()) {
591 Function *F = BasicBlockFwdRefQueue.front();
592 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000593 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000594 if (!BasicBlockFwdRefs.count(F))
595 // Already materialized.
596 continue;
597
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000598 // Check for a function that isn't materializable to prevent an infinite
599 // loop. When parsing a blockaddress stored in a global variable, there
600 // isn't a trivial way to check if a function will have a body without a
601 // linear search through FunctionsWithBodies, so just check it here.
602 if (!F->isMaterializable())
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000603 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000604
605 // Try to materialize F.
Rafael Espindola5a52e6d2014-10-24 22:50:48 +0000606 if (std::error_code EC = materialize(F))
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000607 return EC;
Rafael Espindolab7993462012-01-02 07:49:53 +0000608 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000609 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000610
611 // Reset state.
612 WillMaterializeAllForwardRefs = false;
613 return std::error_code();
Rafael Espindolab7993462012-01-02 07:49:53 +0000614}
615
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000616void BitcodeReader::freeState() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000617 Buffer = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000618 std::vector<Type*>().swap(TypeList);
Chris Lattner9eeada92007-05-18 04:02:46 +0000619 ValueList.clear();
Devang Patel05eb6172009-08-04 06:00:18 +0000620 MDValueList.clear();
David Majnemerdad0a642014-06-27 18:19:56 +0000621 std::vector<Comdat *>().swap(ComdatList);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000622
Bill Wendlinge94d8432012-12-07 23:16:57 +0000623 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattner9eeada92007-05-18 04:02:46 +0000624 std::vector<BasicBlock*>().swap(FunctionBBs);
625 std::vector<Function*>().swap(FunctionsWithBodies);
626 DeferredFunctionInfo.clear();
Manman Ren4a9b0eb2015-03-13 19:24:30 +0000627 DeferredMetadataInfo.clear();
Dan Gohman43aa8f02010-07-20 21:42:28 +0000628 MDKindMap.clear();
Benjamin Kramer736a4fc2012-09-21 14:34:31 +0000629
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +0000630 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000631 BasicBlockFwdRefQueue.clear();
Chris Lattner6694f602007-04-29 07:54:31 +0000632}
633
Chris Lattnerfee5a372007-05-04 03:30:17 +0000634//===----------------------------------------------------------------------===//
635// Helper functions to implement forward reference resolution, etc.
636//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +0000637
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000638/// Convert a string from a record into an std::string, return true on failure.
639template <typename StrTy>
640static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattnerccaa4482007-04-23 21:26:05 +0000641 StrTy &Result) {
Chris Lattnere14cb882007-05-04 19:11:41 +0000642 if (Idx > Record.size())
Chris Lattner1314b992007-04-22 06:23:29 +0000643 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000644
Chris Lattnere14cb882007-05-04 19:11:41 +0000645 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
646 Result += (char)Record[i];
Chris Lattner1314b992007-04-22 06:23:29 +0000647 return false;
648}
649
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000650static bool hasImplicitComdat(size_t Val) {
651 switch (Val) {
652 default:
653 return false;
654 case 1: // Old WeakAnyLinkage
655 case 4: // Old LinkOnceAnyLinkage
656 case 10: // Old WeakODRLinkage
657 case 11: // Old LinkOnceODRLinkage
658 return true;
659 }
660}
661
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000662static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000663 switch (Val) {
664 default: // Map unknown/new linkages to external
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000665 case 0:
666 return GlobalValue::ExternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000667 case 2:
668 return GlobalValue::AppendingLinkage;
669 case 3:
670 return GlobalValue::InternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000671 case 5:
672 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
673 case 6:
674 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
675 case 7:
676 return GlobalValue::ExternalWeakLinkage;
677 case 8:
678 return GlobalValue::CommonLinkage;
679 case 9:
680 return GlobalValue::PrivateLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000681 case 12:
682 return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000683 case 13:
684 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
685 case 14:
686 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Rafael Espindolabec6af62015-01-08 15:39:50 +0000687 case 15:
688 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000689 case 1: // Old value with implicit comdat.
690 case 16:
691 return GlobalValue::WeakAnyLinkage;
692 case 10: // Old value with implicit comdat.
693 case 17:
694 return GlobalValue::WeakODRLinkage;
695 case 4: // Old value with implicit comdat.
696 case 18:
697 return GlobalValue::LinkOnceAnyLinkage;
698 case 11: // Old value with implicit comdat.
699 case 19:
700 return GlobalValue::LinkOnceODRLinkage;
Chris Lattner1314b992007-04-22 06:23:29 +0000701 }
702}
703
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000704static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000705 switch (Val) {
706 default: // Map unknown visibilities to default.
707 case 0: return GlobalValue::DefaultVisibility;
708 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000709 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000710 }
711}
712
Nico Rieck7157bb72014-01-14 15:22:47 +0000713static GlobalValue::DLLStorageClassTypes
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000714getDecodedDLLStorageClass(unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000715 switch (Val) {
716 default: // Map unknown values to default.
717 case 0: return GlobalValue::DefaultStorageClass;
718 case 1: return GlobalValue::DLLImportStorageClass;
719 case 2: return GlobalValue::DLLExportStorageClass;
720 }
721}
722
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000723static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000724 switch (Val) {
725 case 0: return GlobalVariable::NotThreadLocal;
726 default: // Map unknown non-zero value to general dynamic.
727 case 1: return GlobalVariable::GeneralDynamicTLSModel;
728 case 2: return GlobalVariable::LocalDynamicTLSModel;
729 case 3: return GlobalVariable::InitialExecTLSModel;
730 case 4: return GlobalVariable::LocalExecTLSModel;
731 }
732}
733
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000734static int getDecodedCastOpcode(unsigned Val) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000735 switch (Val) {
736 default: return -1;
737 case bitc::CAST_TRUNC : return Instruction::Trunc;
738 case bitc::CAST_ZEXT : return Instruction::ZExt;
739 case bitc::CAST_SEXT : return Instruction::SExt;
740 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
741 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
742 case bitc::CAST_UITOFP : return Instruction::UIToFP;
743 case bitc::CAST_SITOFP : return Instruction::SIToFP;
744 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
745 case bitc::CAST_FPEXT : return Instruction::FPExt;
746 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
747 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
748 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000749 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000750 }
751}
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000752
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000753static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000754 bool IsFP = Ty->isFPOrFPVectorTy();
755 // BinOps are only valid for int/fp or vector of int/fp types
756 if (!IsFP && !Ty->isIntOrIntVectorTy())
757 return -1;
758
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000759 switch (Val) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000760 default:
761 return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000762 case bitc::BINOP_ADD:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000763 return IsFP ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000764 case bitc::BINOP_SUB:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000765 return IsFP ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000766 case bitc::BINOP_MUL:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000767 return IsFP ? Instruction::FMul : Instruction::Mul;
768 case bitc::BINOP_UDIV:
769 return IsFP ? -1 : Instruction::UDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000770 case bitc::BINOP_SDIV:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000771 return IsFP ? Instruction::FDiv : Instruction::SDiv;
772 case bitc::BINOP_UREM:
773 return IsFP ? -1 : Instruction::URem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000774 case bitc::BINOP_SREM:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000775 return IsFP ? Instruction::FRem : Instruction::SRem;
776 case bitc::BINOP_SHL:
777 return IsFP ? -1 : Instruction::Shl;
778 case bitc::BINOP_LSHR:
779 return IsFP ? -1 : Instruction::LShr;
780 case bitc::BINOP_ASHR:
781 return IsFP ? -1 : Instruction::AShr;
782 case bitc::BINOP_AND:
783 return IsFP ? -1 : Instruction::And;
784 case bitc::BINOP_OR:
785 return IsFP ? -1 : Instruction::Or;
786 case bitc::BINOP_XOR:
787 return IsFP ? -1 : Instruction::Xor;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000788 }
789}
790
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000791static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000792 switch (Val) {
793 default: return AtomicRMWInst::BAD_BINOP;
794 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
795 case bitc::RMW_ADD: return AtomicRMWInst::Add;
796 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
797 case bitc::RMW_AND: return AtomicRMWInst::And;
798 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
799 case bitc::RMW_OR: return AtomicRMWInst::Or;
800 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
801 case bitc::RMW_MAX: return AtomicRMWInst::Max;
802 case bitc::RMW_MIN: return AtomicRMWInst::Min;
803 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
804 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
805 }
806}
807
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000808static AtomicOrdering getDecodedOrdering(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000809 switch (Val) {
810 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
811 case bitc::ORDERING_UNORDERED: return Unordered;
812 case bitc::ORDERING_MONOTONIC: return Monotonic;
813 case bitc::ORDERING_ACQUIRE: return Acquire;
814 case bitc::ORDERING_RELEASE: return Release;
815 case bitc::ORDERING_ACQREL: return AcquireRelease;
816 default: // Map unknown orderings to sequentially-consistent.
817 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
818 }
819}
820
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000821static SynchronizationScope getDecodedSynchScope(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000822 switch (Val) {
823 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
824 default: // Map unknown scopes to cross-thread.
825 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
826 }
827}
828
David Majnemerdad0a642014-06-27 18:19:56 +0000829static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
830 switch (Val) {
831 default: // Map unknown selection kinds to any.
832 case bitc::COMDAT_SELECTION_KIND_ANY:
833 return Comdat::Any;
834 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
835 return Comdat::ExactMatch;
836 case bitc::COMDAT_SELECTION_KIND_LARGEST:
837 return Comdat::Largest;
838 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
839 return Comdat::NoDuplicates;
840 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
841 return Comdat::SameSize;
842 }
843}
844
James Molloy88eb5352015-07-10 12:52:00 +0000845static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
846 FastMathFlags FMF;
847 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
848 FMF.setUnsafeAlgebra();
849 if (0 != (Val & FastMathFlags::NoNaNs))
850 FMF.setNoNaNs();
851 if (0 != (Val & FastMathFlags::NoInfs))
852 FMF.setNoInfs();
853 if (0 != (Val & FastMathFlags::NoSignedZeros))
854 FMF.setNoSignedZeros();
855 if (0 != (Val & FastMathFlags::AllowReciprocal))
856 FMF.setAllowReciprocal();
857 return FMF;
858}
859
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000860static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000861 switch (Val) {
862 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
863 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
864 }
865}
866
Gabor Greiff6caff662008-05-10 08:32:32 +0000867namespace llvm {
Chris Lattner1663cca2007-04-24 05:48:56 +0000868namespace {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000869/// \brief A class for maintaining the slot number definition
870/// as a placeholder for the actual definition for forward constants defs.
871class ConstantPlaceHolder : public ConstantExpr {
872 void operator=(const ConstantPlaceHolder &) = delete;
873
874public:
875 // allocate space for exactly one operand
876 void *operator new(size_t s) { return User::operator new(s, 1); }
877 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
Gabor Greiff6caff662008-05-10 08:32:32 +0000878 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000879 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
880 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000881
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000882 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
883 static bool classof(const Value *V) {
884 return isa<ConstantExpr>(V) &&
885 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
886 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000887
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000888 /// Provide fast operand accessors
889 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
890};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000891}
Chris Lattner1663cca2007-04-24 05:48:56 +0000892
Chris Lattner2d8cd802009-03-31 22:55:09 +0000893// FIXME: can we inherit this from ConstantExpr?
Gabor Greiff6caff662008-05-10 08:32:32 +0000894template <>
Jay Foadc8adf5f2011-01-11 15:07:38 +0000895struct OperandTraits<ConstantPlaceHolder> :
896 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greiff6caff662008-05-10 08:32:32 +0000897};
Richard Trieue3d126c2014-11-21 02:42:08 +0000898DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000899}
Gabor Greiff6caff662008-05-10 08:32:32 +0000900
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000901bool BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000902 if (Idx == size()) {
903 push_back(V);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000904 return false;
Chris Lattner2d8cd802009-03-31 22:55:09 +0000905 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000906
Chris Lattner2d8cd802009-03-31 22:55:09 +0000907 if (Idx >= size())
908 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000909
Chris Lattner2d8cd802009-03-31 22:55:09 +0000910 WeakVH &OldV = ValuePtrs[Idx];
Craig Topper2617dcc2014-04-15 06:32:26 +0000911 if (!OldV) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000912 OldV = V;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000913 return false;
Chris Lattner2d8cd802009-03-31 22:55:09 +0000914 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000915
Chris Lattner2d8cd802009-03-31 22:55:09 +0000916 // Handle constants and non-constants (e.g. instrs) differently for
917 // efficiency.
918 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
919 ResolveConstants.push_back(std::make_pair(PHC, Idx));
920 OldV = V;
921 } else {
922 // If there was a forward reference to this value, replace it.
923 Value *PrevVal = OldV;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000924 // Check operator constraints. We only put cleanuppads or catchpads in
925 // the forward value map if the value is constrained to match.
926 if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(PrevVal)) {
927 if (!isa<CatchPadInst>(V))
928 return true;
929 // Delete the dummy basic block that was created with the sentinel
930 // catchpad.
931 BasicBlock *DummyBlock = CatchPad->getUnwindDest();
932 assert(DummyBlock == CatchPad->getNormalDest());
933 CatchPad->dropAllReferences();
934 delete DummyBlock;
935 } else if (isa<CleanupPadInst>(PrevVal)) {
936 if (!isa<CleanupPadInst>(V))
937 return true;
938 }
Chris Lattner2d8cd802009-03-31 22:55:09 +0000939 OldV->replaceAllUsesWith(V);
940 delete PrevVal;
Gabor Greiff6caff662008-05-10 08:32:32 +0000941 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000942
943 return false;
Gabor Greiff6caff662008-05-10 08:32:32 +0000944}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000945
Gabor Greiff6caff662008-05-10 08:32:32 +0000946
Chris Lattner1663cca2007-04-24 05:48:56 +0000947Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattner229907c2011-07-18 04:54:35 +0000948 Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000949 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000950 resize(Idx + 1);
Chris Lattner1663cca2007-04-24 05:48:56 +0000951
Chris Lattner2d8cd802009-03-31 22:55:09 +0000952 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhas6a92a3f2015-05-27 01:05:40 +0000953 if (Ty != V->getType())
954 report_fatal_error("Type mismatch in constant table!");
Chris Lattner83930552007-05-01 07:01:57 +0000955 return cast<Constant>(V);
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000956 }
Chris Lattner1663cca2007-04-24 05:48:56 +0000957
958 // Create and return a placeholder, which will later be RAUW'd.
Owen Andersone9f98042009-07-07 20:18:58 +0000959 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000960 ValuePtrs[Idx] = C;
Chris Lattner1663cca2007-04-24 05:48:56 +0000961 return C;
962}
963
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000964Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty,
965 OperatorConstraint OC) {
Filipe Cabecinhasbad07792015-04-30 00:52:42 +0000966 // Bail out for a clearly invalid value. This would make us call resize(0)
967 if (Idx == UINT_MAX)
968 return nullptr;
969
Chris Lattner2d8cd802009-03-31 22:55:09 +0000970 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000971 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000972
Chris Lattner2d8cd802009-03-31 22:55:09 +0000973 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhasb435d0f2015-04-28 20:18:47 +0000974 // If the types don't match, it's invalid.
975 if (Ty && Ty != V->getType())
976 return nullptr;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000977 if (!OC)
978 return V;
979 // Use dyn_cast to enforce operator constraints
980 switch (OC) {
981 case OC_CatchPad:
982 return dyn_cast<CatchPadInst>(V);
983 case OC_CleanupPad:
984 return dyn_cast<CleanupPadInst>(V);
985 default:
986 llvm_unreachable("Unexpected operator constraint");
987 }
Chris Lattner83930552007-05-01 07:01:57 +0000988 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000989
Chris Lattner1fc27f02007-05-02 05:16:49 +0000990 // No type specified, must be invalid reference.
Craig Topper2617dcc2014-04-15 06:32:26 +0000991 if (!Ty) return nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000992
Chris Lattner83930552007-05-01 07:01:57 +0000993 // Create and return a placeholder, which will later be RAUW'd.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000994 Value *V;
995 switch (OC) {
996 case OC_None:
997 V = new Argument(Ty);
998 break;
999 case OC_CatchPad: {
1000 BasicBlock *BB = BasicBlock::Create(Context);
1001 V = CatchPadInst::Create(BB, BB, {});
1002 break;
1003 }
1004 default:
1005 assert(OC == OC_CleanupPad && "unexpected operator constraint");
1006 V = CleanupPadInst::Create(Context, {});
1007 break;
1008 }
1009
Chris Lattner2d8cd802009-03-31 22:55:09 +00001010 ValuePtrs[Idx] = V;
Chris Lattner83930552007-05-01 07:01:57 +00001011 return V;
1012}
1013
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001014/// Once all constants are read, this method bulk resolves any forward
1015/// references. The idea behind this is that we sometimes get constants (such
1016/// as large arrays) which reference *many* forward ref constants. Replacing
1017/// each of these causes a lot of thrashing when building/reuniquing the
1018/// constant. Instead of doing this, we look at all the uses and rewrite all
1019/// the place holders at once for any constant that uses a placeholder.
1020void BitcodeReaderValueList::resolveConstantForwardRefs() {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001021 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattner74429932008-08-21 02:34:16 +00001022 // binary search.
1023 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001024
Chris Lattner74429932008-08-21 02:34:16 +00001025 SmallVector<Constant*, 64> NewOps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001026
Chris Lattner74429932008-08-21 02:34:16 +00001027 while (!ResolveConstants.empty()) {
Chris Lattner2d8cd802009-03-31 22:55:09 +00001028 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattner74429932008-08-21 02:34:16 +00001029 Constant *Placeholder = ResolveConstants.back().first;
1030 ResolveConstants.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001031
Chris Lattner74429932008-08-21 02:34:16 +00001032 // Loop over all users of the placeholder, updating them to reference the
1033 // new value. If they reference more than one placeholder, update them all
1034 // at once.
1035 while (!Placeholder->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001036 auto UI = Placeholder->user_begin();
Gabor Greif2c0ab482010-07-09 16:01:21 +00001037 User *U = *UI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001038
Chris Lattner74429932008-08-21 02:34:16 +00001039 // If the using object isn't uniqued, just update the operands. This
1040 // handles instructions and initializers for global variables.
Gabor Greif2c0ab482010-07-09 16:01:21 +00001041 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattner479c5d92008-08-21 17:31:45 +00001042 UI.getUse().set(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +00001043 continue;
1044 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001045
Chris Lattner74429932008-08-21 02:34:16 +00001046 // Otherwise, we have a constant that uses the placeholder. Replace that
1047 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greif2c0ab482010-07-09 16:01:21 +00001048 Constant *UserC = cast<Constant>(U);
Chris Lattner74429932008-08-21 02:34:16 +00001049 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
1050 I != E; ++I) {
1051 Value *NewOp;
1052 if (!isa<ConstantPlaceHolder>(*I)) {
1053 // Not a placeholder reference.
1054 NewOp = *I;
1055 } else if (*I == Placeholder) {
1056 // Common case is that it just references this one placeholder.
1057 NewOp = RealVal;
1058 } else {
1059 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001060 ResolveConstantsTy::iterator It =
1061 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattner74429932008-08-21 02:34:16 +00001062 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1063 0));
1064 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner2d8cd802009-03-31 22:55:09 +00001065 NewOp = operator[](It->second);
Chris Lattner74429932008-08-21 02:34:16 +00001066 }
1067
1068 NewOps.push_back(cast<Constant>(NewOp));
1069 }
1070
1071 // Make the new constant.
1072 Constant *NewC;
1073 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad83be3612011-06-22 09:24:39 +00001074 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001075 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnercc19efa2011-06-20 04:01:31 +00001076 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001077 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner69229312011-02-15 00:14:00 +00001078 NewC = ConstantVector::get(NewOps);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001079 } else {
1080 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foad5c984e562011-04-13 13:46:01 +00001081 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001082 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001083
Chris Lattner74429932008-08-21 02:34:16 +00001084 UserC->replaceAllUsesWith(NewC);
1085 UserC->destroyConstant();
1086 NewOps.clear();
1087 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001088
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001089 // Update all ValueHandles, they should be the only users at this point.
1090 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +00001091 delete Placeholder;
1092 }
1093}
1094
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001095void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +00001096 if (Idx == size()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001097 push_back(MD);
Devang Patel05eb6172009-08-04 06:00:18 +00001098 return;
1099 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001100
Devang Patel05eb6172009-08-04 06:00:18 +00001101 if (Idx >= size())
1102 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001103
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001104 TrackingMDRef &OldMD = MDValuePtrs[Idx];
1105 if (!OldMD) {
1106 OldMD.reset(MD);
Devang Patel05eb6172009-08-04 06:00:18 +00001107 return;
1108 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001109
Devang Patel05eb6172009-08-04 06:00:18 +00001110 // If there was a forward reference to this value, replace it.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +00001111 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001112 PrevMD->replaceAllUsesWith(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001113 --NumFwdRefs;
Devang Patel05eb6172009-08-04 06:00:18 +00001114}
1115
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001116Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +00001117 if (Idx >= size())
1118 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001119
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001120 if (Metadata *MD = MDValuePtrs[Idx])
1121 return MD;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001122
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001123 // Track forward refs to be resolved later.
1124 if (AnyFwdRefs) {
1125 MinFwdRef = std::min(MinFwdRef, Idx);
1126 MaxFwdRef = std::max(MaxFwdRef, Idx);
1127 } else {
1128 AnyFwdRefs = true;
1129 MinFwdRef = MaxFwdRef = Idx;
1130 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001131 ++NumFwdRefs;
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001132
1133 // Create and return a placeholder, which will later be RAUW'd.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +00001134 Metadata *MD = MDNode::getTemporary(Context, None).release();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001135 MDValuePtrs[Idx].reset(MD);
1136 return MD;
1137}
1138
1139void BitcodeReaderMDValueList::tryToResolveCycles() {
1140 if (!AnyFwdRefs)
1141 // Nothing to do.
1142 return;
1143
1144 if (NumFwdRefs)
1145 // Still forward references... can't resolve cycles.
1146 return;
1147
1148 // Resolve any cycles.
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001149 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1150 auto &MD = MDValuePtrs[I];
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +00001151 auto *N = dyn_cast_or_null<MDNode>(MD);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +00001152 if (!N)
1153 continue;
1154
1155 assert(!N->isTemporary() && "Unexpected forward reference");
1156 N->resolveCycles();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001157 }
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001158
1159 // Make sure we return early again until there's another forward ref.
1160 AnyFwdRefs = false;
Devang Patel05eb6172009-08-04 06:00:18 +00001161}
Chris Lattner1314b992007-04-22 06:23:29 +00001162
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001163Type *BitcodeReader::getTypeByID(unsigned ID) {
1164 // The type table size is always specified correctly.
1165 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +00001166 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +00001167
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001168 if (Type *Ty = TypeList[ID])
1169 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001170
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001171 // If we have a forward reference, the only possible case is when it is to a
1172 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001173 return TypeList[ID] = createIdentifiedStructType(Context);
1174}
1175
1176StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1177 StringRef Name) {
1178 auto *Ret = StructType::create(Context, Name);
1179 IdentifiedStructTypes.push_back(Ret);
1180 return Ret;
1181}
1182
1183StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1184 auto *Ret = StructType::create(Context);
1185 IdentifiedStructTypes.push_back(Ret);
1186 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +00001187}
1188
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001189
Chris Lattnerfee5a372007-05-04 03:30:17 +00001190//===----------------------------------------------------------------------===//
1191// Functions for parsing blocks from the bitcode file
1192//===----------------------------------------------------------------------===//
1193
Bill Wendling56aeccc2013-02-04 23:32:23 +00001194
1195/// \brief This fills an AttrBuilder object with the LLVM attributes that have
1196/// been decoded from the given integer. This function must stay in sync with
1197/// 'encodeLLVMAttributesForBitcode'.
1198static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1199 uint64_t EncodedAttrs) {
1200 // FIXME: Remove in 4.0.
1201
1202 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1203 // the bits above 31 down by 11 bits.
1204 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1205 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1206 "Alignment must be a power of two.");
1207
1208 if (Alignment)
1209 B.addAlignmentAttr(Alignment);
Kostya Serebryanyd688bab2013-02-11 08:13:54 +00001210 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
Bill Wendling56aeccc2013-02-04 23:32:23 +00001211 (EncodedAttrs & 0xffff));
1212}
1213
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001214std::error_code BitcodeReader::parseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001215 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001216 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001217
Devang Patela05633e2008-09-26 22:53:05 +00001218 if (!MAttributes.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001219 return error("Invalid multiple blocks");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001220
Chris Lattnerfee5a372007-05-04 03:30:17 +00001221 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001222
Bill Wendling71173cb2013-01-27 00:36:48 +00001223 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001224
Chris Lattnerfee5a372007-05-04 03:30:17 +00001225 // Read all the records.
1226 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001227 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001228
Chris Lattner27d38752013-01-20 02:13:19 +00001229 switch (Entry.Kind) {
1230 case BitstreamEntry::SubBlock: // Handled for us already.
1231 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001232 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001233 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001234 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001235 case BitstreamEntry::Record:
1236 // The interesting case.
1237 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001238 }
Joe Abbey97b7a172013-02-06 22:14:06 +00001239
Chris Lattnerfee5a372007-05-04 03:30:17 +00001240 // Read a record.
1241 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001242 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +00001243 default: // Default behavior: ignore.
1244 break;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001245 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1246 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +00001247 if (Record.size() & 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001248 return error("Invalid record");
Chris Lattnerfee5a372007-05-04 03:30:17 +00001249
Chris Lattnerfee5a372007-05-04 03:30:17 +00001250 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +00001251 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001252 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling60011b82013-01-29 01:43:29 +00001253 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +00001254 }
Devang Patela05633e2008-09-26 22:53:05 +00001255
Bill Wendlinge94d8432012-12-07 23:16:57 +00001256 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +00001257 Attrs.clear();
1258 break;
1259 }
Bill Wendling0dc08912013-02-12 08:13:50 +00001260 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1261 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1262 Attrs.push_back(MAttributeGroups[Record[i]]);
1263
1264 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1265 Attrs.clear();
1266 break;
1267 }
Duncan Sands04eb67e2007-11-20 14:09:29 +00001268 }
Chris Lattnerfee5a372007-05-04 03:30:17 +00001269 }
1270}
1271
Reid Klecknere9f36af2013-11-12 01:31:00 +00001272// Returns Attribute::None on unrecognized codes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001273static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
Reid Klecknere9f36af2013-11-12 01:31:00 +00001274 switch (Code) {
1275 default:
1276 return Attribute::None;
1277 case bitc::ATTR_KIND_ALIGNMENT:
1278 return Attribute::Alignment;
1279 case bitc::ATTR_KIND_ALWAYS_INLINE:
1280 return Attribute::AlwaysInline;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001281 case bitc::ATTR_KIND_ARGMEMONLY:
1282 return Attribute::ArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001283 case bitc::ATTR_KIND_BUILTIN:
1284 return Attribute::Builtin;
1285 case bitc::ATTR_KIND_BY_VAL:
1286 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +00001287 case bitc::ATTR_KIND_IN_ALLOCA:
1288 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001289 case bitc::ATTR_KIND_COLD:
1290 return Attribute::Cold;
Owen Anderson85fa7d52015-05-26 23:48:40 +00001291 case bitc::ATTR_KIND_CONVERGENT:
1292 return Attribute::Convergent;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001293 case bitc::ATTR_KIND_INLINE_HINT:
1294 return Attribute::InlineHint;
1295 case bitc::ATTR_KIND_IN_REG:
1296 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +00001297 case bitc::ATTR_KIND_JUMP_TABLE:
1298 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001299 case bitc::ATTR_KIND_MIN_SIZE:
1300 return Attribute::MinSize;
1301 case bitc::ATTR_KIND_NAKED:
1302 return Attribute::Naked;
1303 case bitc::ATTR_KIND_NEST:
1304 return Attribute::Nest;
1305 case bitc::ATTR_KIND_NO_ALIAS:
1306 return Attribute::NoAlias;
1307 case bitc::ATTR_KIND_NO_BUILTIN:
1308 return Attribute::NoBuiltin;
1309 case bitc::ATTR_KIND_NO_CAPTURE:
1310 return Attribute::NoCapture;
1311 case bitc::ATTR_KIND_NO_DUPLICATE:
1312 return Attribute::NoDuplicate;
1313 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1314 return Attribute::NoImplicitFloat;
1315 case bitc::ATTR_KIND_NO_INLINE:
1316 return Attribute::NoInline;
James Molloye6f87ca2015-11-06 10:32:53 +00001317 case bitc::ATTR_KIND_NO_RECURSE:
1318 return Attribute::NoRecurse;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001319 case bitc::ATTR_KIND_NON_LAZY_BIND:
1320 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001321 case bitc::ATTR_KIND_NON_NULL:
1322 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001323 case bitc::ATTR_KIND_DEREFERENCEABLE:
1324 return Attribute::Dereferenceable;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001325 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1326 return Attribute::DereferenceableOrNull;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001327 case bitc::ATTR_KIND_NO_RED_ZONE:
1328 return Attribute::NoRedZone;
1329 case bitc::ATTR_KIND_NO_RETURN:
1330 return Attribute::NoReturn;
1331 case bitc::ATTR_KIND_NO_UNWIND:
1332 return Attribute::NoUnwind;
1333 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1334 return Attribute::OptimizeForSize;
1335 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1336 return Attribute::OptimizeNone;
1337 case bitc::ATTR_KIND_READ_NONE:
1338 return Attribute::ReadNone;
1339 case bitc::ATTR_KIND_READ_ONLY:
1340 return Attribute::ReadOnly;
1341 case bitc::ATTR_KIND_RETURNED:
1342 return Attribute::Returned;
1343 case bitc::ATTR_KIND_RETURNS_TWICE:
1344 return Attribute::ReturnsTwice;
1345 case bitc::ATTR_KIND_S_EXT:
1346 return Attribute::SExt;
1347 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1348 return Attribute::StackAlignment;
1349 case bitc::ATTR_KIND_STACK_PROTECT:
1350 return Attribute::StackProtect;
1351 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1352 return Attribute::StackProtectReq;
1353 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1354 return Attribute::StackProtectStrong;
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001355 case bitc::ATTR_KIND_SAFESTACK:
1356 return Attribute::SafeStack;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001357 case bitc::ATTR_KIND_STRUCT_RET:
1358 return Attribute::StructRet;
1359 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1360 return Attribute::SanitizeAddress;
1361 case bitc::ATTR_KIND_SANITIZE_THREAD:
1362 return Attribute::SanitizeThread;
1363 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1364 return Attribute::SanitizeMemory;
1365 case bitc::ATTR_KIND_UW_TABLE:
1366 return Attribute::UWTable;
1367 case bitc::ATTR_KIND_Z_EXT:
1368 return Attribute::ZExt;
1369 }
1370}
1371
JF Bastien30bf96b2015-02-22 19:32:03 +00001372std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1373 unsigned &Alignment) {
1374 // Note: Alignment in bitcode files is incremented by 1, so that zero
1375 // can be used for default alignment.
1376 if (Exponent > Value::MaxAlignmentExponent + 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001377 return error("Invalid alignment value");
JF Bastien30bf96b2015-02-22 19:32:03 +00001378 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1379 return std::error_code();
1380}
1381
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001382std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001383 Attribute::AttrKind *Kind) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001384 *Kind = getAttrFromCode(Code);
Reid Klecknere9f36af2013-11-12 01:31:00 +00001385 if (*Kind == Attribute::None)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001386 return error(BitcodeError::CorruptedBitcode,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001387 "Unknown attribute kind (" + Twine(Code) + ")");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001388 return std::error_code();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001389}
1390
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001391std::error_code BitcodeReader::parseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +00001392 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001393 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001394
1395 if (!MAttributeGroups.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001396 return error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +00001397
1398 SmallVector<uint64_t, 64> Record;
1399
1400 // Read all the records.
1401 while (1) {
1402 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1403
1404 switch (Entry.Kind) {
1405 case BitstreamEntry::SubBlock: // Handled for us already.
1406 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001407 return error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +00001408 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001409 return std::error_code();
Bill Wendlingba629332013-02-10 23:24:25 +00001410 case BitstreamEntry::Record:
1411 // The interesting case.
1412 break;
1413 }
1414
1415 // Read a record.
1416 Record.clear();
1417 switch (Stream.readRecord(Entry.ID, Record)) {
1418 default: // Default behavior: ignore.
1419 break;
1420 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1421 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001422 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001423
Bill Wendlinge46707e2013-02-11 22:32:29 +00001424 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +00001425 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1426
1427 AttrBuilder B;
1428 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1429 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001430 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001431 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001432 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001433
1434 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +00001435 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001436 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001437 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001438 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001439 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001440 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001441 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001442 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001443 else if (Kind == Attribute::Dereferenceable)
1444 B.addDereferenceableAttr(Record[++i]);
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001445 else if (Kind == Attribute::DereferenceableOrNull)
1446 B.addDereferenceableOrNullAttr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +00001447 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +00001448 assert((Record[i] == 3 || Record[i] == 4) &&
1449 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +00001450 bool HasValue = (Record[i++] == 4);
1451 SmallString<64> KindStr;
1452 SmallString<64> ValStr;
1453
1454 while (Record[i] != 0 && i != e)
1455 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001456 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001457
1458 if (HasValue) {
1459 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +00001460 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +00001461 while (Record[i] != 0 && i != e)
1462 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001463 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001464 }
1465
1466 B.addAttribute(KindStr.str(), ValStr.str());
1467 }
1468 }
1469
Bill Wendlinge46707e2013-02-11 22:32:29 +00001470 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +00001471 break;
1472 }
1473 }
1474 }
1475}
1476
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001477std::error_code BitcodeReader::parseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001478 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001479 return error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +00001480
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001481 return parseTypeTableBody();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001482}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001483
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001484std::error_code BitcodeReader::parseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +00001485 if (!TypeList.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001486 return error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +00001487
1488 SmallVector<uint64_t, 64> Record;
1489 unsigned NumRecords = 0;
1490
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001491 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +00001492
Chris Lattner1314b992007-04-22 06:23:29 +00001493 // Read all the records for this type table.
1494 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001495 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001496
Chris Lattner27d38752013-01-20 02:13:19 +00001497 switch (Entry.Kind) {
1498 case BitstreamEntry::SubBlock: // Handled for us already.
1499 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001500 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001501 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +00001502 if (NumRecords != TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001503 return error("Malformed block");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001504 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001505 case BitstreamEntry::Record:
1506 // The interesting case.
1507 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001508 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001509
Chris Lattner1314b992007-04-22 06:23:29 +00001510 // Read a record.
1511 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001512 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001513 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001514 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001515 return error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +00001516 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1517 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1518 // type list. This allows us to reserve space.
1519 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001520 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001521 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001522 continue;
Chris Lattner1314b992007-04-22 06:23:29 +00001523 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +00001524 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001525 break;
Dan Gohman518cda42011-12-17 00:04:22 +00001526 case bitc::TYPE_CODE_HALF: // HALF
1527 ResultTy = Type::getHalfTy(Context);
1528 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001529 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +00001530 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001531 break;
1532 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +00001533 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001534 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001535 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +00001536 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001537 break;
1538 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001539 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001540 break;
1541 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001542 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001543 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001544 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +00001545 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001546 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001547 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +00001548 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001549 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +00001550 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1551 ResultTy = Type::getX86_MMXTy(Context);
1552 break;
David Majnemerb611e3f2015-08-14 05:09:07 +00001553 case bitc::TYPE_CODE_TOKEN: // TOKEN
1554 ResultTy = Type::getTokenTy(Context);
1555 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001556 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
Chris Lattner1314b992007-04-22 06:23:29 +00001557 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001558 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001559
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001560 uint64_t NumBits = Record[0];
1561 if (NumBits < IntegerType::MIN_INT_BITS ||
1562 NumBits > IntegerType::MAX_INT_BITS)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001563 return error("Bitwidth for integer type out of range");
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001564 ResultTy = IntegerType::get(Context, NumBits);
Chris Lattner1314b992007-04-22 06:23:29 +00001565 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001566 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001567 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001568 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +00001569 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001570 return error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001571 unsigned AddressSpace = 0;
1572 if (Record.size() == 2)
1573 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001574 ResultTy = getTypeByID(Record[0]);
Filipe Cabecinhasd8a1bcd2015-04-29 02:27:28 +00001575 if (!ResultTy ||
1576 !PointerType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001577 return error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001578 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +00001579 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001580 }
Nuno Lopes561dae02012-05-23 15:19:39 +00001581 case bitc::TYPE_CODE_FUNCTION_OLD: {
1582 // FIXME: attrid is dead, remove it in LLVM 4.0
1583 // FUNCTION: [vararg, attrid, retty, paramty x N]
1584 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001585 return error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +00001586 SmallVector<Type*, 8> ArgTys;
1587 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1588 if (Type *T = getTypeByID(Record[i]))
1589 ArgTys.push_back(T);
1590 else
1591 break;
1592 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001593
Nuno Lopes561dae02012-05-23 15:19:39 +00001594 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001595 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001596 return error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +00001597
1598 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1599 break;
1600 }
Chad Rosier95898722011-11-03 00:14:01 +00001601 case bitc::TYPE_CODE_FUNCTION: {
1602 // FUNCTION: [vararg, retty, paramty x N]
1603 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001604 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001605 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +00001606 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001607 if (Type *T = getTypeByID(Record[i])) {
1608 if (!FunctionType::isValidArgumentType(T))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001609 return error("Invalid function argument type");
Chad Rosier95898722011-11-03 00:14:01 +00001610 ArgTys.push_back(T);
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001611 }
Chad Rosier95898722011-11-03 00:14:01 +00001612 else
1613 break;
1614 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001615
Chad Rosier95898722011-11-03 00:14:01 +00001616 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001617 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001618 return error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +00001619
1620 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1621 break;
1622 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001623 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +00001624 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001625 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001626 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001627 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1628 if (Type *T = getTypeByID(Record[i]))
1629 EltTys.push_back(T);
1630 else
1631 break;
1632 }
1633 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001634 return error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001635 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001636 break;
1637 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001638 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001639 if (convertToString(Record, 0, TypeName))
1640 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001641 continue;
1642
1643 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1644 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001645 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001646
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001647 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001648 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001649
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001650 // Check to see if this was forward referenced, if so fill in the temp.
1651 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1652 if (Res) {
1653 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001654 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001655 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001656 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001657 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001658
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001659 SmallVector<Type*, 8> EltTys;
1660 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1661 if (Type *T = getTypeByID(Record[i]))
1662 EltTys.push_back(T);
1663 else
1664 break;
1665 }
1666 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001667 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001668 Res->setBody(EltTys, Record[0]);
1669 ResultTy = Res;
1670 break;
1671 }
1672 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1673 if (Record.size() != 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001674 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001675
1676 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001677 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001678
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001679 // Check to see if this was forward referenced, if so fill in the temp.
1680 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1681 if (Res) {
1682 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001683 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001684 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001685 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001686 TypeName.clear();
1687 ResultTy = Res;
1688 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001689 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001690 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1691 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001692 return error("Invalid record");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001693 ResultTy = getTypeByID(Record[1]);
1694 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001695 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001696 ResultTy = ArrayType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001697 break;
1698 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1699 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001700 return error("Invalid record");
Filipe Cabecinhas8e421902015-06-03 00:05:30 +00001701 if (Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001702 return error("Invalid vector length");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001703 ResultTy = getTypeByID(Record[1]);
1704 if (!ResultTy || !StructType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001705 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001706 ResultTy = VectorType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001707 break;
1708 }
1709
1710 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001711 return error("Invalid TYPE table");
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001712 if (TypeList[NumRecords])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001713 return error(
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001714 "Invalid TYPE table: Only named structs can be forward referenced");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001715 assert(ResultTy && "Didn't read a type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001716 TypeList[NumRecords++] = ResultTy;
1717 }
1718}
1719
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001720std::error_code BitcodeReader::parseOperandBundleTags() {
1721 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1722 return error("Invalid record");
1723
1724 if (!BundleTags.empty())
1725 return error("Invalid multiple blocks");
1726
1727 SmallVector<uint64_t, 64> Record;
1728
1729 while (1) {
1730 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1731
1732 switch (Entry.Kind) {
1733 case BitstreamEntry::SubBlock: // Handled for us already.
1734 case BitstreamEntry::Error:
1735 return error("Malformed block");
1736 case BitstreamEntry::EndBlock:
1737 return std::error_code();
1738 case BitstreamEntry::Record:
1739 // The interesting case.
1740 break;
1741 }
1742
1743 // Tags are implicitly mapped to integers by their order.
1744
1745 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1746 return error("Invalid record");
1747
1748 // OPERAND_BUNDLE_TAG: [strchr x N]
1749 BundleTags.emplace_back();
1750 if (convertToString(Record, 0, BundleTags.back()))
1751 return error("Invalid record");
1752 Record.clear();
1753 }
1754}
1755
Teresa Johnsonff642b92015-09-17 20:12:00 +00001756/// Associate a value with its name from the given index in the provided record.
1757ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1758 unsigned NameIndex, Triple &TT) {
1759 SmallString<128> ValueName;
1760 if (convertToString(Record, NameIndex, ValueName))
1761 return error("Invalid record");
1762 unsigned ValueID = Record[0];
1763 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1764 return error("Invalid record");
1765 Value *V = ValueList[ValueID];
1766
Filipe Cabecinhasa2b0ac42015-11-04 14:53:36 +00001767 StringRef NameStr(ValueName.data(), ValueName.size());
1768 if (NameStr.find_first_of(0) != StringRef::npos)
1769 return error("Invalid value name");
1770 V->setName(NameStr);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001771 auto *GO = dyn_cast<GlobalObject>(V);
1772 if (GO) {
1773 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1774 if (TT.isOSBinFormatMachO())
1775 GO->setComdat(nullptr);
1776 else
1777 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1778 }
1779 }
1780 return V;
1781}
1782
1783/// Parse the value symbol table at either the current parsing location or
1784/// at the given bit offset if provided.
Peter Collingbourne128a9762015-10-27 23:01:25 +00001785std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001786 uint64_t CurrentBit;
1787 // Pass in the Offset to distinguish between calling for the module-level
1788 // VST (where we want to jump to the VST offset) and the function-level
1789 // VST (where we don't).
1790 if (Offset > 0) {
1791 // Save the current parsing location so we can jump back at the end
1792 // of the VST read.
1793 CurrentBit = Stream.GetCurrentBitNo();
1794 Stream.JumpToBit(Offset * 32);
1795#ifndef NDEBUG
1796 // Do some checking if we are in debug mode.
1797 BitstreamEntry Entry = Stream.advance();
1798 assert(Entry.Kind == BitstreamEntry::SubBlock);
1799 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1800#else
1801 // In NDEBUG mode ignore the output so we don't get an unused variable
1802 // warning.
1803 Stream.advance();
1804#endif
1805 }
1806
1807 // Compute the delta between the bitcode indices in the VST (the word offset
1808 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1809 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1810 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1811 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1812 // just before entering the VST subblock because: 1) the EnterSubBlock
1813 // changes the AbbrevID width; 2) the VST block is nested within the same
1814 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1815 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1816 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1817 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1818 unsigned FuncBitcodeOffsetDelta =
1819 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1820
Chris Lattner982ec1e2007-05-05 00:17:00 +00001821 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001822 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001823
1824 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001825
David Majnemer3087b222015-01-20 05:58:07 +00001826 Triple TT(TheModule->getTargetTriple());
1827
Chris Lattnerccaa4482007-04-23 21:26:05 +00001828 // Read all the records for this value table.
1829 SmallString<128> ValueName;
1830 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001831 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001832
Chris Lattner27d38752013-01-20 02:13:19 +00001833 switch (Entry.Kind) {
1834 case BitstreamEntry::SubBlock: // Handled for us already.
1835 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001836 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001837 case BitstreamEntry::EndBlock:
Teresa Johnsonff642b92015-09-17 20:12:00 +00001838 if (Offset > 0)
1839 Stream.JumpToBit(CurrentBit);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001840 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001841 case BitstreamEntry::Record:
1842 // The interesting case.
1843 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001844 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001845
Chris Lattnerccaa4482007-04-23 21:26:05 +00001846 // Read a record.
1847 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001848 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001849 default: // Default behavior: unknown type.
1850 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00001851 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Teresa Johnsonff642b92015-09-17 20:12:00 +00001852 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1853 if (std::error_code EC = ValOrErr.getError())
1854 return EC;
1855 ValOrErr.get();
1856 break;
1857 }
1858 case bitc::VST_CODE_FNENTRY: {
1859 // VST_FNENTRY: [valueid, offset, namechar x N]
1860 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1861 if (std::error_code EC = ValOrErr.getError())
1862 return EC;
1863 Value *V = ValOrErr.get();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001864
Teresa Johnsonff642b92015-09-17 20:12:00 +00001865 auto *GO = dyn_cast<GlobalObject>(V);
1866 if (!GO) {
1867 // If this is an alias, need to get the actual Function object
1868 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1869 auto *GA = dyn_cast<GlobalAlias>(V);
1870 if (GA)
1871 GO = GA->getBaseObject();
1872 assert(GO);
Rafael Espindola12ca34f2015-01-19 15:16:06 +00001873 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001874
1875 uint64_t FuncWordOffset = Record[1];
1876 Function *F = dyn_cast<Function>(GO);
1877 assert(F);
1878 uint64_t FuncBitOffset = FuncWordOffset * 32;
1879 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
Teresa Johnson1493ad92015-10-10 14:18:36 +00001880 // Set the LastFunctionBlockBit to point to the last function block.
Teresa Johnsonff642b92015-09-17 20:12:00 +00001881 // Later when parsing is resumed after function materialization,
1882 // we can simply skip that last function block.
Teresa Johnson1493ad92015-10-10 14:18:36 +00001883 if (FuncBitOffset > LastFunctionBlockBit)
1884 LastFunctionBlockBit = FuncBitOffset;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001885 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00001886 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00001887 case bitc::VST_CODE_BBENTRY: {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001888 if (convertToString(Record, 1, ValueName))
1889 return error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00001890 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001891 if (!BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001892 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001893
Daniel Dunbard786b512009-07-26 00:34:27 +00001894 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00001895 ValueName.clear();
1896 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001897 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00001898 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001899 }
1900}
1901
Teresa Johnson12545072015-11-15 02:00:09 +00001902/// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1903std::error_code
1904BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
1905 if (Record.size() < 2)
1906 return error("Invalid record");
1907
1908 unsigned Kind = Record[0];
1909 SmallString<8> Name(Record.begin() + 1, Record.end());
1910
1911 unsigned NewKind = TheModule->getMDKindID(Name.str());
1912 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1913 return error("Conflicting METADATA_KIND records");
1914 return std::error_code();
1915}
1916
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001917static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1918
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00001919/// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
1920/// module level metadata.
1921std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00001922 IsMetadataMaterialized = true;
Devang Patel89923232010-01-11 18:52:33 +00001923 unsigned NextMDValueNo = MDValueList.size();
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00001924 if (ModuleLevel && SeenModuleValuesRecord) {
1925 // Now that we are parsing the module level metadata, we want to restart
1926 // the numbering of the MD values, and replace temp MD created earlier
1927 // with their real values. If we saw a METADATA_VALUE record then we
1928 // would have set the MDValueList size to the number specified in that
1929 // record, to support parsing function-level metadata first, and we need
1930 // to reset back to 0 to fill the MDValueList in with the parsed module
1931 // The function-level metadata parsing should have reset the MDValueList
1932 // size back to the value reported by the METADATA_VALUE record, saved in
1933 // NumModuleMDs.
1934 assert(NumModuleMDs == MDValueList.size() &&
1935 "Expected MDValueList to only contain module level values");
1936 NextMDValueNo = 0;
1937 }
Devang Patel7428d8a2009-07-22 17:43:22 +00001938
1939 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001940 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001941
Devang Patel7428d8a2009-07-22 17:43:22 +00001942 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001943
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001944 auto getMD =
1945 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1946 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1947 if (ID)
1948 return getMD(ID - 1);
1949 return nullptr;
1950 };
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001951 auto getMDString = [&](unsigned ID) -> MDString *{
1952 // This requires that the ID is not really a forward reference. In
1953 // particular, the MDString must already have been resolved.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001954 return cast_or_null<MDString>(getMDOrNull(ID));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001955 };
1956
1957#define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1958 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1959
Devang Patel7428d8a2009-07-22 17:43:22 +00001960 // Read all the records.
1961 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001962 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001963
Chris Lattner27d38752013-01-20 02:13:19 +00001964 switch (Entry.Kind) {
1965 case BitstreamEntry::SubBlock: // Handled for us already.
1966 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001967 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001968 case BitstreamEntry::EndBlock:
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001969 MDValueList.tryToResolveCycles();
Teresa Johnson16e2a9e2015-11-21 03:51:23 +00001970 assert((!(ModuleLevel && SeenModuleValuesRecord) ||
1971 NumModuleMDs == MDValueList.size()) &&
1972 "Inconsistent bitcode: METADATA_VALUES mismatch");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001973 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001974 case BitstreamEntry::Record:
1975 // The interesting case.
1976 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00001977 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001978
Devang Patel7428d8a2009-07-22 17:43:22 +00001979 // Read a record.
1980 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001981 unsigned Code = Stream.readRecord(Entry.ID, Record);
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001982 bool IsDistinct = false;
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00001983 switch (Code) {
Devang Patel7428d8a2009-07-22 17:43:22 +00001984 default: // Default behavior: ignore.
1985 break;
Devang Patel27c87ff2009-07-29 22:34:41 +00001986 case bitc::METADATA_NAME: {
Chris Lattner8d140532013-01-20 02:54:05 +00001987 // Read name of the named metadata.
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001988 SmallString<8> Name(Record.begin(), Record.end());
Devang Patel27c87ff2009-07-29 22:34:41 +00001989 Record.clear();
1990 Code = Stream.ReadCode();
1991
Chris Lattner27d38752013-01-20 02:13:19 +00001992 unsigned NextBitCode = Stream.readRecord(Code, Record);
Filipe Cabecinhas14e68672015-05-30 00:17:20 +00001993 if (NextBitCode != bitc::METADATA_NAMED_NODE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001994 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
Devang Patel27c87ff2009-07-29 22:34:41 +00001995
1996 // Read named metadata elements.
1997 unsigned Size = Record.size();
Dan Gohman2637cc12010-07-21 23:38:33 +00001998 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patel27c87ff2009-07-29 22:34:41 +00001999 for (unsigned i = 0; i != Size; ++i) {
Karthik Bhat82540e92014-03-27 12:08:23 +00002000 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002001 if (!MD)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002002 return error("Invalid record");
Dan Gohman2637cc12010-07-21 23:38:33 +00002003 NMD->addOperand(MD);
Devang Patel27c87ff2009-07-29 22:34:41 +00002004 }
Devang Patel27c87ff2009-07-29 22:34:41 +00002005 break;
2006 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00002007 case bitc::METADATA_OLD_FN_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00002008 // FIXME: Remove in 4.0.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002009 // This is a LocalAsMetadata record, the only type of function-local
2010 // metadata.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002011 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002012 return error("Invalid record");
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002013
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002014 // If this isn't a LocalAsMetadata record, we're dropping it. This used
2015 // to be legal, but there's no upgrade path.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002016 auto dropRecord = [&] {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002017 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002018 };
2019 if (Record.size() != 2) {
2020 dropRecord();
2021 break;
2022 }
2023
2024 Type *Ty = getTypeByID(Record[0]);
2025 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
2026 dropRecord();
2027 break;
2028 }
2029
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002030 MDValueList.assignValue(
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002031 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2032 NextMDValueNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002033 break;
2034 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00002035 case bitc::METADATA_OLD_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00002036 // FIXME: Remove in 4.0.
Dan Gohman1e0213a2010-07-13 19:33:27 +00002037 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002038 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002039
Devang Patele059ba6e2009-07-23 01:07:34 +00002040 unsigned Size = Record.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002041 SmallVector<Metadata *, 8> Elts;
Devang Patele059ba6e2009-07-23 01:07:34 +00002042 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00002043 Type *Ty = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002044 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002045 return error("Invalid record");
Chris Lattnerfdd87902009-10-05 05:54:46 +00002046 if (Ty->isMetadataTy())
Devang Patel05eb6172009-08-04 06:00:18 +00002047 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002048 else if (!Ty->isVoidTy()) {
2049 auto *MD =
2050 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2051 assert(isa<ConstantAsMetadata>(MD) &&
2052 "Expected non-function-local metadata");
2053 Elts.push_back(MD);
2054 } else
Craig Topper2617dcc2014-04-15 06:32:26 +00002055 Elts.push_back(nullptr);
Devang Patele059ba6e2009-07-23 01:07:34 +00002056 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002057 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
Devang Patele059ba6e2009-07-23 01:07:34 +00002058 break;
2059 }
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002060 case bitc::METADATA_VALUE: {
2061 if (Record.size() != 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002062 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002063
2064 Type *Ty = getTypeByID(Record[0]);
2065 if (Ty->isMetadataTy() || Ty->isVoidTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002066 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002067
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002068 MDValueList.assignValue(
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002069 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
2070 NextMDValueNo++);
2071 break;
2072 }
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00002073 case bitc::METADATA_DISTINCT_NODE:
2074 IsDistinct = true;
2075 // fallthrough...
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002076 case bitc::METADATA_NODE: {
2077 SmallVector<Metadata *, 8> Elts;
2078 Elts.reserve(Record.size());
2079 for (unsigned ID : Record)
2080 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002081 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00002082 : MDNode::get(Context, Elts),
2083 NextMDValueNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002084 break;
2085 }
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002086 case bitc::METADATA_LOCATION: {
2087 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002088 return error("Invalid record");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002089
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002090 unsigned Line = Record[1];
2091 unsigned Column = Record[2];
2092 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
2093 Metadata *InlinedAt =
2094 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002095 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002096 GET_OR_DISTINCT(DILocation, Record[0],
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00002097 (Context, Line, Column, Scope, InlinedAt)),
2098 NextMDValueNo++);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002099 break;
2100 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002101 case bitc::METADATA_GENERIC_DEBUG: {
2102 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002103 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002104
2105 unsigned Tag = Record[1];
2106 unsigned Version = Record[2];
2107
2108 if (Tag >= 1u << 16 || Version != 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002109 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002110
2111 auto *Header = getMDString(Record[3]);
2112 SmallVector<Metadata *, 8> DwarfOps;
2113 for (unsigned I = 4, E = Record.size(); I != E; ++I)
2114 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
2115 : nullptr);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002116 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002117 (Context, Tag, Header, DwarfOps)),
2118 NextMDValueNo++);
2119 break;
2120 }
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002121 case bitc::METADATA_SUBRANGE: {
2122 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002123 return error("Invalid record");
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002124
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002125 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002126 GET_OR_DISTINCT(DISubrange, Record[0],
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002127 (Context, Record[1], unrotateSign(Record[2]))),
2128 NextMDValueNo++);
2129 break;
2130 }
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002131 case bitc::METADATA_ENUMERATOR: {
2132 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002133 return error("Invalid record");
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002134
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002135 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002136 (Context, unrotateSign(Record[1]),
2137 getMDString(Record[2]))),
2138 NextMDValueNo++);
2139 break;
2140 }
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002141 case bitc::METADATA_BASIC_TYPE: {
2142 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002143 return error("Invalid record");
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002144
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002145 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002146 GET_OR_DISTINCT(DIBasicType, Record[0],
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002147 (Context, Record[1], getMDString(Record[2]),
2148 Record[3], Record[4], Record[5])),
2149 NextMDValueNo++);
2150 break;
2151 }
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002152 case bitc::METADATA_DERIVED_TYPE: {
2153 if (Record.size() != 12)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002154 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002155
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002156 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002157 GET_OR_DISTINCT(DIDerivedType, Record[0],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002158 (Context, Record[1], getMDString(Record[2]),
2159 getMDOrNull(Record[3]), Record[4],
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00002160 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2161 Record[7], Record[8], Record[9], Record[10],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002162 getMDOrNull(Record[11]))),
2163 NextMDValueNo++);
2164 break;
2165 }
2166 case bitc::METADATA_COMPOSITE_TYPE: {
2167 if (Record.size() != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002168 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002169
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002170 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002171 GET_OR_DISTINCT(DICompositeType, Record[0],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002172 (Context, Record[1], getMDString(Record[2]),
2173 getMDOrNull(Record[3]), Record[4],
2174 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2175 Record[7], Record[8], Record[9], Record[10],
2176 getMDOrNull(Record[11]), Record[12],
2177 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2178 getMDString(Record[15]))),
2179 NextMDValueNo++);
2180 break;
2181 }
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002182 case bitc::METADATA_SUBROUTINE_TYPE: {
2183 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002184 return error("Invalid record");
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002185
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002186 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002187 GET_OR_DISTINCT(DISubroutineType, Record[0],
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002188 (Context, Record[1], getMDOrNull(Record[2]))),
2189 NextMDValueNo++);
2190 break;
2191 }
Adrian Prantlab1243f2015-06-29 23:03:47 +00002192
2193 case bitc::METADATA_MODULE: {
2194 if (Record.size() != 6)
2195 return error("Invalid record");
2196
2197 MDValueList.assignValue(
2198 GET_OR_DISTINCT(DIModule, Record[0],
2199 (Context, getMDOrNull(Record[1]),
2200 getMDString(Record[2]), getMDString(Record[3]),
2201 getMDString(Record[4]), getMDString(Record[5]))),
2202 NextMDValueNo++);
2203 break;
2204 }
2205
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002206 case bitc::METADATA_FILE: {
2207 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002208 return error("Invalid record");
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002209
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002210 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002211 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002212 getMDString(Record[2]))),
2213 NextMDValueNo++);
2214 break;
2215 }
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002216 case bitc::METADATA_COMPILE_UNIT: {
Adrian Prantl1f599f92015-05-21 20:37:30 +00002217 if (Record.size() < 14 || Record.size() > 15)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002218 return error("Invalid record");
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002219
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00002220 // Ignore Record[1], which indicates whether this compile unit is
2221 // distinct. It's always distinct.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002222 MDValueList.assignValue(
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00002223 DICompileUnit::getDistinct(
2224 Context, Record[1], getMDOrNull(Record[2]),
2225 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2226 Record[6], getMDString(Record[7]), Record[8],
2227 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2228 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
2229 getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14]),
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002230 NextMDValueNo++);
2231 break;
2232 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002233 case bitc::METADATA_SUBPROGRAM: {
Peter Collingbourned4bff302015-11-05 22:03:56 +00002234 if (Record.size() != 18 && Record.size() != 19)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002235 return error("Invalid record");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002236
Peter Collingbourned4bff302015-11-05 22:03:56 +00002237 bool HasFn = Record.size() == 19;
2238 DISubprogram *SP = GET_OR_DISTINCT(
2239 DISubprogram,
2240 Record[0] || Record[8], // All definitions should be distinct.
2241 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2242 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2243 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2244 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2245 Record[14], getMDOrNull(Record[15 + HasFn]),
2246 getMDOrNull(Record[16 + HasFn]), getMDOrNull(Record[17 + HasFn])));
2247 MDValueList.assignValue(SP, NextMDValueNo++);
2248
2249 // Upgrade sp->function mapping to function->sp mapping.
2250 if (HasFn && Record[15]) {
2251 if (auto *CMD = dyn_cast<ConstantAsMetadata>(getMDOrNull(Record[15])))
2252 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2253 if (F->isMaterializable())
2254 // Defer until materialized; unmaterialized functions may not have
2255 // metadata.
2256 FunctionsWithSPs[F] = SP;
2257 else if (!F->empty())
2258 F->setSubprogram(SP);
2259 }
2260 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002261 break;
2262 }
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002263 case bitc::METADATA_LEXICAL_BLOCK: {
2264 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002265 return error("Invalid record");
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002266
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002267 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002268 GET_OR_DISTINCT(DILexicalBlock, Record[0],
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002269 (Context, getMDOrNull(Record[1]),
2270 getMDOrNull(Record[2]), Record[3], Record[4])),
2271 NextMDValueNo++);
2272 break;
2273 }
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002274 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2275 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002276 return error("Invalid record");
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002277
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002278 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002279 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002280 (Context, getMDOrNull(Record[1]),
2281 getMDOrNull(Record[2]), Record[3])),
2282 NextMDValueNo++);
2283 break;
2284 }
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002285 case bitc::METADATA_NAMESPACE: {
2286 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002287 return error("Invalid record");
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002288
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002289 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002290 GET_OR_DISTINCT(DINamespace, Record[0],
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002291 (Context, getMDOrNull(Record[1]),
2292 getMDOrNull(Record[2]), getMDString(Record[3]),
2293 Record[4])),
2294 NextMDValueNo++);
2295 break;
2296 }
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002297 case bitc::METADATA_TEMPLATE_TYPE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002298 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002299 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002300
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002301 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002302 Record[0],
2303 (Context, getMDString(Record[1]),
2304 getMDOrNull(Record[2]))),
2305 NextMDValueNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002306 break;
2307 }
2308 case bitc::METADATA_TEMPLATE_VALUE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002309 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002310 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002311
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002312 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002313 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002314 (Context, Record[1], getMDString(Record[2]),
2315 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002316 NextMDValueNo++);
2317 break;
2318 }
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002319 case bitc::METADATA_GLOBAL_VAR: {
2320 if (Record.size() != 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002321 return error("Invalid record");
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002322
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002323 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002324 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002325 (Context, getMDOrNull(Record[1]),
2326 getMDString(Record[2]), getMDString(Record[3]),
2327 getMDOrNull(Record[4]), Record[5],
2328 getMDOrNull(Record[6]), Record[7], Record[8],
2329 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2330 NextMDValueNo++);
2331 break;
2332 }
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002333 case bitc::METADATA_LOCAL_VAR: {
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00002334 // 10th field is for the obseleted 'inlinedAt:' field.
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002335 if (Record.size() < 8 || Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002336 return error("Invalid record");
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002337
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002338 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2339 // DW_TAG_arg_variable.
2340 bool HasTag = Record.size() > 8;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002341 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002342 GET_OR_DISTINCT(DILocalVariable, Record[0],
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002343 (Context, getMDOrNull(Record[1 + HasTag]),
2344 getMDString(Record[2 + HasTag]),
2345 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2346 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2347 Record[7 + HasTag])),
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002348 NextMDValueNo++);
2349 break;
2350 }
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002351 case bitc::METADATA_EXPRESSION: {
2352 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002353 return error("Invalid record");
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002354
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002355 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002356 GET_OR_DISTINCT(DIExpression, Record[0],
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002357 (Context, makeArrayRef(Record).slice(1))),
2358 NextMDValueNo++);
2359 break;
2360 }
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002361 case bitc::METADATA_OBJC_PROPERTY: {
2362 if (Record.size() != 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002363 return error("Invalid record");
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002364
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002365 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002366 GET_OR_DISTINCT(DIObjCProperty, Record[0],
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002367 (Context, getMDString(Record[1]),
2368 getMDOrNull(Record[2]), Record[3],
2369 getMDString(Record[4]), getMDString(Record[5]),
2370 Record[6], getMDOrNull(Record[7]))),
2371 NextMDValueNo++);
2372 break;
2373 }
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002374 case bitc::METADATA_IMPORTED_ENTITY: {
2375 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002376 return error("Invalid record");
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002377
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002378 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002379 GET_OR_DISTINCT(DIImportedEntity, Record[0],
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002380 (Context, Record[1], getMDOrNull(Record[2]),
2381 getMDOrNull(Record[3]), Record[4],
2382 getMDString(Record[5]))),
2383 NextMDValueNo++);
2384 break;
2385 }
Devang Patel7428d8a2009-07-22 17:43:22 +00002386 case bitc::METADATA_STRING: {
Eli Bendersky5d5e18d2014-06-25 15:41:00 +00002387 std::string String(Record.begin(), Record.end());
2388 llvm::UpgradeMDStringConstant(String);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002389 Metadata *MD = MDString::get(Context, String);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002390 MDValueList.assignValue(MD, NextMDValueNo++);
Devang Patel7428d8a2009-07-22 17:43:22 +00002391 break;
2392 }
Devang Patelaf206b82009-09-18 19:26:43 +00002393 case bitc::METADATA_KIND: {
Teresa Johnson12545072015-11-15 02:00:09 +00002394 // Support older bitcode files that had METADATA_KIND records in a
2395 // block with METADATA_BLOCK_ID.
2396 if (std::error_code EC = parseMetadataKindRecord(Record))
2397 return EC;
Devang Patelaf206b82009-09-18 19:26:43 +00002398 break;
2399 }
Devang Patel7428d8a2009-07-22 17:43:22 +00002400 }
2401 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002402#undef GET_OR_DISTINCT
Devang Patel7428d8a2009-07-22 17:43:22 +00002403}
2404
Teresa Johnson12545072015-11-15 02:00:09 +00002405/// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2406std::error_code BitcodeReader::parseMetadataKinds() {
2407 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2408 return error("Invalid record");
2409
2410 SmallVector<uint64_t, 64> Record;
2411
2412 // Read all the records.
2413 while (1) {
2414 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2415
2416 switch (Entry.Kind) {
2417 case BitstreamEntry::SubBlock: // Handled for us already.
2418 case BitstreamEntry::Error:
2419 return error("Malformed block");
2420 case BitstreamEntry::EndBlock:
2421 return std::error_code();
2422 case BitstreamEntry::Record:
2423 // The interesting case.
2424 break;
2425 }
2426
2427 // Read a record.
2428 Record.clear();
2429 unsigned Code = Stream.readRecord(Entry.ID, Record);
2430 switch (Code) {
2431 default: // Default behavior: ignore.
2432 break;
2433 case bitc::METADATA_KIND: {
2434 if (std::error_code EC = parseMetadataKindRecord(Record))
2435 return EC;
2436 break;
2437 }
2438 }
2439 }
2440}
2441
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002442/// Decode a signed value stored with the sign bit in the LSB for dense VBR
2443/// encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002444uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00002445 if ((V & 1) == 0)
2446 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002447 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00002448 return -(V >> 1);
2449 // There is no such thing as -0 with integers. "-0" really means MININT.
2450 return 1ULL << 63;
2451}
2452
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002453/// Resolve all of the initializers for global values and aliases that we can.
2454std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00002455 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2456 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002457 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002458 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
David Majnemer7fddecc2015-06-17 20:52:32 +00002459 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002460
Chris Lattner44c17072007-04-26 02:46:40 +00002461 GlobalInitWorklist.swap(GlobalInits);
2462 AliasInitWorklist.swap(AliasInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002463 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002464 FunctionPrologueWorklist.swap(FunctionPrologues);
David Majnemer7fddecc2015-06-17 20:52:32 +00002465 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
Chris Lattner44c17072007-04-26 02:46:40 +00002466
2467 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00002468 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002469 if (ValID >= ValueList.size()) {
2470 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00002471 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002472 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002473 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00002474 GlobalInitWorklist.back().first->setInitializer(C);
2475 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002476 return error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00002477 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002478 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002479 }
2480
2481 while (!AliasInitWorklist.empty()) {
2482 unsigned ValID = AliasInitWorklist.back().second;
2483 if (ValID >= ValueList.size()) {
2484 AliasInits.push_back(AliasInitWorklist.back());
2485 } else {
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002486 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2487 if (!C)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002488 return error("Expected a constant");
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002489 GlobalAlias *Alias = AliasInitWorklist.back().first;
2490 if (C->getType() != Alias->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002491 return error("Alias and aliasee types don't match");
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002492 Alias->setAliasee(C);
Chris Lattner44c17072007-04-26 02:46:40 +00002493 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002494 AliasInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002495 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002496
2497 while (!FunctionPrefixWorklist.empty()) {
2498 unsigned ValID = FunctionPrefixWorklist.back().second;
2499 if (ValID >= ValueList.size()) {
2500 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2501 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002502 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002503 FunctionPrefixWorklist.back().first->setPrefixData(C);
2504 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002505 return error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002506 }
2507 FunctionPrefixWorklist.pop_back();
2508 }
2509
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002510 while (!FunctionPrologueWorklist.empty()) {
2511 unsigned ValID = FunctionPrologueWorklist.back().second;
2512 if (ValID >= ValueList.size()) {
2513 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2514 } else {
2515 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2516 FunctionPrologueWorklist.back().first->setPrologueData(C);
2517 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002518 return error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002519 }
2520 FunctionPrologueWorklist.pop_back();
2521 }
2522
David Majnemer7fddecc2015-06-17 20:52:32 +00002523 while (!FunctionPersonalityFnWorklist.empty()) {
2524 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2525 if (ValID >= ValueList.size()) {
2526 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2527 } else {
2528 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2529 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2530 else
2531 return error("Expected a constant");
2532 }
2533 FunctionPersonalityFnWorklist.pop_back();
2534 }
2535
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002536 return std::error_code();
Chris Lattner44c17072007-04-26 02:46:40 +00002537}
2538
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002539static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002540 SmallVector<uint64_t, 8> Words(Vals.size());
2541 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00002542 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002543
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002544 return APInt(TypeBits, Words);
2545}
2546
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002547std::error_code BitcodeReader::parseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002548 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002549 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002550
2551 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002552
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002553 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00002554 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00002555 unsigned NextCstNo = ValueList.size();
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002556 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002557 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002558
Chris Lattner27d38752013-01-20 02:13:19 +00002559 switch (Entry.Kind) {
2560 case BitstreamEntry::SubBlock: // Handled for us already.
2561 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002562 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002563 case BitstreamEntry::EndBlock:
2564 if (NextCstNo != ValueList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002565 return error("Invalid ronstant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00002566
Chris Lattner27d38752013-01-20 02:13:19 +00002567 // Once all the constants have been read, go through and resolve forward
2568 // references.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002569 ValueList.resolveConstantForwardRefs();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002570 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002571 case BitstreamEntry::Record:
2572 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00002573 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002574 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002575
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002576 // Read a record.
2577 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00002578 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002579 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002580 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002581 default: // Default behavior: unknown constant
2582 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00002583 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002584 break;
2585 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2586 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002587 return error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00002588 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002589 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002590 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00002591 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002592 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00002593 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002594 break;
2595 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002596 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002597 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002598 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00002599 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00002600 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002601 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002602 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002603
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002604 APInt VInt =
2605 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002606 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002607
Chris Lattner08feb1e2007-04-24 04:04:35 +00002608 break;
2609 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002610 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00002611 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002612 return error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00002613 if (CurTy->isHalfTy())
Tim Northover29178a32013-01-22 09:46:31 +00002614 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2615 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00002616 else if (CurTy->isFloatTy())
Tim Northover29178a32013-01-22 09:46:31 +00002617 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2618 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002619 else if (CurTy->isDoubleTy())
Tim Northover29178a32013-01-22 09:46:31 +00002620 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2621 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002622 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00002623 // Bits are not stored the same way as a normal i80 APInt, compensate.
2624 uint64_t Rearrange[2];
2625 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2626 Rearrange[1] = Record[0] >> 48;
Tim Northover29178a32013-01-22 09:46:31 +00002627 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2628 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002629 } else if (CurTy->isFP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002630 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2631 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002632 else if (CurTy->isPPC_FP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002633 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2634 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002635 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00002636 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002637 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00002638 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002639
Chris Lattnere14cb882007-05-04 19:11:41 +00002640 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2641 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002642 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002643
Chris Lattnere14cb882007-05-04 19:11:41 +00002644 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00002645 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002646
Chris Lattner229907c2011-07-18 04:54:35 +00002647 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00002648 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002649 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00002650 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00002651 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002652 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2653 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002654 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002655 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00002656 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002657 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2658 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002659 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002660 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00002661 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00002662 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002663 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00002664 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002665 break;
2666 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002667 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00002668 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2669 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002670 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002671
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002672 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002673 V = ConstantDataArray::getString(Context, Elts,
2674 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00002675 break;
2676 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002677 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2678 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002679 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002680
Chris Lattner372dd1e2012-01-30 00:51:16 +00002681 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2682 unsigned Size = Record.size();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002683
Chris Lattner372dd1e2012-01-30 00:51:16 +00002684 if (EltTy->isIntegerTy(8)) {
2685 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2686 if (isa<VectorType>(CurTy))
2687 V = ConstantDataVector::get(Context, Elts);
2688 else
2689 V = ConstantDataArray::get(Context, Elts);
2690 } else if (EltTy->isIntegerTy(16)) {
2691 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2692 if (isa<VectorType>(CurTy))
2693 V = ConstantDataVector::get(Context, Elts);
2694 else
2695 V = ConstantDataArray::get(Context, Elts);
2696 } else if (EltTy->isIntegerTy(32)) {
2697 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2698 if (isa<VectorType>(CurTy))
2699 V = ConstantDataVector::get(Context, Elts);
2700 else
2701 V = ConstantDataArray::get(Context, Elts);
2702 } else if (EltTy->isIntegerTy(64)) {
2703 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2704 if (isa<VectorType>(CurTy))
2705 V = ConstantDataVector::get(Context, Elts);
2706 else
2707 V = ConstantDataArray::get(Context, Elts);
2708 } else if (EltTy->isFloatTy()) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002709 SmallVector<float, 16> Elts(Size);
2710 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002711 if (isa<VectorType>(CurTy))
2712 V = ConstantDataVector::get(Context, Elts);
2713 else
2714 V = ConstantDataArray::get(Context, Elts);
2715 } else if (EltTy->isDoubleTy()) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002716 SmallVector<double, 16> Elts(Size);
2717 std::transform(Record.begin(), Record.end(), Elts.begin(),
2718 BitsToDouble);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002719 if (isa<VectorType>(CurTy))
2720 V = ConstantDataVector::get(Context, Elts);
2721 else
2722 V = ConstantDataArray::get(Context, Elts);
2723 } else {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002724 return error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00002725 }
2726 break;
2727 }
2728
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002729 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002730 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002731 return error("Invalid record");
2732 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002733 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002734 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00002735 } else {
2736 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2737 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00002738 unsigned Flags = 0;
2739 if (Record.size() >= 4) {
2740 if (Opc == Instruction::Add ||
2741 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002742 Opc == Instruction::Mul ||
2743 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00002744 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2745 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2746 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2747 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002748 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002749 Opc == Instruction::UDiv ||
2750 Opc == Instruction::LShr ||
2751 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00002752 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00002753 Flags |= SDivOperator::IsExact;
2754 }
2755 }
2756 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00002757 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002758 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002759 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002760 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002761 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002762 return error("Invalid record");
2763 int Opc = getDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00002764 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002765 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00002766 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002767 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002768 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002769 return error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00002770 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002771 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2772 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002773 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002774 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002775 }
Dan Gohman1639c392009-07-27 21:53:46 +00002776 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002777 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
David Blaikieb9263572015-03-13 21:03:36 +00002778 unsigned OpNum = 0;
2779 Type *PointeeType = nullptr;
2780 if (Record.size() % 2)
2781 PointeeType = getTypeByID(Record[OpNum++]);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002782 SmallVector<Constant*, 16> Elts;
David Blaikieb9263572015-03-13 21:03:36 +00002783 while (OpNum != Record.size()) {
2784 Type *ElTy = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002785 if (!ElTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002786 return error("Invalid record");
David Blaikieb9263572015-03-13 21:03:36 +00002787 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002788 }
David Blaikieb9263572015-03-13 21:03:36 +00002789
David Blaikieb9263572015-03-13 21:03:36 +00002790 if (PointeeType &&
David Blaikie4a2e73b2015-04-02 18:55:32 +00002791 PointeeType !=
2792 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2793 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002794 return error("Explicit gep operator type does not match pointee type "
David Blaikie12cf5d702015-03-16 22:03:50 +00002795 "of pointer operand");
David Blaikie4a2e73b2015-04-02 18:55:32 +00002796
2797 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2798 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2799 BitCode ==
2800 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattner890683d2007-04-24 18:15:21 +00002801 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002802 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00002803 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002804 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002805 return error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00002806
2807 Type *SelectorTy = Type::getInt1Ty(Context);
2808
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00002809 // The selector might be an i1 or an <n x i1>
2810 // Get the type from the ValueList before getting a forward ref.
Joe Abbey1a6e7702013-09-12 22:02:31 +00002811 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00002812 if (Value *V = ValueList[Record[0]])
2813 if (SelectorTy != V->getType())
2814 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
Joe Abbey1a6e7702013-09-12 22:02:31 +00002815
2816 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2817 SelectorTy),
2818 ValueList.getConstantFwdRef(Record[1],CurTy),
2819 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002820 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00002821 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002822 case bitc::CST_CODE_CE_EXTRACTELT
2823 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002824 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002825 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002826 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002827 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002828 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002829 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002830 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002831 Constant *Op1 = nullptr;
2832 if (Record.size() == 4) {
2833 Type *IdxTy = getTypeByID(Record[2]);
2834 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002835 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002836 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2837 } else // TODO: Remove with llvm 4.0
2838 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2839 if (!Op1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002840 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002841 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002842 break;
2843 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002844 case bitc::CST_CODE_CE_INSERTELT
2845 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002846 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002847 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002848 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002849 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2850 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2851 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002852 Constant *Op2 = nullptr;
2853 if (Record.size() == 4) {
2854 Type *IdxTy = getTypeByID(Record[2]);
2855 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002856 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002857 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2858 } else // TODO: Remove with llvm 4.0
2859 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2860 if (!Op2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002861 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002862 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002863 break;
2864 }
2865 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002866 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002867 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002868 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002869 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2870 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002871 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002872 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002873 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002874 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002875 break;
2876 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00002877 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002878 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2879 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00002880 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002881 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002882 return error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002883 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2884 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002885 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002886 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00002887 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002888 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00002889 break;
2890 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002891 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002892 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002893 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002894 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002895 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002896 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002897 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2898 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2899
Duncan Sands9dff9be2010-02-15 16:12:20 +00002900 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002901 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00002902 else
Owen Anderson487375e2009-07-29 18:55:55 +00002903 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002904 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00002905 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002906 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00002907 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002908 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002909 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002910 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002911 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00002912 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002913 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002914 unsigned AsmStrSize = Record[1];
2915 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002916 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002917 unsigned ConstStrSize = Record[2+AsmStrSize];
2918 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002919 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002920
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002921 for (unsigned i = 0; i != AsmStrSize; ++i)
2922 AsmStr += (char)Record[2+i];
2923 for (unsigned i = 0; i != ConstStrSize; ++i)
2924 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00002925 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002926 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002927 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002928 break;
2929 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002930 // This version adds support for the asm dialect keywords (e.g.,
2931 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002932 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002933 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002934 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002935 std::string AsmStr, ConstrStr;
2936 bool HasSideEffects = Record[0] & 1;
2937 bool IsAlignStack = (Record[0] >> 1) & 1;
2938 unsigned AsmDialect = Record[0] >> 2;
2939 unsigned AsmStrSize = Record[1];
2940 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002941 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002942 unsigned ConstStrSize = Record[2+AsmStrSize];
2943 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002944 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002945
2946 for (unsigned i = 0; i != AsmStrSize; ++i)
2947 AsmStr += (char)Record[2+i];
2948 for (unsigned i = 0; i != ConstStrSize; ++i)
2949 ConstrStr += (char)Record[3+AsmStrSize+i];
2950 PointerType *PTy = cast<PointerType>(CurTy);
2951 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2952 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00002953 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002954 break;
2955 }
Chris Lattner5956dc82009-10-28 05:53:48 +00002956 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00002957 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002958 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002959 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002960 if (!FnTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002961 return error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00002962 Function *Fn =
2963 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00002964 if (!Fn)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002965 return error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002966
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00002967 // Don't let Fn get dematerialized.
2968 BlockAddressesTaken.insert(Fn);
2969
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002970 // If the function is already parsed we can insert the block address right
2971 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002972 BasicBlock *BB;
2973 unsigned BBID = Record[2];
2974 if (!BBID)
2975 // Invalid reference to entry block.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002976 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002977 if (!Fn->empty()) {
2978 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002979 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002980 if (BBI == BBE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002981 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002982 ++BBI;
2983 }
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00002984 BB = &*BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002985 } else {
2986 // Otherwise insert a placeholder and remember it so it can be inserted
2987 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00002988 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2989 if (FwdBBs.empty())
2990 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00002991 if (FwdBBs.size() < BBID + 1)
2992 FwdBBs.resize(BBID + 1);
2993 if (!FwdBBs[BBID])
2994 FwdBBs[BBID] = BasicBlock::Create(Context);
2995 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002996 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002997 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00002998 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002999 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003000 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003001
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003002 if (ValueList.assignValue(V, NextCstNo))
3003 return error("Invalid forward reference");
Chris Lattner1663cca2007-04-24 05:48:56 +00003004 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003005 }
3006}
Chris Lattner1314b992007-04-22 06:23:29 +00003007
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003008std::error_code BitcodeReader::parseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00003009 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003010 return error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00003011
Chad Rosierca2567b2011-12-07 21:44:12 +00003012 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003013 SmallVector<uint64_t, 64> Record;
Chad Rosierca2567b2011-12-07 21:44:12 +00003014 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00003015 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003016
Chris Lattner27d38752013-01-20 02:13:19 +00003017 switch (Entry.Kind) {
3018 case BitstreamEntry::SubBlock: // Handled for us already.
3019 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003020 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003021 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003022 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003023 case BitstreamEntry::Record:
3024 // The interesting case.
3025 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003026 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003027
Chad Rosierca2567b2011-12-07 21:44:12 +00003028 // Read a use list record.
3029 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003030 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00003031 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00003032 default: // Default behavior: unknown type.
3033 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003034 case bitc::USELIST_CODE_BB:
3035 IsBB = true;
3036 // fallthrough
3037 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00003038 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003039 if (RecordLength < 3)
3040 // Records should have at least an ID and two indexes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003041 return error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003042 unsigned ID = Record.back();
3043 Record.pop_back();
3044
3045 Value *V;
3046 if (IsBB) {
3047 assert(ID < FunctionBBs.size() && "Basic block not found");
3048 V = FunctionBBs[ID];
3049 } else
3050 V = ValueList[ID];
3051 unsigned NumUses = 0;
3052 SmallDenseMap<const Use *, unsigned, 16> Order;
3053 for (const Use &U : V->uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00003054 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003055 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00003056 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003057 }
3058 if (Order.size() != Record.size() || NumUses > Record.size())
3059 // Mismatches can happen if the functions are being materialized lazily
3060 // (out-of-order), or a value has been upgraded.
3061 break;
3062
3063 V->sortUseList([&](const Use &L, const Use &R) {
3064 return Order.lookup(&L) < Order.lookup(&R);
3065 });
Chad Rosierca2567b2011-12-07 21:44:12 +00003066 break;
3067 }
3068 }
3069 }
3070}
3071
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003072/// When we see the block for metadata, remember where it is and then skip it.
3073/// This lets us lazily deserialize the metadata.
3074std::error_code BitcodeReader::rememberAndSkipMetadata() {
3075 // Save the current stream state.
3076 uint64_t CurBit = Stream.GetCurrentBitNo();
3077 DeferredMetadataInfo.push_back(CurBit);
3078
3079 // Skip over the block for now.
3080 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003081 return error("Invalid record");
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003082 return std::error_code();
3083}
3084
3085std::error_code BitcodeReader::materializeMetadata() {
3086 for (uint64_t BitPos : DeferredMetadataInfo) {
3087 // Move the bit stream to the saved position.
3088 Stream.JumpToBit(BitPos);
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003089 if (std::error_code EC = parseMetadata(true))
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003090 return EC;
3091 }
3092 DeferredMetadataInfo.clear();
3093 return std::error_code();
3094}
3095
Rafael Espindola468b8682015-04-01 14:44:59 +00003096void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00003097
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003098/// When we see the block for a function body, remember where it is and then
3099/// skip it. This lets us lazily deserialize the functions.
3100std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003101 // Get the function we are talking about.
3102 if (FunctionsWithBodies.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003103 return error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003104
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003105 Function *Fn = FunctionsWithBodies.back();
3106 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003107
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003108 // Save the current stream state.
3109 uint64_t CurBit = Stream.GetCurrentBitNo();
Teresa Johnson1493ad92015-10-10 14:18:36 +00003110 assert(
3111 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3112 "Mismatch between VST and scanned function offsets");
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003113 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003114
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003115 // Skip over the function block for now.
3116 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003117 return error("Invalid record");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003118 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003119}
3120
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003121std::error_code BitcodeReader::globalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003122 // Patch the initializers for globals and aliases up.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003123 resolveGlobalAndAliasInits();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003124 if (!GlobalInits.empty() || !AliasInits.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003125 return error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003126
3127 // Look for intrinsic functions which need to be upgraded at some point
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003128 for (Function &F : *TheModule) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003129 Function *NewFn;
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003130 if (UpgradeIntrinsicFunction(&F, NewFn))
Rafael Espindola4e721212015-07-02 16:22:40 +00003131 UpgradedIntrinsics[&F] = NewFn;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003132 }
3133
3134 // Look for global variables which need to be renamed.
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003135 for (GlobalVariable &GV : TheModule->globals())
3136 UpgradeGlobalVariable(&GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00003137
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003138 // Force deallocation of memory for these vectors to favor the client that
3139 // want lazy deserialization.
3140 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3141 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003142 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003143}
3144
Teresa Johnson1493ad92015-10-10 14:18:36 +00003145/// Support for lazy parsing of function bodies. This is required if we
3146/// either have an old bitcode file without a VST forward declaration record,
3147/// or if we have an anonymous function being materialized, since anonymous
3148/// functions do not have a name and are therefore not in the VST.
3149std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3150 Stream.JumpToBit(NextUnreadBit);
3151
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003152 if (Stream.AtEndOfStream())
3153 return error("Could not find function in stream");
Teresa Johnson1493ad92015-10-10 14:18:36 +00003154
Filipe Cabecinhas7aae2f22015-11-03 13:48:26 +00003155 if (!SeenFirstFunctionBody)
3156 return error("Trying to materialize functions before seeing function blocks");
3157
Teresa Johnson1493ad92015-10-10 14:18:36 +00003158 // An old bitcode file with the symbol table at the end would have
3159 // finished the parse greedily.
3160 assert(SeenValueSymbolTable);
3161
3162 SmallVector<uint64_t, 64> Record;
3163
3164 while (1) {
3165 BitstreamEntry Entry = Stream.advance();
3166 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003167 default:
3168 return error("Expect SubBlock");
3169 case BitstreamEntry::SubBlock:
3170 switch (Entry.ID) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003171 default:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003172 return error("Expect function block");
3173 case bitc::FUNCTION_BLOCK_ID:
3174 if (std::error_code EC = rememberAndSkipFunctionBody())
3175 return EC;
3176 NextUnreadBit = Stream.GetCurrentBitNo();
3177 return std::error_code();
3178 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00003179 }
3180 }
3181}
3182
Mehdi Amini5d303282015-10-26 18:37:00 +00003183std::error_code BitcodeReader::parseBitcodeVersion() {
3184 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3185 return error("Invalid record");
3186
3187 // Read all the records.
3188 SmallVector<uint64_t, 64> Record;
3189 while (1) {
3190 BitstreamEntry Entry = Stream.advance();
3191
3192 switch (Entry.Kind) {
3193 default:
3194 case BitstreamEntry::Error:
3195 return error("Malformed block");
3196 case BitstreamEntry::EndBlock:
3197 return std::error_code();
3198 case BitstreamEntry::Record:
3199 // The interesting case.
3200 break;
3201 }
3202
3203 // Read a record.
3204 Record.clear();
3205 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3206 switch (BitCode) {
3207 default: // Default behavior: reject
3208 return error("Invalid value");
3209 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3210 // N]
3211 convertToString(Record, 0, ProducerIdentification);
3212 break;
3213 }
3214 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3215 unsigned epoch = (unsigned)Record[0];
3216 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
Oleksiy Vyalov6c2403f2015-10-26 22:37:36 +00003217 return error(
3218 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3219 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
Mehdi Amini5d303282015-10-26 18:37:00 +00003220 }
3221 }
3222 }
3223 }
3224}
3225
Teresa Johnson1493ad92015-10-10 14:18:36 +00003226std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003227 bool ShouldLazyLoadMetadata) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003228 if (ResumeBit)
3229 Stream.JumpToBit(ResumeBit);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003230 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003231 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003232
Chris Lattner1314b992007-04-22 06:23:29 +00003233 SmallVector<uint64_t, 64> Record;
3234 std::vector<std::string> SectionTable;
Gordon Henriksend930f912008-08-17 18:44:35 +00003235 std::vector<std::string> GCTable;
Chris Lattner1314b992007-04-22 06:23:29 +00003236
3237 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00003238 while (1) {
3239 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003240
Chris Lattner27d38752013-01-20 02:13:19 +00003241 switch (Entry.Kind) {
3242 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003243 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003244 case BitstreamEntry::EndBlock:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003245 return globalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00003246
Chris Lattner27d38752013-01-20 02:13:19 +00003247 case BitstreamEntry::SubBlock:
3248 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00003249 default: // Skip unknown content.
3250 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003251 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003252 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003253 case bitc::BLOCKINFO_BLOCK_ID:
3254 if (Stream.ReadBlockInfoBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003255 return error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003256 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003257 case bitc::PARAMATTR_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003258 if (std::error_code EC = parseAttributeBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003259 return EC;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003260 break;
Bill Wendlingba629332013-02-10 23:24:25 +00003261 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003262 if (std::error_code EC = parseAttributeGroupBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003263 return EC;
Bill Wendlingba629332013-02-10 23:24:25 +00003264 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003265 case bitc::TYPE_BLOCK_ID_NEW:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003266 if (std::error_code EC = parseTypeTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003267 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00003268 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00003269 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnsonff642b92015-09-17 20:12:00 +00003270 if (!SeenValueSymbolTable) {
3271 // Either this is an old form VST without function index and an
3272 // associated VST forward declaration record (which would have caused
3273 // the VST to be jumped to and parsed before it was encountered
3274 // normally in the stream), or there were no function blocks to
3275 // trigger an earlier parsing of the VST.
3276 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3277 if (std::error_code EC = parseValueSymbolTable())
3278 return EC;
3279 SeenValueSymbolTable = true;
3280 } else {
3281 // We must have had a VST forward declaration record, which caused
3282 // the parser to jump to and parse the VST earlier.
3283 assert(VSTOffset > 0);
3284 if (Stream.SkipBlock())
3285 return error("Invalid record");
3286 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00003287 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003288 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003289 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003290 return EC;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003291 if (std::error_code EC = resolveGlobalAndAliasInits())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003292 return EC;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003293 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00003294 case bitc::METADATA_BLOCK_ID:
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003295 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3296 if (std::error_code EC = rememberAndSkipMetadata())
3297 return EC;
3298 break;
3299 }
3300 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003301 if (std::error_code EC = parseMetadata(true))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003302 return EC;
Devang Patel7428d8a2009-07-22 17:43:22 +00003303 break;
Teresa Johnson12545072015-11-15 02:00:09 +00003304 case bitc::METADATA_KIND_BLOCK_ID:
3305 if (std::error_code EC = parseMetadataKinds())
3306 return EC;
3307 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003308 case bitc::FUNCTION_BLOCK_ID:
3309 // If this is the first function body we've seen, reverse the
3310 // FunctionsWithBodies list.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003311 if (!SeenFirstFunctionBody) {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003312 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003313 if (std::error_code EC = globalCleanup())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003314 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003315 SeenFirstFunctionBody = true;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003316 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003317
Teresa Johnsonff642b92015-09-17 20:12:00 +00003318 if (VSTOffset > 0) {
3319 // If we have a VST forward declaration record, make sure we
3320 // parse the VST now if we haven't already. It is needed to
3321 // set up the DeferredFunctionInfo vector for lazy reading.
3322 if (!SeenValueSymbolTable) {
3323 if (std::error_code EC =
3324 BitcodeReader::parseValueSymbolTable(VSTOffset))
3325 return EC;
3326 SeenValueSymbolTable = true;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003327 // Fall through so that we record the NextUnreadBit below.
3328 // This is necessary in case we have an anonymous function that
3329 // is later materialized. Since it will not have a VST entry we
3330 // need to fall back to the lazy parse to find its offset.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003331 } else {
3332 // If we have a VST forward declaration record, but have already
3333 // parsed the VST (just above, when the first function body was
3334 // encountered here), then we are resuming the parse after
Teresa Johnson1493ad92015-10-10 14:18:36 +00003335 // materializing functions. The ResumeBit points to the
3336 // start of the last function block recorded in the
3337 // DeferredFunctionInfo map. Skip it.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003338 if (Stream.SkipBlock())
3339 return error("Invalid record");
3340 continue;
3341 }
3342 }
3343
3344 // Support older bitcode files that did not have the function
Teresa Johnson1493ad92015-10-10 14:18:36 +00003345 // index in the VST, nor a VST forward declaration record, as
3346 // well as anonymous functions that do not have VST entries.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003347 // Build the DeferredFunctionInfo vector on the fly.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003348 if (std::error_code EC = rememberAndSkipFunctionBody())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003349 return EC;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003350
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003351 // Suspend parsing when we reach the function bodies. Subsequent
3352 // materialization calls will resume it when necessary. If the bitcode
3353 // file is old, the symbol table will be at the end instead and will not
3354 // have been seen yet. In this case, just finish the parse now.
3355 if (SeenValueSymbolTable) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003356 NextUnreadBit = Stream.GetCurrentBitNo();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003357 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003358 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003359 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003360 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003361 if (std::error_code EC = parseUseLists())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003362 return EC;
Chad Rosierca2567b2011-12-07 21:44:12 +00003363 break;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003364 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3365 if (std::error_code EC = parseOperandBundleTags())
3366 return EC;
3367 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003368 }
3369 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003370
Chris Lattner27d38752013-01-20 02:13:19 +00003371 case BitstreamEntry::Record:
3372 // The interesting case.
3373 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003374 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003375
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003376
Chris Lattner1314b992007-04-22 06:23:29 +00003377 // Read a record.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003378 auto BitCode = Stream.readRecord(Entry.ID, Record);
3379 switch (BitCode) {
Chris Lattner1314b992007-04-22 06:23:29 +00003380 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungafaced02012-10-11 20:20:40 +00003381 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattner1314b992007-04-22 06:23:29 +00003382 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003383 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00003384 // Only version #0 and #1 are supported so far.
3385 unsigned module_version = Record[0];
3386 switch (module_version) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003387 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003388 return error("Invalid value");
Jan Wen Voungafaced02012-10-11 20:20:40 +00003389 case 0:
3390 UseRelativeIDs = false;
3391 break;
3392 case 1:
3393 UseRelativeIDs = true;
3394 break;
3395 }
Chris Lattner1314b992007-04-22 06:23:29 +00003396 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00003397 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003398 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003399 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003400 if (convertToString(Record, 0, S))
3401 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003402 TheModule->setTargetTriple(S);
3403 break;
3404 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003405 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003406 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003407 if (convertToString(Record, 0, S))
3408 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003409 TheModule->setDataLayout(S);
3410 break;
3411 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003412 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003413 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003414 if (convertToString(Record, 0, S))
3415 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003416 TheModule->setModuleInlineAsm(S);
3417 break;
3418 }
Bill Wendling706d3d62012-11-28 08:41:48 +00003419 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3420 // FIXME: Remove in 4.0.
3421 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003422 if (convertToString(Record, 0, S))
3423 return error("Invalid record");
Bill Wendling706d3d62012-11-28 08:41:48 +00003424 // Ignore value.
3425 break;
3426 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003427 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003428 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003429 if (convertToString(Record, 0, S))
3430 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003431 SectionTable.push_back(S);
3432 break;
3433 }
Gordon Henriksend930f912008-08-17 18:44:35 +00003434 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00003435 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003436 if (convertToString(Record, 0, S))
3437 return error("Invalid record");
Gordon Henriksend930f912008-08-17 18:44:35 +00003438 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00003439 break;
3440 }
David Majnemerdad0a642014-06-27 18:19:56 +00003441 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3442 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003443 return error("Invalid record");
David Majnemerdad0a642014-06-27 18:19:56 +00003444 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3445 unsigned ComdatNameSize = Record[1];
3446 std::string ComdatName;
3447 ComdatName.reserve(ComdatNameSize);
3448 for (unsigned i = 0; i != ComdatNameSize; ++i)
3449 ComdatName += (char)Record[2 + i];
3450 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3451 C->setSelectionKind(SK);
3452 ComdatList.push_back(C);
3453 break;
3454 }
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003455 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00003456 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00003457 // unnamed_addr, externally_initialized, dllstorageclass,
3458 // comdat]
Chris Lattner1314b992007-04-22 06:23:29 +00003459 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner4b00d922007-04-23 16:04:05 +00003460 if (Record.size() < 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003461 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003462 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003463 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003464 return error("Invalid record");
David Blaikie1a848da2015-04-27 19:58:56 +00003465 bool isConstant = Record[1] & 1;
3466 bool explicitType = Record[1] & 2;
3467 unsigned AddressSpace;
3468 if (explicitType) {
3469 AddressSpace = Record[1] >> 2;
3470 } else {
3471 if (!Ty->isPointerTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003472 return error("Invalid type for value");
David Blaikie1a848da2015-04-27 19:58:56 +00003473 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3474 Ty = cast<PointerType>(Ty)->getElementType();
3475 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003476
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003477 uint64_t RawLinkage = Record[3];
3478 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
JF Bastien30bf96b2015-02-22 19:32:03 +00003479 unsigned Alignment;
3480 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3481 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00003482 std::string Section;
3483 if (Record[5]) {
3484 if (Record[5]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003485 return error("Invalid ID");
Chris Lattner1314b992007-04-22 06:23:29 +00003486 Section = SectionTable[Record[5]-1];
3487 }
Chris Lattner4b00d922007-04-23 16:04:05 +00003488 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003489 // Local linkage must have default visibility.
3490 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3491 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003492 Visibility = getDecodedVisibility(Record[6]);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00003493
3494 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner53862f72007-05-06 19:27:46 +00003495 if (Record.size() > 7)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003496 TLM = getDecodedThreadLocalMode(Record[7]);
Chris Lattner1314b992007-04-22 06:23:29 +00003497
Rafael Espindola45e6c192011-01-08 16:42:36 +00003498 bool UnnamedAddr = false;
3499 if (Record.size() > 8)
3500 UnnamedAddr = Record[8];
3501
Michael Gottesman27e7ef32013-02-05 05:57:38 +00003502 bool ExternallyInitialized = false;
3503 if (Record.size() > 9)
3504 ExternallyInitialized = Record[9];
3505
Chris Lattner1314b992007-04-22 06:23:29 +00003506 GlobalVariable *NewGV =
Craig Topper2617dcc2014-04-15 06:32:26 +00003507 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
Michael Gottesman27e7ef32013-02-05 05:57:38 +00003508 TLM, AddressSpace, ExternallyInitialized);
Chris Lattner1314b992007-04-22 06:23:29 +00003509 NewGV->setAlignment(Alignment);
3510 if (!Section.empty())
3511 NewGV->setSection(Section);
3512 NewGV->setVisibility(Visibility);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003513 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003514
Nico Rieck7157bb72014-01-14 15:22:47 +00003515 if (Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003516 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003517 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003518 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00003519
Chris Lattnerccaa4482007-04-23 21:26:05 +00003520 ValueList.push_back(NewGV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003521
Chris Lattner47d131b2007-04-24 00:18:21 +00003522 // Remember which value to use for the global initializer.
3523 if (unsigned InitID = Record[2])
3524 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
David Majnemerdad0a642014-06-27 18:19:56 +00003525
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003526 if (Record.size() > 11) {
David Majnemerdad0a642014-06-27 18:19:56 +00003527 if (unsigned ComdatID = Record[11]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00003528 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003529 return error("Invalid global variable comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00003530 NewGV->setComdat(ComdatList[ComdatID - 1]);
3531 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003532 } else if (hasImplicitComdat(RawLinkage)) {
3533 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3534 }
Chris Lattner1314b992007-04-22 06:23:29 +00003535 break;
3536 }
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003537 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Nico Rieck7157bb72014-01-14 15:22:47 +00003538 // alignment, section, visibility, gc, unnamed_addr,
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003539 // prologuedata, dllstorageclass, comdat, prefixdata]
Chris Lattner1314b992007-04-22 06:23:29 +00003540 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003541 if (Record.size() < 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003542 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003543 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003544 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003545 return error("Invalid record");
David Blaikie561a1572015-04-17 16:28:26 +00003546 if (auto *PTy = dyn_cast<PointerType>(Ty))
3547 Ty = PTy->getElementType();
3548 auto *FTy = dyn_cast<FunctionType>(Ty);
Chris Lattner1314b992007-04-22 06:23:29 +00003549 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003550 return error("Invalid type for value");
Vedant Kumarad6d6e72015-10-27 21:17:06 +00003551 auto CC = static_cast<CallingConv::ID>(Record[1]);
3552 if (CC & ~CallingConv::MaxID)
3553 return error("Invalid calling convention ID");
Chris Lattner1314b992007-04-22 06:23:29 +00003554
Gabor Greife9ecc682008-04-06 20:25:17 +00003555 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3556 "", TheModule);
Chris Lattner1314b992007-04-22 06:23:29 +00003557
Vedant Kumarad6d6e72015-10-27 21:17:06 +00003558 Func->setCallingConv(CC);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003559 bool isProto = Record[2];
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003560 uint64_t RawLinkage = Record[3];
3561 Func->setLinkage(getDecodedLinkage(RawLinkage));
Devang Patel4c758ea2008-09-25 21:00:45 +00003562 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003563
JF Bastien30bf96b2015-02-22 19:32:03 +00003564 unsigned Alignment;
3565 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3566 return EC;
3567 Func->setAlignment(Alignment);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003568 if (Record[6]) {
3569 if (Record[6]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003570 return error("Invalid ID");
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003571 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattner1314b992007-04-22 06:23:29 +00003572 }
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003573 // Local linkage must have default visibility.
3574 if (!Func->hasLocalLinkage())
3575 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003576 Func->setVisibility(getDecodedVisibility(Record[7]));
Gordon Henriksen71183b62007-12-10 03:18:06 +00003577 if (Record.size() > 8 && Record[8]) {
Filipe Cabecinhasf8a16a92015-04-30 04:09:41 +00003578 if (Record[8]-1 >= GCTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003579 return error("Invalid ID");
Gordon Henriksend930f912008-08-17 18:44:35 +00003580 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen71183b62007-12-10 03:18:06 +00003581 }
Rafael Espindola45e6c192011-01-08 16:42:36 +00003582 bool UnnamedAddr = false;
3583 if (Record.size() > 9)
3584 UnnamedAddr = Record[9];
3585 Func->setUnnamedAddr(UnnamedAddr);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003586 if (Record.size() > 10 && Record[10] != 0)
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003587 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
Nico Rieck7157bb72014-01-14 15:22:47 +00003588
3589 if (Record.size() > 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003590 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003591 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003592 upgradeDLLImportExportLinkage(Func, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00003593
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003594 if (Record.size() > 12) {
David Majnemerdad0a642014-06-27 18:19:56 +00003595 if (unsigned ComdatID = Record[12]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00003596 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003597 return error("Invalid function comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00003598 Func->setComdat(ComdatList[ComdatID - 1]);
3599 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003600 } else if (hasImplicitComdat(RawLinkage)) {
3601 Func->setComdat(reinterpret_cast<Comdat *>(1));
3602 }
David Majnemerdad0a642014-06-27 18:19:56 +00003603
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003604 if (Record.size() > 13 && Record[13] != 0)
3605 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3606
David Majnemer7fddecc2015-06-17 20:52:32 +00003607 if (Record.size() > 14 && Record[14] != 0)
3608 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3609
Chris Lattnerccaa4482007-04-23 21:26:05 +00003610 ValueList.push_back(Func);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003611
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003612 // If this is a function with a body, remember the prototype we are
3613 // creating now, so that we can match up the body with them later.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003614 if (!isProto) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00003615 Func->setIsMaterializable(true);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003616 FunctionsWithBodies.push_back(Func);
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003617 DeferredFunctionInfo[Func] = 0;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003618 }
Chris Lattner1314b992007-04-22 06:23:29 +00003619 break;
3620 }
David Blaikie6a51dbd2015-09-17 22:18:59 +00003621 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3622 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3623 case bitc::MODULE_CODE_ALIAS:
3624 case bitc::MODULE_CODE_ALIAS_OLD: {
3625 bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
Aaron Ballman2d0f38c2015-09-18 13:31:42 +00003626 if (Record.size() < (3 + (unsigned)NewRecord))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003627 return error("Invalid record");
David Blaikie6a51dbd2015-09-17 22:18:59 +00003628 unsigned OpNum = 0;
3629 Type *Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003630 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003631 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003632
David Blaikie6a51dbd2015-09-17 22:18:59 +00003633 unsigned AddrSpace;
3634 if (!NewRecord) {
3635 auto *PTy = dyn_cast<PointerType>(Ty);
3636 if (!PTy)
3637 return error("Invalid type for value");
3638 Ty = PTy->getElementType();
3639 AddrSpace = PTy->getAddressSpace();
3640 } else {
3641 AddrSpace = Record[OpNum++];
3642 }
3643
3644 auto Val = Record[OpNum++];
3645 auto Linkage = Record[OpNum++];
3646 auto *NewGA = GlobalAlias::create(
3647 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00003648 // Old bitcode files didn't have visibility field.
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003649 // Local linkage must have default visibility.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003650 if (OpNum != Record.size()) {
3651 auto VisInd = OpNum++;
3652 if (!NewGA->hasLocalLinkage())
3653 // FIXME: Change to an error if non-default in 4.0.
3654 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3655 }
3656 if (OpNum != Record.size())
3657 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003658 else
David Blaikie6a51dbd2015-09-17 22:18:59 +00003659 upgradeDLLImportExportLinkage(NewGA, Linkage);
3660 if (OpNum != Record.size())
3661 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3662 if (OpNum != Record.size())
3663 NewGA->setUnnamedAddr(Record[OpNum++]);
Chris Lattner44c17072007-04-26 02:46:40 +00003664 ValueList.push_back(NewGA);
David Blaikie6a51dbd2015-09-17 22:18:59 +00003665 AliasInits.push_back(std::make_pair(NewGA, Val));
Chris Lattner44c17072007-04-26 02:46:40 +00003666 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003667 }
Chris Lattner831d4202007-04-26 03:27:58 +00003668 /// MODULE_CODE_PURGEVALS: [numvals]
3669 case bitc::MODULE_CODE_PURGEVALS:
3670 // Trim down the value list to the specified size.
3671 if (Record.size() < 1 || Record[0] > ValueList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003672 return error("Invalid record");
Chris Lattner831d4202007-04-26 03:27:58 +00003673 ValueList.shrinkTo(Record[0]);
3674 break;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003675 /// MODULE_CODE_VSTOFFSET: [offset]
3676 case bitc::MODULE_CODE_VSTOFFSET:
3677 if (Record.size() < 1)
3678 return error("Invalid record");
3679 VSTOffset = Record[0];
3680 break;
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003681 /// MODULE_CODE_METADATA_VALUES: [numvals]
3682 case bitc::MODULE_CODE_METADATA_VALUES:
3683 if (Record.size() < 1)
3684 return error("Invalid record");
3685 assert(!IsMetadataMaterialized);
3686 // This record contains the number of metadata values in the module-level
3687 // METADATA_BLOCK. It is used to support lazy parsing of metadata as
3688 // a postpass, where we will parse function-level metadata first.
3689 // This is needed because the ids of metadata are assigned implicitly
3690 // based on their ordering in the bitcode, with the function-level
3691 // metadata ids starting after the module-level metadata ids. Otherwise,
3692 // we would have to parse the module-level metadata block to prime the
3693 // MDValueList when we are lazy loading metadata during function
3694 // importing. Initialize the MDValueList size here based on the
3695 // record value, regardless of whether we are doing lazy metadata
3696 // loading, so that we have consistent handling and assertion
3697 // checking in parseMetadata for module-level metadata.
3698 NumModuleMDs = Record[0];
3699 SeenModuleValuesRecord = true;
3700 assert(MDValueList.size() == 0);
3701 MDValueList.resize(NumModuleMDs);
3702 break;
Chris Lattner831d4202007-04-26 03:27:58 +00003703 }
Chris Lattner1314b992007-04-22 06:23:29 +00003704 Record.clear();
3705 }
Chris Lattner1314b992007-04-22 06:23:29 +00003706}
3707
Teresa Johnson403a7872015-10-04 14:33:43 +00003708/// Helper to read the header common to all bitcode files.
3709static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3710 // Sniff for the signature.
3711 if (Stream.Read(8) != 'B' ||
3712 Stream.Read(8) != 'C' ||
3713 Stream.Read(4) != 0x0 ||
3714 Stream.Read(4) != 0xC ||
3715 Stream.Read(4) != 0xE ||
3716 Stream.Read(4) != 0xD)
3717 return false;
3718 return true;
3719}
3720
Rafael Espindola1aabf982015-06-16 23:29:49 +00003721std::error_code
3722BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3723 Module *M, bool ShouldLazyLoadMetadata) {
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003724 TheModule = M;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003725
Rafael Espindola1aabf982015-06-16 23:29:49 +00003726 if (std::error_code EC = initStream(std::move(Streamer)))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003727 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003728
Chris Lattner1314b992007-04-22 06:23:29 +00003729 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003730 if (!hasValidBitcodeHeader(Stream))
3731 return error("Invalid bitcode signature");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003732
Chris Lattner1314b992007-04-22 06:23:29 +00003733 // We expect a number of well-defined blocks, though we don't necessarily
3734 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00003735 while (1) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003736 if (Stream.AtEndOfStream()) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003737 // We didn't really read a proper Module.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003738 return error("Malformed IR file");
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003739 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003740
Chris Lattner27d38752013-01-20 02:13:19 +00003741 BitstreamEntry Entry =
3742 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbey97b7a172013-02-06 22:14:06 +00003743
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003744 if (Entry.Kind != BitstreamEntry::SubBlock)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003745 return error("Malformed block");
Joe Abbey97b7a172013-02-06 22:14:06 +00003746
Mehdi Amini5d303282015-10-26 18:37:00 +00003747 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3748 parseBitcodeVersion();
3749 continue;
3750 }
3751
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003752 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Teresa Johnson1493ad92015-10-10 14:18:36 +00003753 return parseModule(0, ShouldLazyLoadMetadata);
Joe Abbey97b7a172013-02-06 22:14:06 +00003754
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003755 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003756 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003757 }
Chris Lattner1314b992007-04-22 06:23:29 +00003758}
Chris Lattner6694f602007-04-29 07:54:31 +00003759
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003760ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
Bill Wendling0198ce02010-10-06 01:22:42 +00003761 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003762 return error("Invalid record");
Bill Wendling0198ce02010-10-06 01:22:42 +00003763
3764 SmallVector<uint64_t, 64> Record;
3765
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003766 std::string Triple;
Bill Wendling0198ce02010-10-06 01:22:42 +00003767 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00003768 while (1) {
3769 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003770
Chris Lattner27d38752013-01-20 02:13:19 +00003771 switch (Entry.Kind) {
3772 case BitstreamEntry::SubBlock: // Handled for us already.
3773 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003774 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003775 case BitstreamEntry::EndBlock:
Rafael Espindolae6107792014-07-04 20:05:56 +00003776 return Triple;
Chris Lattner27d38752013-01-20 02:13:19 +00003777 case BitstreamEntry::Record:
3778 // The interesting case.
3779 break;
Bill Wendling0198ce02010-10-06 01:22:42 +00003780 }
3781
3782 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00003783 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling0198ce02010-10-06 01:22:42 +00003784 default: break; // Default behavior, ignore unknown content.
Bill Wendling0198ce02010-10-06 01:22:42 +00003785 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003786 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003787 if (convertToString(Record, 0, S))
3788 return error("Invalid record");
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003789 Triple = S;
Bill Wendling0198ce02010-10-06 01:22:42 +00003790 break;
3791 }
3792 }
3793 Record.clear();
3794 }
Rafael Espindolae6107792014-07-04 20:05:56 +00003795 llvm_unreachable("Exit infinite loop");
Bill Wendling0198ce02010-10-06 01:22:42 +00003796}
3797
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003798ErrorOr<std::string> BitcodeReader::parseTriple() {
Rafael Espindola1aabf982015-06-16 23:29:49 +00003799 if (std::error_code EC = initStream(nullptr))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003800 return EC;
Bill Wendling0198ce02010-10-06 01:22:42 +00003801
3802 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003803 if (!hasValidBitcodeHeader(Stream))
3804 return error("Invalid bitcode signature");
Bill Wendling0198ce02010-10-06 01:22:42 +00003805
3806 // We expect a number of well-defined blocks, though we don't necessarily
3807 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00003808 while (1) {
3809 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003810
Chris Lattner27d38752013-01-20 02:13:19 +00003811 switch (Entry.Kind) {
3812 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003813 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003814 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003815 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00003816
Chris Lattner27d38752013-01-20 02:13:19 +00003817 case BitstreamEntry::SubBlock:
3818 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Rafael Espindolad346cc82014-07-04 13:52:01 +00003819 return parseModuleTriple();
Joe Abbey97b7a172013-02-06 22:14:06 +00003820
Chris Lattner27d38752013-01-20 02:13:19 +00003821 // Ignore other sub-blocks.
Rafael Espindola48da4f42013-11-04 16:16:24 +00003822 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003823 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003824 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003825
Chris Lattner27d38752013-01-20 02:13:19 +00003826 case BitstreamEntry::Record:
3827 Stream.skipRecord(Entry.ID);
3828 continue;
Bill Wendling0198ce02010-10-06 01:22:42 +00003829 }
3830 }
Bill Wendling0198ce02010-10-06 01:22:42 +00003831}
3832
Mehdi Amini3383ccc2015-11-09 02:46:41 +00003833ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
3834 if (std::error_code EC = initStream(nullptr))
3835 return EC;
3836
3837 // Sniff for the signature.
3838 if (!hasValidBitcodeHeader(Stream))
3839 return error("Invalid bitcode signature");
3840
3841 // We expect a number of well-defined blocks, though we don't necessarily
3842 // need to understand them all.
3843 while (1) {
3844 BitstreamEntry Entry = Stream.advance();
3845 switch (Entry.Kind) {
3846 case BitstreamEntry::Error:
3847 return error("Malformed block");
3848 case BitstreamEntry::EndBlock:
3849 return std::error_code();
3850
3851 case BitstreamEntry::SubBlock:
3852 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3853 if (std::error_code EC = parseBitcodeVersion())
3854 return EC;
3855 return ProducerIdentification;
3856 }
3857 // Ignore other sub-blocks.
3858 if (Stream.SkipBlock())
3859 return error("Malformed block");
3860 continue;
3861 case BitstreamEntry::Record:
3862 Stream.skipRecord(Entry.ID);
3863 continue;
3864 }
3865 }
3866}
3867
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003868/// Parse metadata attachments.
3869std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
Devang Patelaf206b82009-09-18 19:26:43 +00003870 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003871 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003872
Devang Patelaf206b82009-09-18 19:26:43 +00003873 SmallVector<uint64_t, 64> Record;
Chris Lattner27d38752013-01-20 02:13:19 +00003874 while (1) {
3875 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003876
Chris Lattner27d38752013-01-20 02:13:19 +00003877 switch (Entry.Kind) {
3878 case BitstreamEntry::SubBlock: // Handled for us already.
3879 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003880 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003881 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003882 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003883 case BitstreamEntry::Record:
3884 // The interesting case.
Devang Patelaf206b82009-09-18 19:26:43 +00003885 break;
3886 }
Chris Lattner27d38752013-01-20 02:13:19 +00003887
Devang Patelaf206b82009-09-18 19:26:43 +00003888 // Read a metadata attachment record.
3889 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00003890 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patelaf206b82009-09-18 19:26:43 +00003891 default: // Default behavior: ignore.
3892 break;
Chris Lattnerb8778552011-06-17 17:50:30 +00003893 case bitc::METADATA_ATTACHMENT: {
Devang Patelaf206b82009-09-18 19:26:43 +00003894 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003895 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003896 return error("Invalid record");
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003897 if (RecordLength % 2 == 0) {
3898 // A function attachment.
3899 for (unsigned I = 0; I != RecordLength; I += 2) {
3900 auto K = MDKindMap.find(Record[I]);
3901 if (K == MDKindMap.end())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003902 return error("Invalid ID");
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003903 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3904 F.setMetadata(K->second, cast<MDNode>(MD));
3905 }
3906 continue;
3907 }
3908
3909 // An instruction attachment.
Devang Patelaf206b82009-09-18 19:26:43 +00003910 Instruction *Inst = InstructionList[Record[0]];
3911 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patelb1a44772009-09-28 21:14:55 +00003912 unsigned Kind = Record[i];
Dan Gohman43aa8f02010-07-20 21:42:28 +00003913 DenseMap<unsigned, unsigned>::iterator I =
3914 MDKindMap.find(Kind);
3915 if (I == MDKindMap.end())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003916 return error("Invalid ID");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003917 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3918 if (isa<LocalAsMetadata>(Node))
Duncan P. N. Exon Smith35303fd2014-12-06 02:29:44 +00003919 // Drop the attachment. This used to be legal, but there's no
3920 // upgrade path.
3921 break;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003922 Inst->setMetadata(I->second, cast<MDNode>(Node));
Manman Ren209b17c2013-09-28 00:22:27 +00003923 if (I->second == LLVMContext::MD_tbaa)
3924 InstsWithTBAATag.push_back(Inst);
Devang Patelaf206b82009-09-18 19:26:43 +00003925 }
3926 break;
3927 }
3928 }
3929 }
Devang Patelaf206b82009-09-18 19:26:43 +00003930}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003931
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003932static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003933 Type *ValType, Type *PtrType) {
3934 if (!isa<PointerType>(PtrType))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003935 return error(DH, "Load/Store operand is not a pointer type");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003936 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3937
3938 if (ValType && ValType != ElemType)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003939 return error(DH, "Explicit load/store type does not match pointee type of "
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003940 "pointer operand");
3941 if (!PointerType::isLoadableOrStorableType(ElemType))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003942 return error(DH, "Cannot load/store from pointer");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003943 return std::error_code();
3944}
3945
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003946/// Lazily parse the specified function body block.
3947std::error_code BitcodeReader::parseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00003948 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003949 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003950
Nick Lewyckya72e1af2010-02-25 08:30:17 +00003951 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00003952 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman26d837d2010-08-25 20:22:53 +00003953 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003954
Chris Lattner85b7b402007-05-01 05:52:21 +00003955 // Add all the function arguments to the value table.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00003956 for (Argument &I : F->args())
3957 ValueList.push_back(&I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003958
Chris Lattner83930552007-05-01 07:01:57 +00003959 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00003960 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00003961 unsigned CurBBNo = 0;
3962
Chris Lattner07d09ed2010-04-03 02:17:50 +00003963 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003964 auto getLastInstruction = [&]() -> Instruction * {
3965 if (CurBB && !CurBB->empty())
3966 return &CurBB->back();
3967 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3968 !FunctionBBs[CurBBNo - 1]->empty())
3969 return &FunctionBBs[CurBBNo - 1]->back();
3970 return nullptr;
3971 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003972
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003973 std::vector<OperandBundleDef> OperandBundles;
3974
Chris Lattner85b7b402007-05-01 05:52:21 +00003975 // Read all the records.
3976 SmallVector<uint64_t, 64> Record;
3977 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00003978 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003979
Chris Lattner27d38752013-01-20 02:13:19 +00003980 switch (Entry.Kind) {
3981 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003982 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003983 case BitstreamEntry::EndBlock:
3984 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00003985
Chris Lattner27d38752013-01-20 02:13:19 +00003986 case BitstreamEntry::SubBlock:
3987 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00003988 default: // Skip unknown content.
3989 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003990 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00003991 break;
3992 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003993 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003994 return EC;
Chris Lattner83930552007-05-01 07:01:57 +00003995 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00003996 break;
3997 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003998 if (std::error_code EC = parseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003999 return EC;
Chris Lattner85b7b402007-05-01 05:52:21 +00004000 break;
Devang Patelaf206b82009-09-18 19:26:43 +00004001 case bitc::METADATA_ATTACHMENT_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004002 if (std::error_code EC = parseMetadataAttachment(*F))
Rafael Espindola48da4f42013-11-04 16:16:24 +00004003 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004004 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00004005 case bitc::METADATA_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004006 if (std::error_code EC = parseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004007 return EC;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00004008 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004009 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004010 if (std::error_code EC = parseUseLists())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004011 return EC;
4012 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00004013 }
4014 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00004015
Chris Lattner27d38752013-01-20 02:13:19 +00004016 case BitstreamEntry::Record:
4017 // The interesting case.
4018 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00004019 }
Joe Abbey97b7a172013-02-06 22:14:06 +00004020
Chris Lattner85b7b402007-05-01 05:52:21 +00004021 // Read a record.
4022 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00004023 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00004024 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00004025 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00004026 default: // Default behavior: reject
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004027 return error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004028 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00004029 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004030 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00004031 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00004032 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004033
4034 // See if anything took the address of blocks in this function.
4035 auto BBFRI = BasicBlockFwdRefs.find(F);
4036 if (BBFRI == BasicBlockFwdRefs.end()) {
4037 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4038 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
4039 } else {
4040 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00004041 // Check for invalid basic block references.
4042 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004043 return error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00004044 assert(!BBRefs.empty() && "Unexpected empty array");
4045 assert(!BBRefs.front() && "Invalid reference to entry block");
4046 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4047 ++I)
4048 if (I < RE && BBRefs[I]) {
4049 BBRefs[I]->insertInto(F);
4050 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004051 } else {
4052 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4053 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004054
4055 // Erase from the table.
4056 BasicBlockFwdRefs.erase(BBFRI);
4057 }
4058
Chris Lattner83930552007-05-01 07:01:57 +00004059 CurBB = FunctionBBs[0];
4060 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004061 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004062
Chris Lattner07d09ed2010-04-03 02:17:50 +00004063 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4064 // This record indicates that the last instruction is at the same
4065 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004066 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004067
Craig Topper2617dcc2014-04-15 06:32:26 +00004068 if (!I)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004069 return error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00004070 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004071 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004072 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004073
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00004074 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004075 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00004076 if (!I || Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004077 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004078
Chris Lattner07d09ed2010-04-03 02:17:50 +00004079 unsigned Line = Record[0], Col = Record[1];
4080 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004081
Craig Topper2617dcc2014-04-15 06:32:26 +00004082 MDNode *Scope = nullptr, *IA = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004083 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
4084 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
4085 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4086 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004087 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004088 continue;
4089 }
4090
Chris Lattnere9759c22007-05-06 00:21:25 +00004091 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4092 unsigned OpNum = 0;
4093 Value *LHS, *RHS;
4094 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004095 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00004096 OpNum+1 > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004097 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004098
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004099 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00004100 if (Opc == -1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004101 return error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004102 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00004103 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00004104 if (OpNum < Record.size()) {
4105 if (Opc == Instruction::Add ||
4106 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00004107 Opc == Instruction::Mul ||
4108 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00004109 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00004110 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00004111 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00004112 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00004113 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00004114 Opc == Instruction::UDiv ||
4115 Opc == Instruction::LShr ||
4116 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00004117 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00004118 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004119 } else if (isa<FPMathOperator>(I)) {
James Molloy88eb5352015-07-10 12:52:00 +00004120 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004121 if (FMF.any())
4122 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00004123 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004124
Dan Gohman1b849082009-09-07 23:54:19 +00004125 }
Chris Lattner85b7b402007-05-01 05:52:21 +00004126 break;
4127 }
Chris Lattnere9759c22007-05-06 00:21:25 +00004128 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4129 unsigned OpNum = 0;
4130 Value *Op;
4131 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4132 OpNum+2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004133 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004134
Chris Lattner229907c2011-07-18 04:54:35 +00004135 Type *ResTy = getTypeByID(Record[OpNum]);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004136 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004137 if (Opc == -1 || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004138 return error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00004139 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004140 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4141 if (Temp) {
4142 InstructionList.push_back(Temp);
4143 CurBB->getInstList().push_back(Temp);
4144 }
4145 } else {
Filipe Cabecinhasb70fd872015-10-06 12:37:54 +00004146 auto CastOp = (Instruction::CastOps)Opc;
4147 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4148 return error("Invalid cast");
4149 I = CastInst::Create(CastOp, Op, ResTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004150 }
Devang Patelaf206b82009-09-18 19:26:43 +00004151 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004152 break;
4153 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00004154 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4155 case bitc::FUNC_CODE_INST_GEP_OLD:
4156 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004157 unsigned OpNum = 0;
David Blaikieb5b5efd2015-02-25 01:08:52 +00004158
4159 Type *Ty;
4160 bool InBounds;
4161
4162 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4163 InBounds = Record[OpNum++];
4164 Ty = getTypeByID(Record[OpNum++]);
4165 } else {
4166 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4167 Ty = nullptr;
4168 }
4169
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004170 Value *BasePtr;
4171 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004172 return error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00004173
David Blaikie60310f22015-05-08 00:42:26 +00004174 if (!Ty)
4175 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4176 ->getElementType();
4177 else if (Ty !=
4178 cast<SequentialType>(BasePtr->getType()->getScalarType())
4179 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004180 return error(
David Blaikie675e8cb2015-03-16 21:35:48 +00004181 "Explicit gep type does not match pointee type of pointer operand");
4182
Chris Lattner5285b5e2007-05-02 05:46:45 +00004183 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004184 while (OpNum != Record.size()) {
4185 Value *Op;
4186 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004187 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004188 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004189 }
4190
David Blaikie096b1da2015-03-14 19:53:33 +00004191 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
David Blaikie675e8cb2015-03-16 21:35:48 +00004192
Devang Patelaf206b82009-09-18 19:26:43 +00004193 InstructionList.push_back(I);
David Blaikieb5b5efd2015-02-25 01:08:52 +00004194 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004195 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004196 break;
4197 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004198
Dan Gohman1ecaf452008-05-31 00:58:22 +00004199 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4200 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00004201 unsigned OpNum = 0;
4202 Value *Agg;
4203 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004204 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004205
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004206 unsigned RecSize = Record.size();
4207 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004208 return error("EXTRACTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004209
Dan Gohman1ecaf452008-05-31 00:58:22 +00004210 SmallVector<unsigned, 4> EXTRACTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004211 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004212 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004213 bool IsArray = CurTy->isArrayTy();
4214 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00004215 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004216
4217 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004218 return error("EXTRACTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004219 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004220 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004221 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004222 return error("EXTRACTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004223 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004224 return error("EXTRACTVAL: Invalid array index");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004225 EXTRACTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004226
4227 if (IsStruct)
4228 CurTy = CurTy->subtypes()[Index];
4229 else
4230 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00004231 }
4232
Jay Foad57aa6362011-07-13 10:26:04 +00004233 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00004234 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00004235 break;
4236 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004237
Dan Gohman1ecaf452008-05-31 00:58:22 +00004238 case bitc::FUNC_CODE_INST_INSERTVAL: {
4239 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00004240 unsigned OpNum = 0;
4241 Value *Agg;
4242 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004243 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004244 Value *Val;
4245 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004246 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004247
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004248 unsigned RecSize = Record.size();
4249 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004250 return error("INSERTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004251
Dan Gohman1ecaf452008-05-31 00:58:22 +00004252 SmallVector<unsigned, 4> INSERTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004253 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004254 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004255 bool IsArray = CurTy->isArrayTy();
4256 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00004257 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004258
4259 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004260 return error("INSERTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004261 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004262 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004263 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004264 return error("INSERTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004265 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004266 return error("INSERTVAL: Invalid array index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004267
Dan Gohman1ecaf452008-05-31 00:58:22 +00004268 INSERTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004269 if (IsStruct)
4270 CurTy = CurTy->subtypes()[Index];
4271 else
4272 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00004273 }
4274
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00004275 if (CurTy != Val->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004276 return error("Inserted value type doesn't match aggregate type");
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00004277
Jay Foad57aa6362011-07-13 10:26:04 +00004278 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00004279 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00004280 break;
4281 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004282
Chris Lattnere9759c22007-05-06 00:21:25 +00004283 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00004284 // obsolete form of select
4285 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00004286 unsigned OpNum = 0;
4287 Value *TrueVal, *FalseVal, *Cond;
4288 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004289 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4290 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004291 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004292
Dan Gohmanc5d28922008-09-16 01:01:33 +00004293 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00004294 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00004295 break;
4296 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004297
Dan Gohmanc5d28922008-09-16 01:01:33 +00004298 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4299 // new form of select
4300 // handles select i1 or select [N x i1]
4301 unsigned OpNum = 0;
4302 Value *TrueVal, *FalseVal, *Cond;
4303 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004304 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00004305 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004306 return error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00004307
4308 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00004309 if (VectorType* vector_type =
4310 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00004311 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004312 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004313 return error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00004314 } else {
4315 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004316 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004317 return error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004318 }
4319
Gabor Greife9ecc682008-04-06 20:25:17 +00004320 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00004321 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004322 break;
4323 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004324
Chris Lattner1fc27f02007-05-02 05:16:49 +00004325 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00004326 unsigned OpNum = 0;
4327 Value *Vec, *Idx;
4328 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00004329 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004330 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004331 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004332 return error("Invalid type for value");
Eric Christopherc9742252009-07-25 02:28:41 +00004333 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00004334 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004335 break;
4336 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004337
Chris Lattner1fc27f02007-05-02 05:16:49 +00004338 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00004339 unsigned OpNum = 0;
4340 Value *Vec, *Elt, *Idx;
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004341 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004342 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004343 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004344 return error("Invalid type for value");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004345 if (popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00004346 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00004347 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004348 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00004349 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00004350 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004351 break;
4352 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004353
Chris Lattnere9759c22007-05-06 00:21:25 +00004354 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4355 unsigned OpNum = 0;
4356 Value *Vec1, *Vec2, *Mask;
4357 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004358 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004359 return error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00004360
Mon P Wang25f01062008-11-10 04:46:22 +00004361 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004362 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004363 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004364 return error("Invalid type for value");
Chris Lattner1fc27f02007-05-02 05:16:49 +00004365 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00004366 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004367 break;
4368 }
Mon P Wang25f01062008-11-10 04:46:22 +00004369
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004370 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4371 // Old form of ICmp/FCmp returning bool
4372 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4373 // both legal on vectors but had different behaviour.
4374 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4375 // FCmp/ICmp returning bool or vector of bool
4376
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004377 unsigned OpNum = 0;
4378 Value *LHS, *RHS;
4379 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
James Molloy88eb5352015-07-10 12:52:00 +00004380 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4381 return error("Invalid record");
4382
4383 unsigned PredVal = Record[OpNum];
4384 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4385 FastMathFlags FMF;
4386 if (IsFP && Record.size() > OpNum+1)
4387 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4388
4389 if (OpNum+1 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004390 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004391
Duncan Sands9dff9be2010-02-15 16:12:20 +00004392 if (LHS->getType()->isFPOrFPVectorTy())
James Molloy88eb5352015-07-10 12:52:00 +00004393 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004394 else
James Molloy88eb5352015-07-10 12:52:00 +00004395 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4396
4397 if (FMF.any())
4398 I->setFastMathFlags(FMF);
Devang Patelaf206b82009-09-18 19:26:43 +00004399 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00004400 break;
4401 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004402
Chris Lattnere53603e2007-05-02 04:27:25 +00004403 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00004404 {
4405 unsigned Size = Record.size();
4406 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00004407 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004408 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00004409 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004410 }
Devang Patelbbfd8742008-02-26 01:29:32 +00004411
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004412 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004413 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00004414 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004415 return error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00004416 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004417 return error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004418
Chris Lattnerf1c87102011-06-17 18:09:11 +00004419 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004420 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004421 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00004422 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004423 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00004424 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004425 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004426 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004427 if (!TrueDest)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004428 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004429
Devang Patelaf206b82009-09-18 19:26:43 +00004430 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00004431 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004432 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00004433 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004434 else {
4435 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004436 Value *Cond = getValue(Record, 2, NextValueNo,
4437 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00004438 if (!FalseDest || !Cond)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004439 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00004440 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004441 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004442 }
4443 break;
4444 }
David Majnemerb01aa9f2015-08-23 19:22:31 +00004445 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004446 if (Record.size() != 1 && Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00004447 return error("Invalid record");
4448 unsigned Idx = 0;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004449 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4450 Type::getTokenTy(Context), OC_CleanupPad);
4451 if (!CleanupPad)
David Majnemer654e1302015-07-31 17:58:14 +00004452 return error("Invalid record");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004453 BasicBlock *UnwindDest = nullptr;
4454 if (Record.size() == 2) {
David Majnemer654e1302015-07-31 17:58:14 +00004455 UnwindDest = getBasicBlock(Record[Idx++]);
4456 if (!UnwindDest)
4457 return error("Invalid record");
4458 }
4459
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004460 I = CleanupReturnInst::Create(cast<CleanupPadInst>(CleanupPad),
4461 UnwindDest);
David Majnemer654e1302015-07-31 17:58:14 +00004462 InstructionList.push_back(I);
4463 break;
4464 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004465 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4466 if (Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00004467 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004468 unsigned Idx = 0;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004469 Value *CatchPad = getValue(Record, Idx++, NextValueNo,
4470 Type::getTokenTy(Context), OC_CatchPad);
4471 if (!CatchPad)
4472 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004473 BasicBlock *BB = getBasicBlock(Record[Idx++]);
David Majnemer654e1302015-07-31 17:58:14 +00004474 if (!BB)
4475 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004476
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004477 I = CatchReturnInst::Create(cast<CatchPadInst>(CatchPad), BB);
David Majnemer654e1302015-07-31 17:58:14 +00004478 InstructionList.push_back(I);
4479 break;
4480 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004481 case bitc::FUNC_CODE_INST_CATCHPAD: { // CATCHPAD: [bb#,bb#,num,(ty,val)*]
4482 if (Record.size() < 3)
David Majnemer654e1302015-07-31 17:58:14 +00004483 return error("Invalid record");
4484 unsigned Idx = 0;
David Majnemer654e1302015-07-31 17:58:14 +00004485 BasicBlock *NormalBB = getBasicBlock(Record[Idx++]);
4486 if (!NormalBB)
4487 return error("Invalid record");
4488 BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]);
4489 if (!UnwindBB)
4490 return error("Invalid record");
4491 unsigned NumArgOperands = Record[Idx++];
4492 SmallVector<Value *, 2> Args;
4493 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4494 Value *Val;
4495 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4496 return error("Invalid record");
4497 Args.push_back(Val);
4498 }
4499 if (Record.size() != Idx)
4500 return error("Invalid record");
4501
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004502 I = CatchPadInst::Create(NormalBB, UnwindBB, Args);
David Majnemer654e1302015-07-31 17:58:14 +00004503 InstructionList.push_back(I);
4504 break;
4505 }
4506 case bitc::FUNC_CODE_INST_TERMINATEPAD: { // TERMINATEPAD: [bb#,num,(ty,val)*]
4507 if (Record.size() < 1)
4508 return error("Invalid record");
4509 unsigned Idx = 0;
4510 bool HasUnwindDest = !!Record[Idx++];
4511 BasicBlock *UnwindDest = nullptr;
4512 if (HasUnwindDest) {
4513 if (Idx == Record.size())
4514 return error("Invalid record");
4515 UnwindDest = getBasicBlock(Record[Idx++]);
4516 if (!UnwindDest)
4517 return error("Invalid record");
4518 }
4519 unsigned NumArgOperands = Record[Idx++];
4520 SmallVector<Value *, 2> Args;
4521 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4522 Value *Val;
4523 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4524 return error("Invalid record");
4525 Args.push_back(Val);
4526 }
4527 if (Record.size() != Idx)
4528 return error("Invalid record");
4529
4530 I = TerminatePadInst::Create(Context, UnwindDest, Args);
4531 InstructionList.push_back(I);
4532 break;
4533 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004534 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // CLEANUPPAD: [num,(ty,val)*]
4535 if (Record.size() < 1)
David Majnemer654e1302015-07-31 17:58:14 +00004536 return error("Invalid record");
4537 unsigned Idx = 0;
David Majnemer654e1302015-07-31 17:58:14 +00004538 unsigned NumArgOperands = Record[Idx++];
4539 SmallVector<Value *, 2> Args;
4540 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4541 Value *Val;
4542 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4543 return error("Invalid record");
4544 Args.push_back(Val);
4545 }
4546 if (Record.size() != Idx)
4547 return error("Invalid record");
4548
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004549 I = CleanupPadInst::Create(Context, Args);
David Majnemer654e1302015-07-31 17:58:14 +00004550 InstructionList.push_back(I);
4551 break;
4552 }
4553 case bitc::FUNC_CODE_INST_CATCHENDPAD: { // CATCHENDPADINST: [bb#] or []
4554 if (Record.size() > 1)
4555 return error("Invalid record");
4556 BasicBlock *BB = nullptr;
4557 if (Record.size() == 1) {
4558 BB = getBasicBlock(Record[0]);
4559 if (!BB)
4560 return error("Invalid record");
4561 }
4562 I = CatchEndPadInst::Create(Context, BB);
4563 InstructionList.push_back(I);
4564 break;
4565 }
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00004566 case bitc::FUNC_CODE_INST_CLEANUPENDPAD: { // CLEANUPENDPADINST: [val] or [val,bb#]
4567 if (Record.size() != 1 && Record.size() != 2)
4568 return error("Invalid record");
4569 unsigned Idx = 0;
4570 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
4571 Type::getTokenTy(Context), OC_CleanupPad);
4572 if (!CleanupPad)
4573 return error("Invalid record");
4574
4575 BasicBlock *BB = nullptr;
4576 if (Record.size() == 2) {
4577 BB = getBasicBlock(Record[Idx++]);
4578 if (!BB)
4579 return error("Invalid record");
4580 }
4581 I = CleanupEndPadInst::Create(cast<CleanupPadInst>(CleanupPad), BB);
4582 InstructionList.push_back(I);
4583 break;
4584 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00004585 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004586 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004587 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00004588 // "New" SwitchInst format with case ranges. The changes to write this
4589 // format were reverted but we still recognize bitcode that uses it.
4590 // Hopefully someday we will have support for case ranges and can use
4591 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004592
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004593 Type *OpTy = getTypeByID(Record[1]);
4594 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4595
Jan Wen Voungafaced02012-10-11 20:20:40 +00004596 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004597 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004598 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004599 return error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004600
4601 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004602
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004603 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4604 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004605
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004606 unsigned CurIdx = 5;
4607 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00004608 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004609 unsigned NumItems = Record[CurIdx++];
4610 for (unsigned ci = 0; ci != NumItems; ++ci) {
4611 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004612
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004613 APInt Low;
4614 unsigned ActiveWords = 1;
4615 if (ValueBitWidth > 64)
4616 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004617 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
Benjamin Kramer9704ed02012-05-28 14:10:31 +00004618 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004619 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00004620
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004621 if (!isSingleNumber) {
4622 ActiveWords = 1;
4623 if (ValueBitWidth > 64)
4624 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004625 APInt High = readWideAPInt(
4626 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004627 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00004628
4629 // FIXME: It is not clear whether values in the range should be
4630 // compared as signed or unsigned values. The partially
4631 // implemented changes that used this format in the past used
4632 // unsigned comparisons.
4633 for ( ; Low.ule(High); ++Low)
4634 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004635 } else
Bob Wilsone4077362013-09-09 19:14:35 +00004636 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004637 }
4638 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00004639 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4640 cve = CaseVals.end(); cvi != cve; ++cvi)
4641 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004642 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004643 I = SI;
4644 break;
4645 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004646
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004647 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004648
Chris Lattner5285b5e2007-05-02 05:46:45 +00004649 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004650 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004651 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004652 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004653 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004654 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004655 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004656 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00004657 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00004658 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004659 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004660 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00004661 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4662 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004663 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00004664 delete SI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004665 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004666 }
4667 SI->addCase(CaseVal, DestBB);
4668 }
4669 I = SI;
4670 break;
4671 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004672 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00004673 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004674 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004675 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004676 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00004677 if (!OpTy || !Address)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004678 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004679 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004680 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00004681 InstructionList.push_back(IBI);
4682 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4683 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4684 IBI->addDestination(DestBB);
4685 } else {
4686 delete IBI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004687 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004688 }
4689 }
4690 I = IBI;
4691 break;
4692 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004693
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004694 case bitc::FUNC_CODE_INST_INVOKE: {
4695 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00004696 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004697 return error("Invalid record");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004698 unsigned OpNum = 0;
4699 AttributeSet PAL = getAttributes(Record[OpNum++]);
4700 unsigned CCInfo = Record[OpNum++];
4701 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4702 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004703
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004704 FunctionType *FTy = nullptr;
4705 if (CCInfo >> 13 & 1 &&
4706 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004707 return error("Explicit invoke type is not a function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004708
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004709 Value *Callee;
4710 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004711 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004712
Chris Lattner229907c2011-07-18 04:54:35 +00004713 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004714 if (!CalleeTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004715 return error("Callee is not a pointer");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004716 if (!FTy) {
4717 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4718 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004719 return error("Callee is not of pointer to function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004720 } else if (CalleeTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004721 return error("Explicit invoke type does not match pointee type of "
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004722 "callee operand");
4723 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004724 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004725
Chris Lattner5285b5e2007-05-02 05:46:45 +00004726 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004727 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004728 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4729 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004730 if (!Ops.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004731 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004732 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004733
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004734 if (!FTy->isVarArg()) {
4735 if (Record.size() != OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004736 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004737 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004738 // Read type/value pairs for varargs params.
4739 while (OpNum != Record.size()) {
4740 Value *Op;
4741 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004742 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004743 Ops.push_back(Op);
4744 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004745 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004746
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004747 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4748 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00004749 InstructionList.push_back(I);
Vedant Kumarad6d6e72015-10-27 21:17:06 +00004750 cast<InvokeInst>(I)->setCallingConv(
4751 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00004752 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004753 break;
4754 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00004755 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4756 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004757 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004758 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004759 return error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00004760 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00004761 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004762 break;
4763 }
Chris Lattnere53603e2007-05-02 04:27:25 +00004764 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00004765 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00004766 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004767 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00004768 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00004769 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004770 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004771 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004772 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004773 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004774
Jay Foad52131342011-03-30 11:28:46 +00004775 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00004776 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004777
Chris Lattnere14cb882007-05-04 19:11:41 +00004778 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004779 Value *V;
4780 // With the new function encoding, it is possible that operands have
4781 // negative IDs (for forward references). Use a signed VBR
4782 // representation to keep the encoding small.
4783 if (UseRelativeIDs)
4784 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4785 else
4786 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00004787 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004788 if (!V || !BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004789 return error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00004790 PN->addIncoming(V, BB);
4791 }
4792 I = PN;
4793 break;
4794 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004795
David Majnemer7fddecc2015-06-17 20:52:32 +00004796 case bitc::FUNC_CODE_INST_LANDINGPAD:
4797 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
Bill Wendlingfae14752011-08-12 20:24:12 +00004798 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4799 unsigned Idx = 0;
David Majnemer7fddecc2015-06-17 20:52:32 +00004800 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4801 if (Record.size() < 3)
4802 return error("Invalid record");
4803 } else {
4804 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4805 if (Record.size() < 4)
4806 return error("Invalid record");
4807 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004808 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004809 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004810 return error("Invalid record");
David Majnemer7fddecc2015-06-17 20:52:32 +00004811 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4812 Value *PersFn = nullptr;
4813 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4814 return error("Invalid record");
4815
4816 if (!F->hasPersonalityFn())
4817 F->setPersonalityFn(cast<Constant>(PersFn));
4818 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4819 return error("Personality function mismatch");
4820 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004821
4822 bool IsCleanup = !!Record[Idx++];
4823 unsigned NumClauses = Record[Idx++];
David Majnemer7fddecc2015-06-17 20:52:32 +00004824 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
Bill Wendlingfae14752011-08-12 20:24:12 +00004825 LP->setCleanup(IsCleanup);
4826 for (unsigned J = 0; J != NumClauses; ++J) {
4827 LandingPadInst::ClauseType CT =
4828 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4829 Value *Val;
4830
4831 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4832 delete LP;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004833 return error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00004834 }
4835
4836 assert((CT != LandingPadInst::Catch ||
4837 !isa<ArrayType>(Val->getType())) &&
4838 "Catch clause has a invalid type!");
4839 assert((CT != LandingPadInst::Filter ||
4840 isa<ArrayType>(Val->getType())) &&
4841 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004842 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00004843 }
4844
4845 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00004846 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00004847 break;
4848 }
4849
Chris Lattnerf1c87102011-06-17 18:09:11 +00004850 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4851 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004852 return error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00004853 uint64_t AlignRecord = Record[3];
4854 const uint64_t InAllocaMask = uint64_t(1) << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00004855 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
Bob Wilson043ee652015-07-28 04:05:45 +00004856 // Reserve bit 7 for SwiftError flag.
4857 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
David Blaikiebdb49102015-04-28 16:51:01 +00004858 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
JF Bastien30bf96b2015-02-22 19:32:03 +00004859 bool InAlloca = AlignRecord & InAllocaMask;
David Blaikiebdb49102015-04-28 16:51:01 +00004860 Type *Ty = getTypeByID(Record[0]);
4861 if ((AlignRecord & ExplicitTypeMask) == 0) {
4862 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4863 if (!PTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004864 return error("Old-style alloca with a non-pointer type");
David Blaikiebdb49102015-04-28 16:51:01 +00004865 Ty = PTy->getElementType();
4866 }
4867 Type *OpTy = getTypeByID(Record[1]);
4868 Value *Size = getFnValueByID(Record[2], OpTy);
JF Bastien30bf96b2015-02-22 19:32:03 +00004869 unsigned Align;
4870 if (std::error_code EC =
David Blaikiebdb49102015-04-28 16:51:01 +00004871 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
JF Bastien30bf96b2015-02-22 19:32:03 +00004872 return EC;
4873 }
Rafael Espindola48da4f42013-11-04 16:16:24 +00004874 if (!Ty || !Size)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004875 return error("Invalid record");
David Blaikiebdb49102015-04-28 16:51:01 +00004876 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00004877 AI->setUsedWithInAlloca(InAlloca);
4878 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00004879 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00004880 break;
4881 }
Chris Lattner9f600c52007-05-03 22:04:19 +00004882 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004883 unsigned OpNum = 0;
4884 Value *Op;
4885 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004886 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004887 return error("Invalid record");
David Blaikie85035652015-02-25 01:07:20 +00004888
4889 Type *Ty = nullptr;
4890 if (OpNum + 3 == Record.size())
4891 Ty = getTypeByID(Record[OpNum++]);
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004892 if (std::error_code EC =
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004893 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004894 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00004895 if (!Ty)
4896 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004897
JF Bastien30bf96b2015-02-22 19:32:03 +00004898 unsigned Align;
4899 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4900 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00004901 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
David Blaikie85035652015-02-25 01:07:20 +00004902
Devang Patelaf206b82009-09-18 19:26:43 +00004903 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00004904 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00004905 }
Eli Friedman59b66882011-08-09 23:02:53 +00004906 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4907 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4908 unsigned OpNum = 0;
4909 Value *Op;
4910 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004911 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004912 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004913
David Blaikie85035652015-02-25 01:07:20 +00004914 Type *Ty = nullptr;
4915 if (OpNum + 5 == Record.size())
4916 Ty = getTypeByID(Record[OpNum++]);
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004917 if (std::error_code EC =
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004918 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004919 return EC;
4920 if (!Ty)
4921 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004922
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004923 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman59b66882011-08-09 23:02:53 +00004924 if (Ordering == NotAtomic || Ordering == Release ||
4925 Ordering == AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004926 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004927 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004928 return error("Invalid record");
4929 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00004930
JF Bastien30bf96b2015-02-22 19:32:03 +00004931 unsigned Align;
4932 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4933 return EC;
4934 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
David Blaikie85035652015-02-25 01:07:20 +00004935
Eli Friedman59b66882011-08-09 23:02:53 +00004936 InstructionList.push_back(I);
4937 break;
4938 }
David Blaikie612ddbf2015-04-22 04:14:42 +00004939 case bitc::FUNC_CODE_INST_STORE:
4940 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004941 unsigned OpNum = 0;
4942 Value *Val, *Ptr;
4943 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie612ddbf2015-04-22 04:14:42 +00004944 (BitCode == bitc::FUNC_CODE_INST_STORE
4945 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4946 : popValue(Record, OpNum, NextValueNo,
4947 cast<PointerType>(Ptr->getType())->getElementType(),
4948 Val)) ||
4949 OpNum + 2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004950 return error("Invalid record");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004951
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004952 if (std::error_code EC = typeCheckLoadStoreInst(
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004953 DiagnosticHandler, Val->getType(), Ptr->getType()))
4954 return EC;
JF Bastien30bf96b2015-02-22 19:32:03 +00004955 unsigned Align;
4956 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4957 return EC;
4958 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
Devang Patelaf206b82009-09-18 19:26:43 +00004959 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004960 break;
4961 }
David Blaikie50a06152015-04-22 04:14:46 +00004962 case bitc::FUNC_CODE_INST_STOREATOMIC:
4963 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
Eli Friedman59b66882011-08-09 23:02:53 +00004964 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4965 unsigned OpNum = 0;
4966 Value *Val, *Ptr;
4967 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie50a06152015-04-22 04:14:46 +00004968 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4969 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4970 : popValue(Record, OpNum, NextValueNo,
4971 cast<PointerType>(Ptr->getType())->getElementType(),
4972 Val)) ||
4973 OpNum + 4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004974 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004975
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004976 if (std::error_code EC = typeCheckLoadStoreInst(
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004977 DiagnosticHandler, Val->getType(), Ptr->getType()))
4978 return EC;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004979 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman222b5a42011-09-19 19:41:28 +00004980 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman59b66882011-08-09 23:02:53 +00004981 Ordering == AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004982 return error("Invalid record");
4983 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00004984 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004985 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004986
JF Bastien30bf96b2015-02-22 19:32:03 +00004987 unsigned Align;
4988 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4989 return EC;
4990 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
Eli Friedman59b66882011-08-09 23:02:53 +00004991 InstructionList.push_back(I);
4992 break;
4993 }
David Blaikie2a661cd2015-04-28 04:30:29 +00004994 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004995 case bitc::FUNC_CODE_INST_CMPXCHG: {
Tim Northovere94a5182014-03-11 10:48:52 +00004996 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
Tim Northover420a2162014-06-13 14:24:07 +00004997 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004998 unsigned OpNum = 0;
4999 Value *Ptr, *Cmp, *New;
5000 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie2a661cd2015-04-28 04:30:29 +00005001 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
5002 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
5003 : popValue(Record, OpNum, NextValueNo,
5004 cast<PointerType>(Ptr->getType())->getElementType(),
5005 Cmp)) ||
5006 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
5007 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005008 return error("Invalid record");
5009 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
Tim Northovere94a5182014-03-11 10:48:52 +00005010 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005011 return error("Invalid record");
5012 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
Tim Northovere94a5182014-03-11 10:48:52 +00005013
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005014 if (std::error_code EC = typeCheckLoadStoreInst(
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005015 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
5016 return EC;
Tim Northovere94a5182014-03-11 10:48:52 +00005017 AtomicOrdering FailureOrdering;
5018 if (Record.size() < 7)
5019 FailureOrdering =
5020 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
5021 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005022 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
Tim Northovere94a5182014-03-11 10:48:52 +00005023
5024 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
5025 SynchScope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005026 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00005027
5028 if (Record.size() < 8) {
5029 // Before weak cmpxchgs existed, the instruction simply returned the
5030 // value loaded from memory, so bitcode files from that era will be
5031 // expecting the first component of a modern cmpxchg.
5032 CurBB->getInstList().push_back(I);
5033 I = ExtractValueInst::Create(I, 0);
5034 } else {
5035 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
5036 }
5037
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005038 InstructionList.push_back(I);
5039 break;
5040 }
5041 case bitc::FUNC_CODE_INST_ATOMICRMW: {
5042 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
5043 unsigned OpNum = 0;
5044 Value *Ptr, *Val;
5045 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00005046 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005047 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
5048 OpNum+4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005049 return error("Invalid record");
5050 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005051 if (Operation < AtomicRMWInst::FIRST_BINOP ||
5052 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005053 return error("Invalid record");
5054 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman59b66882011-08-09 23:02:53 +00005055 if (Ordering == NotAtomic || Ordering == Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005056 return error("Invalid record");
5057 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005058 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
5059 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
5060 InstructionList.push_back(I);
5061 break;
5062 }
Eli Friedmanfee02c62011-07-25 23:16:38 +00005063 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
5064 if (2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005065 return error("Invalid record");
5066 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005067 if (Ordering == NotAtomic || Ordering == Unordered ||
5068 Ordering == Monotonic)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005069 return error("Invalid record");
5070 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005071 I = new FenceInst(Context, Ordering, SynchScope);
5072 InstructionList.push_back(I);
5073 break;
5074 }
Chris Lattnerc44070802011-06-17 18:17:37 +00005075 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00005076 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
5077 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005078 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005079
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005080 unsigned OpNum = 0;
5081 AttributeSet PAL = getAttributes(Record[OpNum++]);
5082 unsigned CCInfo = Record[OpNum++];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005083
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005084 FunctionType *FTy = nullptr;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005085 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005086 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005087 return error("Explicit call type is not a function type");
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005088
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005089 Value *Callee;
5090 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005091 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005092
Chris Lattner229907c2011-07-18 04:54:35 +00005093 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005094 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005095 return error("Callee is not a pointer type");
David Blaikie348de692015-04-23 21:36:23 +00005096 if (!FTy) {
5097 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5098 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005099 return error("Callee is not of pointer to function type");
David Blaikie348de692015-04-23 21:36:23 +00005100 } else if (OpTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005101 return error("Explicit call type does not match pointee type of "
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005102 "callee operand");
5103 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005104 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005105
Chris Lattner9f600c52007-05-03 22:04:19 +00005106 SmallVector<Value*, 16> Args;
5107 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005108 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005109 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00005110 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00005111 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00005112 Args.push_back(getValue(Record, OpNum, NextValueNo,
5113 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00005114 if (!Args.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005115 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005116 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005117
Chris Lattner9f600c52007-05-03 22:04:19 +00005118 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00005119 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005120 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005121 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005122 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005123 while (OpNum != Record.size()) {
5124 Value *Op;
5125 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005126 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005127 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00005128 }
5129 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005130
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005131 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5132 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00005133 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00005134 cast<CallInst>(I)->setCallingConv(
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005135 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
Reid Kleckner5772b772014-04-24 20:14:34 +00005136 CallInst::TailCallKind TCK = CallInst::TCK_None;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005137 if (CCInfo & 1 << bitc::CALL_TAIL)
Reid Kleckner5772b772014-04-24 20:14:34 +00005138 TCK = CallInst::TCK_Tail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005139 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
Reid Kleckner5772b772014-04-24 20:14:34 +00005140 TCK = CallInst::TCK_MustTail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005141 if (CCInfo & (1 << bitc::CALL_NOTAIL))
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005142 TCK = CallInst::TCK_NoTail;
Reid Kleckner5772b772014-04-24 20:14:34 +00005143 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00005144 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner9f600c52007-05-03 22:04:19 +00005145 break;
5146 }
5147 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5148 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005149 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00005150 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00005151 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00005152 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00005153 if (!OpTy || !Op || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005154 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005155 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00005156 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00005157 break;
5158 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005159
5160 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5161 // A call or an invoke can be optionally prefixed with some variable
5162 // number of operand bundle blocks. These blocks are read into
5163 // OperandBundles and consumed at the next call or invoke instruction.
5164
5165 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5166 return error("Invalid record");
5167
Sanjoy Dasf79d3442015-11-18 08:30:07 +00005168 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005169
5170 unsigned OpNum = 1;
5171 while (OpNum != Record.size()) {
5172 Value *Op;
5173 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5174 return error("Invalid record");
5175 Inputs.push_back(Op);
5176 }
5177
Sanjoy Dasf79d3442015-11-18 08:30:07 +00005178 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005179 continue;
5180 }
Chris Lattner83930552007-05-01 07:01:57 +00005181 }
5182
5183 // Add instruction to end of current BB. If there is no current BB, reject
5184 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00005185 if (!CurBB) {
Chris Lattner83930552007-05-01 07:01:57 +00005186 delete I;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005187 return error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00005188 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005189 if (!OperandBundles.empty()) {
5190 delete I;
5191 return error("Operand bundles found with no consumer");
5192 }
Chris Lattner83930552007-05-01 07:01:57 +00005193 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005194
Chris Lattner83930552007-05-01 07:01:57 +00005195 // If this was a terminator instruction, move to the next block.
5196 if (isa<TerminatorInst>(I)) {
5197 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00005198 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00005199 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005200
Chris Lattner83930552007-05-01 07:01:57 +00005201 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00005202 if (I && !I->getType()->isVoidTy())
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00005203 if (ValueList.assignValue(I, NextValueNo++))
5204 return error("Invalid forward reference");
Chris Lattner85b7b402007-05-01 05:52:21 +00005205 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005206
Chris Lattner27d38752013-01-20 02:13:19 +00005207OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00005208
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005209 if (!OperandBundles.empty())
5210 return error("Operand bundles found with no consumer");
5211
Chris Lattner83930552007-05-01 07:01:57 +00005212 // Check the function list for unresolved values.
5213 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005214 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00005215 // We found at least one unresolved value. Nuke them all to avoid leaks.
5216 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00005217 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00005218 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00005219 delete A;
5220 }
5221 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005222 return error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00005223 }
Chris Lattner83930552007-05-01 07:01:57 +00005224 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005225
Dan Gohman9b9ff462010-08-25 20:23:38 +00005226 // FIXME: Check for unresolved forward-declared metadata references
5227 // and clean up leaks.
5228
Chris Lattner85b7b402007-05-01 05:52:21 +00005229 // Trim the value list down to the size it was before we parsed this function.
5230 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman26d837d2010-08-25 20:22:53 +00005231 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00005232 std::vector<BasicBlock*>().swap(FunctionBBs);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005233 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00005234}
5235
Rafael Espindola7d712032013-11-05 17:16:08 +00005236/// Find the function body in the bitcode stream
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005237std::error_code BitcodeReader::findFunctionInStream(
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005238 Function *F,
5239 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005240 while (DeferredFunctionInfoIterator->second == 0) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00005241 // This is the fallback handling for the old format bitcode that
Teresa Johnson1493ad92015-10-10 14:18:36 +00005242 // didn't contain the function index in the VST, or when we have
5243 // an anonymous function which would not have a VST entry.
5244 // Assert that we have one of those two cases.
5245 assert(VSTOffset == 0 || !F->hasName());
5246 // Parse the next body in the stream and set its position in the
5247 // DeferredFunctionInfo map.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005248 if (std::error_code EC = rememberAndSkipFunctionBodies())
5249 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005250 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005251 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005252}
5253
Chris Lattner9eeada92007-05-18 04:02:46 +00005254//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005255// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00005256//===----------------------------------------------------------------------===//
5257
Rafael Espindolac3f9b5a2014-06-23 21:53:12 +00005258void BitcodeReader::releaseBuffer() { Buffer.release(); }
Chris Lattner9eeada92007-05-18 04:02:46 +00005259
Rafael Espindola5a52e6d2014-10-24 22:50:48 +00005260std::error_code BitcodeReader::materialize(GlobalValue *GV) {
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00005261 // In older bitcode we must materialize the metadata before parsing
5262 // any functions, in order to set up the MDValueList properly.
5263 if (!SeenModuleValuesRecord) {
5264 if (std::error_code EC = materializeMetadata())
5265 return EC;
5266 }
Manman Ren4a9b0eb2015-03-13 19:24:30 +00005267
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005268 Function *F = dyn_cast<Function>(GV);
5269 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005270 if (!F || !F->isMaterializable())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005271 return std::error_code();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005272
5273 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00005274 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005275 // If its position is recorded as 0, its body is somewhere in the stream
5276 // but we haven't seen it yet.
Rafael Espindola1c863ca2015-06-22 18:06:15 +00005277 if (DFII->second == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005278 if (std::error_code EC = findFunctionInStream(F, DFII))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005279 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005280
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005281 // Move the bit stream to the saved position of the deferred function body.
5282 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005283
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005284 if (std::error_code EC = parseFunctionBody(F))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005285 return EC;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00005286 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00005287
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00005288 if (StripDebugInfo)
5289 stripDebugInfo(*F);
5290
Chandler Carruth7132e002007-08-04 01:51:18 +00005291 // Upgrade any old intrinsic calls in the function.
Rafael Espindola86e33402015-07-02 15:55:09 +00005292 for (auto &I : UpgradedIntrinsics) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005293 for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
5294 User *U = *UI;
5295 ++UI;
5296 if (CallInst *CI = dyn_cast<CallInst>(U))
5297 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00005298 }
5299 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005300
Peter Collingbourned4bff302015-11-05 22:03:56 +00005301 // Finish fn->subprogram upgrade for materialized functions.
5302 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5303 F->setSubprogram(SP);
5304
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005305 // Bring in any functions that this function forward-referenced via
5306 // blockaddresses.
5307 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00005308}
5309
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005310bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
5311 const Function *F = dyn_cast<Function>(GV);
5312 if (!F || F->isDeclaration())
5313 return false;
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005314
5315 // Dematerializing F would leave dangling references that wouldn't be
5316 // reconnected on re-materialization.
5317 if (BlockAddressesTaken.count(F))
5318 return false;
5319
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005320 return DeferredFunctionInfo.count(const_cast<Function*>(F));
5321}
5322
Eric Christopher97cb5652015-05-15 18:20:14 +00005323void BitcodeReader::dematerialize(GlobalValue *GV) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005324 Function *F = dyn_cast<Function>(GV);
5325 // If this function isn't dematerializable, this is a noop.
5326 if (!F || !isDematerializable(F))
Chris Lattner9eeada92007-05-18 04:02:46 +00005327 return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005328
Chris Lattner9eeada92007-05-18 04:02:46 +00005329 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005330
Chris Lattner9eeada92007-05-18 04:02:46 +00005331 // Just forget the function body, we can remat it later.
Petar Jovanovic7480e4d2014-09-23 12:54:19 +00005332 F->dropAllReferences();
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00005333 F->setIsMaterializable(true);
Chris Lattner9eeada92007-05-18 04:02:46 +00005334}
5335
Eric Christopher97cb5652015-05-15 18:20:14 +00005336std::error_code BitcodeReader::materializeModule(Module *M) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005337 assert(M == TheModule &&
5338 "Can only Materialize the Module this BitcodeReader is attached to.");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005339
Manman Ren4a9b0eb2015-03-13 19:24:30 +00005340 if (std::error_code EC = materializeMetadata())
5341 return EC;
5342
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005343 // Promise to materialize all forward references.
5344 WillMaterializeAllForwardRefs = true;
5345
Chris Lattner06310bf2009-06-16 05:15:21 +00005346 // Iterate over the module, deserializing any functions that are still on
5347 // disk.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00005348 for (Function &F : *TheModule) {
5349 if (std::error_code EC = materialize(&F))
Rafael Espindola246c4fb2014-11-01 16:46:18 +00005350 return EC;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005351 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00005352 // At this point, if there are any function bodies, parse the rest of
5353 // the bits in the module past the last function block we have recorded
5354 // through either lazy scanning or the VST.
5355 if (LastFunctionBlockBit || NextUnreadBit)
5356 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5357 : NextUnreadBit);
Derek Schuff92ef9752012-02-29 00:07:09 +00005358
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005359 // Check that all block address forward references got resolved (as we
5360 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00005361 if (!BasicBlockFwdRefs.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005362 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005363
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005364 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5365 // delete the old functions to clean up. We can't do this unless the entire
5366 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00005367 // with calls to the old function.
Rafael Espindola86e33402015-07-02 15:55:09 +00005368 for (auto &I : UpgradedIntrinsics) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005369 for (auto *U : I.first->users()) {
5370 if (CallInst *CI = dyn_cast<CallInst>(U))
5371 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00005372 }
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005373 if (!I.first->use_empty())
5374 I.first->replaceAllUsesWith(I.second);
5375 I.first->eraseFromParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00005376 }
Rafael Espindola4e721212015-07-02 16:22:40 +00005377 UpgradedIntrinsics.clear();
Devang Patel80ae3492009-08-28 23:24:31 +00005378
Manman Ren209b17c2013-09-28 00:22:27 +00005379 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5380 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5381
Manman Ren8b4306c2013-12-02 21:29:56 +00005382 UpgradeDebugInfo(*M);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005383 return std::error_code();
Chris Lattner9eeada92007-05-18 04:02:46 +00005384}
5385
Rafael Espindola2fa1e432014-12-03 07:18:23 +00005386std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5387 return IdentifiedStructTypes;
5388}
5389
Rafael Espindola1aabf982015-06-16 23:29:49 +00005390std::error_code
5391BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
Rafael Espindola4223a1f2015-06-15 20:08:17 +00005392 if (Streamer)
Rafael Espindola1aabf982015-06-16 23:29:49 +00005393 return initLazyStream(std::move(Streamer));
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005394 return initStreamFromBuffer();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005395}
5396
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005397std::error_code BitcodeReader::initStreamFromBuffer() {
Roman Divacky4717a8d2012-09-06 15:42:13 +00005398 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005399 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5400
Rafael Espindola27435252014-07-29 21:01:24 +00005401 if (Buffer->getBufferSize() & 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005402 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005403
5404 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5405 // The magic number is 0x0B17C0DE stored in little endian.
5406 if (isBitcodeWrapper(BufPtr, BufEnd))
5407 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005408 return error("Invalid bitcode wrapper header");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005409
5410 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00005411 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005412
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005413 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005414}
5415
Rafael Espindola1aabf982015-06-16 23:29:49 +00005416std::error_code
5417BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005418 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5419 // see it.
Rafael Espindola1aabf982015-06-16 23:29:49 +00005420 auto OwnedBytes =
5421 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
Rafael Espindola7d727b52014-12-18 05:08:43 +00005422 StreamingMemoryObject &Bytes = *OwnedBytes;
Yaron Keren06d69302014-12-18 10:03:35 +00005423 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00005424 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005425
5426 unsigned char buf[16];
Rafael Espindola7d727b52014-12-18 05:08:43 +00005427 if (Bytes.readBytes(buf, 16, 0) != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005428 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005429
5430 if (!isBitcode(buf, buf + 16))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005431 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005432
5433 if (isBitcodeWrapper(buf, buf + 4)) {
5434 const unsigned char *bitcodeStart = buf;
5435 const unsigned char *bitcodeEnd = buf + 16;
5436 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
Rafael Espindola7d727b52014-12-18 05:08:43 +00005437 Bytes.dropLeadingBytes(bitcodeStart - buf);
5438 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005439 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005440 return std::error_code();
Rafael Espindola48da4f42013-11-04 16:16:24 +00005441}
5442
Teresa Johnson403a7872015-10-04 14:33:43 +00005443std::error_code FunctionIndexBitcodeReader::error(BitcodeError E,
5444 const Twine &Message) {
5445 return ::error(DiagnosticHandler, make_error_code(E), Message);
5446}
5447
5448std::error_code FunctionIndexBitcodeReader::error(const Twine &Message) {
5449 return ::error(DiagnosticHandler,
5450 make_error_code(BitcodeError::CorruptedBitcode), Message);
5451}
5452
5453std::error_code FunctionIndexBitcodeReader::error(BitcodeError E) {
5454 return ::error(DiagnosticHandler, make_error_code(E));
5455}
5456
5457FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
Mehdi Amini354f5202015-11-19 05:52:29 +00005458 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
5459 bool IsLazy, bool CheckFuncSummaryPresenceOnly)
5460 : DiagnosticHandler(DiagnosticHandler), Buffer(Buffer), IsLazy(IsLazy),
Teresa Johnson403a7872015-10-04 14:33:43 +00005461 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5462
5463FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
Mehdi Amini354f5202015-11-19 05:52:29 +00005464 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
5465 bool CheckFuncSummaryPresenceOnly)
5466 : DiagnosticHandler(DiagnosticHandler), Buffer(nullptr), IsLazy(IsLazy),
Teresa Johnson403a7872015-10-04 14:33:43 +00005467 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5468
5469void FunctionIndexBitcodeReader::freeState() { Buffer = nullptr; }
5470
5471void FunctionIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5472
5473// Specialized value symbol table parser used when reading function index
5474// blocks where we don't actually create global values.
5475// At the end of this routine the function index is populated with a map
5476// from function name to FunctionInfo. The function info contains
5477// the function block's bitcode offset as well as the offset into the
5478// function summary section.
5479std::error_code FunctionIndexBitcodeReader::parseValueSymbolTable() {
5480 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5481 return error("Invalid record");
5482
5483 SmallVector<uint64_t, 64> Record;
5484
5485 // Read all the records for this value table.
5486 SmallString<128> ValueName;
5487 while (1) {
5488 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5489
5490 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005491 case BitstreamEntry::SubBlock: // Handled for us already.
5492 case BitstreamEntry::Error:
5493 return error("Malformed block");
5494 case BitstreamEntry::EndBlock:
5495 return std::error_code();
5496 case BitstreamEntry::Record:
5497 // The interesting case.
5498 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005499 }
5500
5501 // Read a record.
5502 Record.clear();
5503 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005504 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5505 break;
5506 case bitc::VST_CODE_FNENTRY: {
5507 // VST_FNENTRY: [valueid, offset, namechar x N]
5508 if (convertToString(Record, 2, ValueName))
5509 return error("Invalid record");
5510 unsigned ValueID = Record[0];
5511 uint64_t FuncOffset = Record[1];
5512 std::unique_ptr<FunctionInfo> FuncInfo =
5513 llvm::make_unique<FunctionInfo>(FuncOffset);
5514 if (foundFuncSummary() && !IsLazy) {
5515 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5516 SummaryMap.find(ValueID);
5517 assert(SMI != SummaryMap.end() && "Summary info not found");
5518 FuncInfo->setFunctionSummary(std::move(SMI->second));
Teresa Johnson403a7872015-10-04 14:33:43 +00005519 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005520 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
Teresa Johnson403a7872015-10-04 14:33:43 +00005521
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005522 ValueName.clear();
5523 break;
5524 }
5525 case bitc::VST_CODE_COMBINED_FNENTRY: {
5526 // VST_FNENTRY: [offset, namechar x N]
5527 if (convertToString(Record, 1, ValueName))
5528 return error("Invalid record");
5529 uint64_t FuncSummaryOffset = Record[0];
5530 std::unique_ptr<FunctionInfo> FuncInfo =
5531 llvm::make_unique<FunctionInfo>(FuncSummaryOffset);
5532 if (foundFuncSummary() && !IsLazy) {
5533 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5534 SummaryMap.find(FuncSummaryOffset);
5535 assert(SMI != SummaryMap.end() && "Summary info not found");
5536 FuncInfo->setFunctionSummary(std::move(SMI->second));
Teresa Johnson403a7872015-10-04 14:33:43 +00005537 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005538 TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5539
5540 ValueName.clear();
5541 break;
5542 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005543 }
5544 }
5545}
5546
5547// Parse just the blocks needed for function index building out of the module.
5548// At the end of this routine the function Index is populated with a map
5549// from function name to FunctionInfo. The function info contains
5550// either the parsed function summary information (when parsing summaries
5551// eagerly), or just to the function summary record's offset
5552// if parsing lazily (IsLazy).
5553std::error_code FunctionIndexBitcodeReader::parseModule() {
5554 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5555 return error("Invalid record");
5556
5557 // Read the function index for this module.
5558 while (1) {
5559 BitstreamEntry Entry = Stream.advance();
5560
5561 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005562 case BitstreamEntry::Error:
5563 return error("Malformed block");
5564 case BitstreamEntry::EndBlock:
5565 return std::error_code();
5566
5567 case BitstreamEntry::SubBlock:
5568 if (CheckFuncSummaryPresenceOnly) {
Teresa Johnson6290dbc2015-11-21 21:55:48 +00005569 if (Entry.ID == bitc::FUNCTION_SUMMARY_BLOCK_ID) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005570 SeenFuncSummary = true;
Teresa Johnson6290dbc2015-11-21 21:55:48 +00005571 // No need to parse the rest since we found the summary.
5572 return std::error_code();
5573 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005574 if (Stream.SkipBlock())
5575 return error("Invalid record");
Teresa Johnson6290dbc2015-11-21 21:55:48 +00005576 continue;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005577 }
5578 switch (Entry.ID) {
5579 default: // Skip unknown content.
5580 if (Stream.SkipBlock())
5581 return error("Invalid record");
5582 break;
5583 case bitc::BLOCKINFO_BLOCK_ID:
5584 // Need to parse these to get abbrev ids (e.g. for VST)
5585 if (Stream.ReadBlockInfoBlock())
5586 return error("Malformed block");
5587 break;
5588 case bitc::VALUE_SYMTAB_BLOCK_ID:
5589 if (std::error_code EC = parseValueSymbolTable())
5590 return EC;
5591 break;
5592 case bitc::FUNCTION_SUMMARY_BLOCK_ID:
5593 SeenFuncSummary = true;
5594 if (IsLazy) {
5595 // Lazy parsing of summary info, skip it.
5596 if (Stream.SkipBlock())
5597 return error("Invalid record");
5598 } else if (std::error_code EC = parseEntireSummary())
5599 return EC;
5600 break;
5601 case bitc::MODULE_STRTAB_BLOCK_ID:
5602 if (std::error_code EC = parseModuleStringTable())
5603 return EC;
5604 break;
5605 }
5606 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00005607
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005608 case BitstreamEntry::Record:
5609 Stream.skipRecord(Entry.ID);
5610 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00005611 }
5612 }
5613}
5614
5615// Eagerly parse the entire function summary block (i.e. for all functions
5616// in the index). This populates the FunctionSummary objects in
5617// the index.
5618std::error_code FunctionIndexBitcodeReader::parseEntireSummary() {
5619 if (Stream.EnterSubBlock(bitc::FUNCTION_SUMMARY_BLOCK_ID))
5620 return error("Invalid record");
5621
5622 SmallVector<uint64_t, 64> Record;
5623
5624 while (1) {
5625 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5626
5627 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005628 case BitstreamEntry::SubBlock: // Handled for us already.
5629 case BitstreamEntry::Error:
5630 return error("Malformed block");
5631 case BitstreamEntry::EndBlock:
5632 return std::error_code();
5633 case BitstreamEntry::Record:
5634 // The interesting case.
5635 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005636 }
5637
5638 // Read a record. The record format depends on whether this
5639 // is a per-module index or a combined index file. In the per-module
5640 // case the records contain the associated value's ID for correlation
5641 // with VST entries. In the combined index the correlation is done
5642 // via the bitcode offset of the summary records (which were saved
5643 // in the combined index VST entries). The records also contain
5644 // information used for ThinLTO renaming and importing.
5645 Record.clear();
5646 uint64_t CurRecordBit = Stream.GetCurrentBitNo();
5647 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005648 default: // Default behavior: ignore.
5649 break;
5650 // FS_PERMODULE_ENTRY: [valueid, islocal, instcount]
5651 case bitc::FS_CODE_PERMODULE_ENTRY: {
5652 unsigned ValueID = Record[0];
5653 bool IsLocal = Record[1];
5654 unsigned InstCount = Record[2];
5655 std::unique_ptr<FunctionSummary> FS =
5656 llvm::make_unique<FunctionSummary>(InstCount);
5657 FS->setLocalFunction(IsLocal);
5658 // The module path string ref set in the summary must be owned by the
5659 // index's module string table. Since we don't have a module path
5660 // string table section in the per-module index, we create a single
5661 // module path string table entry with an empty (0) ID to take
5662 // ownership.
5663 FS->setModulePath(
5664 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0));
5665 SummaryMap[ValueID] = std::move(FS);
5666 }
5667 // FS_COMBINED_ENTRY: [modid, instcount]
5668 case bitc::FS_CODE_COMBINED_ENTRY: {
5669 uint64_t ModuleId = Record[0];
5670 unsigned InstCount = Record[1];
5671 std::unique_ptr<FunctionSummary> FS =
5672 llvm::make_unique<FunctionSummary>(InstCount);
5673 FS->setModulePath(ModuleIdMap[ModuleId]);
5674 SummaryMap[CurRecordBit] = std::move(FS);
5675 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005676 }
5677 }
5678 llvm_unreachable("Exit infinite loop");
5679}
5680
5681// Parse the module string table block into the Index.
5682// This populates the ModulePathStringTable map in the index.
5683std::error_code FunctionIndexBitcodeReader::parseModuleStringTable() {
5684 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5685 return error("Invalid record");
5686
5687 SmallVector<uint64_t, 64> Record;
5688
5689 SmallString<128> ModulePath;
5690 while (1) {
5691 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5692
5693 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005694 case BitstreamEntry::SubBlock: // Handled for us already.
5695 case BitstreamEntry::Error:
5696 return error("Malformed block");
5697 case BitstreamEntry::EndBlock:
5698 return std::error_code();
5699 case BitstreamEntry::Record:
5700 // The interesting case.
5701 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005702 }
5703
5704 Record.clear();
5705 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005706 default: // Default behavior: ignore.
5707 break;
5708 case bitc::MST_CODE_ENTRY: {
5709 // MST_ENTRY: [modid, namechar x N]
5710 if (convertToString(Record, 1, ModulePath))
5711 return error("Invalid record");
5712 uint64_t ModuleId = Record[0];
5713 StringRef ModulePathInMap = TheIndex->addModulePath(ModulePath, ModuleId);
5714 ModuleIdMap[ModuleId] = ModulePathInMap;
5715 ModulePath.clear();
5716 break;
5717 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005718 }
5719 }
5720 llvm_unreachable("Exit infinite loop");
5721}
5722
5723// Parse the function info index from the bitcode streamer into the given index.
5724std::error_code FunctionIndexBitcodeReader::parseSummaryIndexInto(
5725 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I) {
5726 TheIndex = I;
5727
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005728 if (std::error_code EC = initStream(std::move(Streamer)))
5729 return EC;
Teresa Johnson403a7872015-10-04 14:33:43 +00005730
5731 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005732 if (!hasValidBitcodeHeader(Stream))
5733 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00005734
5735 // We expect a number of well-defined blocks, though we don't necessarily
5736 // need to understand them all.
5737 while (1) {
5738 if (Stream.AtEndOfStream()) {
5739 // We didn't really read a proper Module block.
5740 return error("Malformed block");
5741 }
5742
5743 BitstreamEntry Entry =
5744 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
5745
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005746 if (Entry.Kind != BitstreamEntry::SubBlock)
5747 return error("Malformed block");
Teresa Johnson403a7872015-10-04 14:33:43 +00005748
5749 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
5750 // building the function summary index.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005751 if (Entry.ID == bitc::MODULE_BLOCK_ID)
5752 return parseModule();
Teresa Johnson403a7872015-10-04 14:33:43 +00005753
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005754 if (Stream.SkipBlock())
5755 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00005756 }
5757}
5758
5759// Parse the function information at the given offset in the buffer into
5760// the index. Used to support lazy parsing of function summaries from the
5761// combined index during importing.
5762// TODO: This function is not yet complete as it won't have a consumer
5763// until ThinLTO function importing is added.
5764std::error_code FunctionIndexBitcodeReader::parseFunctionSummary(
5765 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I,
5766 size_t FunctionSummaryOffset) {
5767 TheIndex = I;
5768
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005769 if (std::error_code EC = initStream(std::move(Streamer)))
5770 return EC;
Teresa Johnson403a7872015-10-04 14:33:43 +00005771
5772 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005773 if (!hasValidBitcodeHeader(Stream))
5774 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00005775
5776 Stream.JumpToBit(FunctionSummaryOffset);
5777
5778 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5779
5780 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005781 default:
5782 return error("Malformed block");
5783 case BitstreamEntry::Record:
5784 // The expected case.
5785 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005786 }
5787
5788 // TODO: Read a record. This interface will be completed when ThinLTO
5789 // importing is added so that it can be tested.
5790 SmallVector<uint64_t, 64> Record;
5791 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005792 case bitc::FS_CODE_COMBINED_ENTRY:
5793 default:
5794 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00005795 }
5796
5797 return std::error_code();
5798}
5799
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005800std::error_code
5801FunctionIndexBitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5802 if (Streamer)
5803 return initLazyStream(std::move(Streamer));
Teresa Johnson403a7872015-10-04 14:33:43 +00005804 return initStreamFromBuffer();
5805}
5806
5807std::error_code FunctionIndexBitcodeReader::initStreamFromBuffer() {
5808 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
5809 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
5810
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005811 if (Buffer->getBufferSize() & 3)
5812 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00005813
5814 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5815 // The magic number is 0x0B17C0DE stored in little endian.
5816 if (isBitcodeWrapper(BufPtr, BufEnd))
5817 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5818 return error("Invalid bitcode wrapper header");
5819
5820 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5821 Stream.init(&*StreamFile);
5822
5823 return std::error_code();
5824}
5825
5826std::error_code FunctionIndexBitcodeReader::initLazyStream(
5827 std::unique_ptr<DataStreamer> Streamer) {
5828 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5829 // see it.
5830 auto OwnedBytes =
5831 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5832 StreamingMemoryObject &Bytes = *OwnedBytes;
5833 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5834 Stream.init(&*StreamFile);
5835
5836 unsigned char buf[16];
5837 if (Bytes.readBytes(buf, 16, 0) != 16)
5838 return error("Invalid bitcode signature");
5839
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005840 if (!isBitcode(buf, buf + 16))
5841 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00005842
5843 if (isBitcodeWrapper(buf, buf + 4)) {
5844 const unsigned char *bitcodeStart = buf;
5845 const unsigned char *bitcodeEnd = buf + 16;
5846 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5847 Bytes.dropLeadingBytes(bitcodeStart - buf);
5848 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5849 }
5850 return std::error_code();
5851}
5852
Rafael Espindola48da4f42013-11-04 16:16:24 +00005853namespace {
Rafael Espindola25188c92014-06-12 01:45:43 +00005854class BitcodeErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +00005855 const char *name() const LLVM_NOEXCEPT override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00005856 return "llvm.bitcode";
5857 }
Craig Topper73156022014-03-02 09:09:27 +00005858 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00005859 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005860 switch (E) {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00005861 case BitcodeError::InvalidBitcodeSignature:
Rafael Espindola48da4f42013-11-04 16:16:24 +00005862 return "Invalid bitcode signature";
Rafael Espindolad0b23be2015-01-10 00:07:30 +00005863 case BitcodeError::CorruptedBitcode:
5864 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00005865 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00005866 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00005867 }
5868};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00005869}
Rafael Espindola48da4f42013-11-04 16:16:24 +00005870
Chris Bieneman770163e2014-09-19 20:29:02 +00005871static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5872
Rafael Espindolac3f2e732014-07-29 20:22:46 +00005873const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00005874 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005875}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00005876
Chris Lattner6694f602007-04-29 07:54:31 +00005877//===----------------------------------------------------------------------===//
5878// External interface
5879//===----------------------------------------------------------------------===//
5880
Rafael Espindola456baad2015-06-17 01:15:47 +00005881static ErrorOr<std::unique_ptr<Module>>
5882getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
5883 BitcodeReader *R, LLVMContext &Context,
5884 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
5885 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5886 M->setMaterializer(R);
5887
5888 auto cleanupOnError = [&](std::error_code EC) {
5889 R->releaseBuffer(); // Never take ownership on error.
5890 return EC;
5891 };
5892
5893 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5894 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
5895 ShouldLazyLoadMetadata))
5896 return cleanupOnError(EC);
5897
5898 if (MaterializeAll) {
5899 // Read in the entire module, and destroy the BitcodeReader.
5900 if (std::error_code EC = M->materializeAllPermanently())
5901 return cleanupOnError(EC);
5902 } else {
5903 // Resolve forward references from blockaddresses.
5904 if (std::error_code EC = R->materializeForwardReferencedFunctions())
5905 return cleanupOnError(EC);
5906 }
5907 return std::move(M);
5908}
5909
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005910/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00005911///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005912/// This isn't always used in a lazy context. In particular, it's also used by
5913/// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
5914/// in forward-referenced functions from block address references.
5915///
Rafael Espindola728074b2015-06-17 00:40:56 +00005916/// \param[in] MaterializeAll Set to \c true if we should materialize
5917/// everything.
Rafael Espindoladcd1dca2015-06-16 22:27:55 +00005918static ErrorOr<std::unique_ptr<Module>>
Rafael Espindola68812152014-09-03 17:31:46 +00005919getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindola728074b2015-06-17 00:40:56 +00005920 LLVMContext &Context, bool MaterializeAll,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00005921 DiagnosticHandlerFunction DiagnosticHandler,
5922 bool ShouldLazyLoadMetadata = false) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00005923 BitcodeReader *R =
5924 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005925
Rafael Espindola456baad2015-06-17 01:15:47 +00005926 ErrorOr<std::unique_ptr<Module>> Ret =
5927 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
5928 MaterializeAll, ShouldLazyLoadMetadata);
5929 if (!Ret)
5930 return Ret;
Rafael Espindolab7993462012-01-02 07:49:53 +00005931
Rafael Espindolae2c1d772014-08-26 22:00:09 +00005932 Buffer.release(); // The BitcodeReader owns it now.
Rafael Espindola456baad2015-06-17 01:15:47 +00005933 return Ret;
Chris Lattner6694f602007-04-29 07:54:31 +00005934}
5935
Rafael Espindoladcd1dca2015-06-16 22:27:55 +00005936ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
5937 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5938 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00005939 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00005940 DiagnosticHandler, ShouldLazyLoadMetadata);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005941}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005942
Rafael Espindola1aabf982015-06-16 23:29:49 +00005943ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
5944 StringRef Name, std::unique_ptr<DataStreamer> Streamer,
5945 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindola7d727b52014-12-18 05:08:43 +00005946 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
Rafael Espindola1aabf982015-06-16 23:29:49 +00005947 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
Rafael Espindola456baad2015-06-17 01:15:47 +00005948
5949 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
5950 false);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005951}
5952
Rafael Espindoladcd1dca2015-06-16 22:27:55 +00005953ErrorOr<std::unique_ptr<Module>>
Rafael Espindolad0b23be2015-01-10 00:07:30 +00005954llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
5955 DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00005956 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola728074b2015-06-17 00:40:56 +00005957 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
5958 DiagnosticHandler);
Chad Rosierca2567b2011-12-07 21:44:12 +00005959 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5960 // written. We must defer until the Module has been fully materialized.
Chris Lattner6694f602007-04-29 07:54:31 +00005961}
Bill Wendling0198ce02010-10-06 01:22:42 +00005962
Rafael Espindolad0b23be2015-01-10 00:07:30 +00005963std::string
5964llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
5965 DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00005966 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindolad0b23be2015-01-10 00:07:30 +00005967 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
5968 DiagnosticHandler);
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00005969 ErrorOr<std::string> Triple = R->parseTriple();
Rafael Espindolad346cc82014-07-04 13:52:01 +00005970 if (Triple.getError())
5971 return "";
5972 return Triple.get();
Bill Wendling0198ce02010-10-06 01:22:42 +00005973}
Teresa Johnson403a7872015-10-04 14:33:43 +00005974
Mehdi Amini3383ccc2015-11-09 02:46:41 +00005975std::string
5976llvm::getBitcodeProducerString(MemoryBufferRef Buffer, LLVMContext &Context,
5977 DiagnosticHandlerFunction DiagnosticHandler) {
5978 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5979 BitcodeReader R(Buf.release(), Context, DiagnosticHandler);
5980 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
5981 if (ProducerString.getError())
5982 return "";
5983 return ProducerString.get();
5984}
5985
Teresa Johnson403a7872015-10-04 14:33:43 +00005986// Parse the specified bitcode buffer, returning the function info index.
5987// If IsLazy is false, parse the entire function summary into
5988// the index. Otherwise skip the function summary section, and only create
5989// an index object with a map from function name to function summary offset.
5990// The index is used to perform lazy function summary reading later.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005991ErrorOr<std::unique_ptr<FunctionInfoIndex>>
Mehdi Amini354f5202015-11-19 05:52:29 +00005992llvm::getFunctionInfoIndex(MemoryBufferRef Buffer,
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005993 DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00005994 const Module *ExportingModule, bool IsLazy) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005995 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Mehdi Amini354f5202015-11-19 05:52:29 +00005996 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, IsLazy);
Teresa Johnson403a7872015-10-04 14:33:43 +00005997
5998 std::unique_ptr<FunctionInfoIndex> Index =
Teresa Johnsonc7ed52f2015-11-03 00:14:15 +00005999 llvm::make_unique<FunctionInfoIndex>(ExportingModule);
Teresa Johnson403a7872015-10-04 14:33:43 +00006000
6001 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006002 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00006003 return EC;
6004 };
6005
6006 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
6007 return cleanupOnError(EC);
6008
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006009 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
Teresa Johnson403a7872015-10-04 14:33:43 +00006010 return std::move(Index);
6011}
6012
6013// Check if the given bitcode buffer contains a function summary block.
Mehdi Amini354f5202015-11-19 05:52:29 +00006014bool llvm::hasFunctionSummary(MemoryBufferRef Buffer,
Teresa Johnson403a7872015-10-04 14:33:43 +00006015 DiagnosticHandlerFunction DiagnosticHandler) {
6016 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Mehdi Amini354f5202015-11-19 05:52:29 +00006017 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, false, true);
Teresa Johnson403a7872015-10-04 14:33:43 +00006018
6019 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006020 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00006021 return false;
6022 };
6023
6024 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
6025 return cleanupOnError(EC);
6026
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006027 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
Teresa Johnson403a7872015-10-04 14:33:43 +00006028 return R.foundFuncSummary();
6029}
6030
6031// This method supports lazy reading of function summary data from the combined
6032// index during ThinLTO function importing. When reading the combined index
6033// file, getFunctionInfoIndex is first invoked with IsLazy=true.
6034// Then this method is called for each function considered for importing,
6035// to parse the summary information for the given function name into
6036// the index.
Mehdi Amini354f5202015-11-19 05:52:29 +00006037std::error_code llvm::readFunctionSummary(
6038 MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler,
6039 StringRef FunctionName, std::unique_ptr<FunctionInfoIndex> Index) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006040 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Mehdi Amini354f5202015-11-19 05:52:29 +00006041 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler);
Teresa Johnson403a7872015-10-04 14:33:43 +00006042
6043 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006044 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00006045 return EC;
6046 };
6047
6048 // Lookup the given function name in the FunctionMap, which may
6049 // contain a list of function infos in the case of a COMDAT. Walk through
6050 // and parse each function summary info at the function summary offset
6051 // recorded when parsing the value symbol table.
6052 for (const auto &FI : Index->getFunctionInfoList(FunctionName)) {
6053 size_t FunctionSummaryOffset = FI->bitcodeIndex();
6054 if (std::error_code EC =
6055 R.parseFunctionSummary(nullptr, Index.get(), FunctionSummaryOffset))
6056 return cleanupOnError(EC);
6057 }
6058
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006059 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
Teresa Johnson403a7872015-10-04 14:33:43 +00006060 return std::error_code();
6061}