blob: 06a120a5ff1e91ba2e680be9ab64d1d797fd3e7d [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>
Eugene Zelenko6ac3f732016-01-26 18:48:36 +000038
Chris Lattner1314b992007-04-22 06:23:29 +000039using namespace llvm;
40
Benjamin Kramercced8be2015-03-17 20:40:24 +000041namespace {
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +000042enum {
43 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
44};
45
Benjamin Kramercced8be2015-03-17 20:40:24 +000046class BitcodeReaderValueList {
47 std::vector<WeakVH> ValuePtrs;
48
Rafael Espindolacbdcb502015-06-15 20:55:37 +000049 /// As we resolve forward-referenced constants, we add information about them
50 /// to this vector. This allows us to resolve them in bulk instead of
51 /// resolving each reference at a time. See the code in
Benjamin Kramercced8be2015-03-17 20:40:24 +000052 /// ResolveConstantForwardRefs for more information about this.
53 ///
54 /// The key of this vector is the placeholder constant, the value is the slot
55 /// number that holds the resolved value.
56 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
57 ResolveConstantsTy ResolveConstants;
58 LLVMContext &Context;
59public:
60 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
61 ~BitcodeReaderValueList() {
62 assert(ResolveConstants.empty() && "Constants not resolved?");
63 }
64
65 // vector compatibility methods
66 unsigned size() const { return ValuePtrs.size(); }
67 void resize(unsigned N) { ValuePtrs.resize(N); }
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +000068 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
Benjamin Kramercced8be2015-03-17 20:40:24 +000069
70 void clear() {
71 assert(ResolveConstants.empty() && "Constants not resolved?");
72 ValuePtrs.clear();
73 }
74
75 Value *operator[](unsigned i) const {
76 assert(i < ValuePtrs.size());
77 return ValuePtrs[i];
78 }
79
80 Value *back() const { return ValuePtrs.back(); }
81 void pop_back() { ValuePtrs.pop_back(); }
82 bool empty() const { return ValuePtrs.empty(); }
83 void shrinkTo(unsigned N) {
84 assert(N <= size() && "Invalid shrinkTo request!");
85 ValuePtrs.resize(N);
86 }
87
88 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
David Majnemer8a1c45d2015-12-12 05:38:55 +000089 Value *getValueFwdRef(unsigned Idx, Type *Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +000090
David Majnemer8a1c45d2015-12-12 05:38:55 +000091 void assignValue(Value *V, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +000092
Rafael Espindolacbdcb502015-06-15 20:55:37 +000093 /// Once all constants are read, this method bulk resolves any forward
94 /// references.
95 void resolveConstantForwardRefs();
Benjamin Kramercced8be2015-03-17 20:40:24 +000096};
97
Teresa Johnson61b406e2015-12-29 23:00:22 +000098class BitcodeReaderMetadataList {
Benjamin Kramercced8be2015-03-17 20:40:24 +000099 unsigned NumFwdRefs;
100 bool AnyFwdRefs;
101 unsigned MinFwdRef;
102 unsigned MaxFwdRef;
Teresa Johnson61b406e2015-12-29 23:00:22 +0000103 std::vector<TrackingMDRef> MetadataPtrs;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000104
105 LLVMContext &Context;
106public:
Teresa Johnson61b406e2015-12-29 23:00:22 +0000107 BitcodeReaderMetadataList(LLVMContext &C)
Teresa Johnson34702952015-12-21 15:38:13 +0000108 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
Benjamin Kramercced8be2015-03-17 20:40:24 +0000109
110 // vector compatibility methods
Teresa Johnson61b406e2015-12-29 23:00:22 +0000111 unsigned size() const { return MetadataPtrs.size(); }
112 void resize(unsigned N) { MetadataPtrs.resize(N); }
113 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
114 void clear() { MetadataPtrs.clear(); }
115 Metadata *back() const { return MetadataPtrs.back(); }
116 void pop_back() { MetadataPtrs.pop_back(); }
117 bool empty() const { return MetadataPtrs.empty(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000118
119 Metadata *operator[](unsigned i) const {
Teresa Johnson61b406e2015-12-29 23:00:22 +0000120 assert(i < MetadataPtrs.size());
121 return MetadataPtrs[i];
Benjamin Kramercced8be2015-03-17 20:40:24 +0000122 }
123
124 void shrinkTo(unsigned N) {
125 assert(N <= size() && "Invalid shrinkTo request!");
Teresa Johnson61b406e2015-12-29 23:00:22 +0000126 MetadataPtrs.resize(N);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000127 }
128
129 Metadata *getValueFwdRef(unsigned Idx);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000130 void assignValue(Metadata *MD, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000131 void tryToResolveCycles();
132};
133
134class BitcodeReader : public GVMaterializer {
135 LLVMContext &Context;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000136 Module *TheModule = nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000137 std::unique_ptr<MemoryBuffer> Buffer;
138 std::unique_ptr<BitstreamReader> StreamFile;
139 BitstreamCursor Stream;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000140 // Next offset to start scanning for lazy parsing of function bodies.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000141 uint64_t NextUnreadBit = 0;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000142 // Last function offset found in the VST.
143 uint64_t LastFunctionBlockBit = 0;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000144 bool SeenValueSymbolTable = false;
Peter Collingbourne128a9762015-10-27 23:01:25 +0000145 uint64_t VSTOffset = 0;
Mehdi Amini5d303282015-10-26 18:37:00 +0000146 // Contains an arbitrary and optional string identifying the bitcode producer
147 std::string ProducerIdentification;
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +0000148 // Number of module level metadata records specified by the
149 // MODULE_CODE_METADATA_VALUES record.
150 unsigned NumModuleMDs = 0;
151 // Support older bitcode without the MODULE_CODE_METADATA_VALUES record.
152 bool SeenModuleValuesRecord = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000153
154 std::vector<Type*> TypeList;
155 BitcodeReaderValueList ValueList;
Teresa Johnson61b406e2015-12-29 23:00:22 +0000156 BitcodeReaderMetadataList MetadataList;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000157 std::vector<Comdat *> ComdatList;
158 SmallVector<Instruction *, 64> InstructionList;
159
160 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
161 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
162 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
163 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
David Majnemer7fddecc2015-06-17 20:52:32 +0000164 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000165
166 SmallVector<Instruction*, 64> InstsWithTBAATag;
167
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000168 /// The set of attributes by index. Index zero in the file is for null, and
169 /// is thus not represented here. As such all indices are off by one.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000170 std::vector<AttributeSet> MAttributes;
171
Karl Schimpf36440082015-08-31 16:43:55 +0000172 /// The set of attribute groups.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000173 std::map<unsigned, AttributeSet> MAttributeGroups;
174
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000175 /// While parsing a function body, this is a list of the basic blocks for the
176 /// function.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000177 std::vector<BasicBlock*> FunctionBBs;
178
179 // When reading the module header, this list is populated with functions that
180 // have bodies later in the file.
181 std::vector<Function*> FunctionsWithBodies;
182
183 // When intrinsic functions are encountered which require upgrading they are
184 // stored here with their replacement function.
Rafael Espindola4e721212015-07-02 16:22:40 +0000185 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000186 UpgradedIntrinsicMap UpgradedIntrinsics;
187
188 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
189 DenseMap<unsigned, unsigned> MDKindMap;
190
191 // Several operations happen after the module header has been read, but
192 // before function bodies are processed. This keeps track of whether
193 // we've done this yet.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000194 bool SeenFirstFunctionBody = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000195
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000196 /// When function bodies are initially scanned, this map contains info about
197 /// where to find deferred function body in the stream.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000198 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
199
200 /// When Metadata block is initially scanned when parsing the module, we may
201 /// choose to defer parsing of the metadata. This vector contains info about
202 /// which Metadata blocks are deferred.
203 std::vector<uint64_t> DeferredMetadataInfo;
204
205 /// These are basic blocks forward-referenced by block addresses. They are
206 /// inserted lazily into functions when they're loaded. The basic block ID is
207 /// its index into the vector.
208 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
209 std::deque<Function *> BasicBlockFwdRefQueue;
210
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000211 /// Indicates that we are using a new encoding for instruction operands where
212 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
213 /// instruction number, for a more compact encoding. Some instruction
214 /// operands are not relative to the instruction ID: basic block numbers, and
215 /// types. Once the old style function blocks have been phased out, we would
Benjamin Kramercced8be2015-03-17 20:40:24 +0000216 /// not need this flag.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000217 bool UseRelativeIDs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000218
219 /// True if all functions will be materialized, negating the need to process
220 /// (e.g.) blockaddress forward references.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000221 bool WillMaterializeAllForwardRefs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000222
Benjamin Kramercced8be2015-03-17 20:40:24 +0000223 /// True if any Metadata block has been materialized.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000224 bool IsMetadataMaterialized = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000225
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000226 bool StripDebugInfo = false;
227
Peter Collingbourned4bff302015-11-05 22:03:56 +0000228 /// Functions that need to be matched with subprograms when upgrading old
229 /// metadata.
230 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
231
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000232 std::vector<std::string> BundleTags;
233
Benjamin Kramercced8be2015-03-17 20:40:24 +0000234public:
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000235 std::error_code error(BitcodeError E, const Twine &Message);
236 std::error_code error(BitcodeError E);
237 std::error_code error(const Twine &Message);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000238
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000239 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context);
240 BitcodeReader(LLVMContext &Context);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000241 ~BitcodeReader() override { freeState(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000242
243 std::error_code materializeForwardReferencedFunctions();
244
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000245 void freeState();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000246
247 void releaseBuffer();
248
Benjamin Kramercced8be2015-03-17 20:40:24 +0000249 std::error_code materialize(GlobalValue *GV) override;
Rafael Espindola79753a02015-12-18 21:18:57 +0000250 std::error_code materializeModule() override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000251 std::vector<StructType *> getIdentifiedStructTypes() const override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000252
Rafael Espindola6ace6852015-06-15 21:02:49 +0000253 /// \brief Main interface to parsing a bitcode buffer.
254 /// \returns true if an error occurred.
Rafael Espindola1aabf982015-06-16 23:29:49 +0000255 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
256 Module *M,
Benjamin Kramercced8be2015-03-17 20:40:24 +0000257 bool ShouldLazyLoadMetadata = false);
258
Rafael Espindola6ace6852015-06-15 21:02:49 +0000259 /// \brief Cheap mechanism to just extract module triple
260 /// \returns true if an error occurred.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000261 ErrorOr<std::string> parseTriple();
262
Mehdi Amini3383ccc2015-11-09 02:46:41 +0000263 /// Cheap mechanism to just extract the identification block out of bitcode.
264 ErrorOr<std::string> parseIdentificationBlock();
265
Benjamin Kramercced8be2015-03-17 20:40:24 +0000266 static uint64_t decodeSignRotatedValue(uint64_t V);
267
268 /// Materialize any deferred Metadata block.
269 std::error_code materializeMetadata() override;
270
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000271 void setStripDebugInfo() override;
272
Teresa Johnsone5a61912015-12-17 17:14:09 +0000273 /// Save the mapping between the metadata values and the corresponding
Teresa Johnson61b406e2015-12-29 23:00:22 +0000274 /// value id that were recorded in the MetadataList during parsing. If
Teresa Johnsone5a61912015-12-17 17:14:09 +0000275 /// OnlyTempMD is true, then only record those entries that are still
276 /// temporary metadata. This interface is used when metadata linking is
277 /// performed as a postpass, such as during function importing.
Teresa Johnson61b406e2015-12-29 23:00:22 +0000278 void saveMetadataList(DenseMap<const Metadata *, unsigned> &MetadataToIDs,
279 bool OnlyTempMD) override;
Teresa Johnsone5a61912015-12-17 17:14:09 +0000280
Benjamin Kramercced8be2015-03-17 20:40:24 +0000281private:
Mehdi Amini5d303282015-10-26 18:37:00 +0000282 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
283 // ProducerIdentification data member, and do some basic enforcement on the
284 // "epoch" encoded in the bitcode.
285 std::error_code parseBitcodeVersion();
286
Benjamin Kramercced8be2015-03-17 20:40:24 +0000287 std::vector<StructType *> IdentifiedStructTypes;
288 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
289 StructType *createIdentifiedStructType(LLVMContext &Context);
290
291 Type *getTypeByID(unsigned ID);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000292 Value *getFnValueByID(unsigned ID, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000293 if (Ty && Ty->isMetadataTy())
294 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
David Majnemer8a1c45d2015-12-12 05:38:55 +0000295 return ValueList.getValueFwdRef(ID, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000296 }
297 Metadata *getFnMetadataByID(unsigned ID) {
Teresa Johnson61b406e2015-12-29 23:00:22 +0000298 return MetadataList.getValueFwdRef(ID);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000299 }
300 BasicBlock *getBasicBlock(unsigned ID) const {
301 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
302 return FunctionBBs[ID];
303 }
304 AttributeSet getAttributes(unsigned i) const {
305 if (i-1 < MAttributes.size())
306 return MAttributes[i-1];
307 return AttributeSet();
308 }
309
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000310 /// Read a value/type pair out of the specified record from slot 'Slot'.
311 /// Increment Slot past the number of slots used in the record. Return true on
312 /// failure.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000313 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
314 unsigned InstNum, Value *&ResVal) {
315 if (Slot == Record.size()) return true;
316 unsigned ValNo = (unsigned)Record[Slot++];
317 // Adjust the ValNo, if it was encoded relative to the InstNum.
318 if (UseRelativeIDs)
319 ValNo = InstNum - ValNo;
320 if (ValNo < InstNum) {
321 // If this is not a forward reference, just return the value we already
322 // have.
323 ResVal = getFnValueByID(ValNo, nullptr);
324 return ResVal == nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000325 }
David Blaikiedbe6e0f2015-04-17 06:40:14 +0000326 if (Slot == Record.size())
327 return true;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000328
329 unsigned TypeNo = (unsigned)Record[Slot++];
330 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
331 return ResVal == nullptr;
332 }
333
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000334 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
335 /// past the number of slots used by the value in the record. Return true if
336 /// there is an error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000337 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000338 unsigned InstNum, Type *Ty, Value *&ResVal) {
339 if (getValue(Record, Slot, InstNum, Ty, ResVal))
Benjamin Kramercced8be2015-03-17 20:40:24 +0000340 return true;
341 // All values currently take a single record slot.
342 ++Slot;
343 return false;
344 }
345
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000346 /// Like popValue, but does not increment the Slot number.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000347 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000348 unsigned InstNum, Type *Ty, Value *&ResVal) {
349 ResVal = getValue(Record, Slot, InstNum, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000350 return ResVal == nullptr;
351 }
352
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000353 /// Version of getValue that returns ResVal directly, or 0 if there is an
354 /// error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000355 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000356 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000357 if (Slot == Record.size()) return nullptr;
358 unsigned ValNo = (unsigned)Record[Slot];
359 // Adjust the ValNo, if it was encoded relative to the InstNum.
360 if (UseRelativeIDs)
361 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000362 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000363 }
364
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000365 /// Like getValue, but decodes signed VBRs.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000366 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000367 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000368 if (Slot == Record.size()) return nullptr;
369 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
370 // Adjust the ValNo, if it was encoded relative to the InstNum.
371 if (UseRelativeIDs)
372 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000373 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000374 }
375
376 /// Converts alignment exponent (i.e. power of two (or zero)) to the
377 /// corresponding alignment to use. If alignment is too large, returns
378 /// a corresponding error code.
379 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000380 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
Teresa Johnson1493ad92015-10-10 14:18:36 +0000381 std::error_code parseModule(uint64_t ResumeBit,
382 bool ShouldLazyLoadMetadata = false);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000383 std::error_code parseAttributeBlock();
384 std::error_code parseAttributeGroupBlock();
385 std::error_code parseTypeTable();
386 std::error_code parseTypeTableBody();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000387 std::error_code parseOperandBundleTags();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000388
Teresa Johnsonff642b92015-09-17 20:12:00 +0000389 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
390 unsigned NameIndex, Triple &TT);
Peter Collingbourne128a9762015-10-27 23:01:25 +0000391 std::error_code parseValueSymbolTable(uint64_t Offset = 0);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000392 std::error_code parseConstants();
Teresa Johnson1493ad92015-10-10 14:18:36 +0000393 std::error_code rememberAndSkipFunctionBodies();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000394 std::error_code rememberAndSkipFunctionBody();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000395 /// Save the positions of the Metadata blocks and skip parsing the blocks.
396 std::error_code rememberAndSkipMetadata();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000397 std::error_code parseFunctionBody(Function *F);
398 std::error_code globalCleanup();
399 std::error_code resolveGlobalAndAliasInits();
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +0000400 std::error_code parseMetadata(bool ModuleLevel = false);
Teresa Johnson12545072015-11-15 02:00:09 +0000401 std::error_code parseMetadataKinds();
402 std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000403 std::error_code parseMetadataAttachment(Function &F);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000404 ErrorOr<std::string> parseModuleTriple();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000405 std::error_code parseUseLists();
Rafael Espindola1aabf982015-06-16 23:29:49 +0000406 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000407 std::error_code initStreamFromBuffer();
Rafael Espindola1aabf982015-06-16 23:29:49 +0000408 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000409 std::error_code findFunctionInStream(
Benjamin Kramercced8be2015-03-17 20:40:24 +0000410 Function *F,
411 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
412};
Teresa Johnson403a7872015-10-04 14:33:43 +0000413
414/// Class to manage reading and parsing function summary index bitcode
415/// files/sections.
416class FunctionIndexBitcodeReader {
Teresa Johnson403a7872015-10-04 14:33:43 +0000417 DiagnosticHandlerFunction DiagnosticHandler;
418
419 /// Eventually points to the function index built during parsing.
420 FunctionInfoIndex *TheIndex = nullptr;
421
422 std::unique_ptr<MemoryBuffer> Buffer;
423 std::unique_ptr<BitstreamReader> StreamFile;
424 BitstreamCursor Stream;
425
426 /// \brief Used to indicate whether we are doing lazy parsing of summary data.
427 ///
428 /// If false, the summary section is fully parsed into the index during
429 /// the initial parse. Otherwise, if true, the caller is expected to
430 /// invoke \a readFunctionSummary for each summary needed, and the summary
431 /// section is thus parsed lazily.
432 bool IsLazy = false;
433
434 /// Used to indicate whether caller only wants to check for the presence
435 /// of the function summary bitcode section. All blocks are skipped,
436 /// but the SeenFuncSummary boolean is set.
437 bool CheckFuncSummaryPresenceOnly = false;
438
439 /// Indicates whether we have encountered a function summary section
440 /// yet during parsing, used when checking if file contains function
441 /// summary section.
442 bool SeenFuncSummary = false;
443
444 /// \brief Map populated during function summary section parsing, and
445 /// consumed during ValueSymbolTable parsing.
446 ///
447 /// Used to correlate summary records with VST entries. For the per-module
448 /// index this maps the ValueID to the parsed function summary, and
449 /// for the combined index this maps the summary record's bitcode
450 /// offset to the function summary (since in the combined index the
451 /// VST records do not hold value IDs but rather hold the function
452 /// summary record offset).
453 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>> SummaryMap;
454
455 /// Map populated during module path string table parsing, from the
456 /// module ID to a string reference owned by the index's module
457 /// path string table, used to correlate with combined index function
458 /// summary records.
459 DenseMap<uint64_t, StringRef> ModuleIdMap;
460
Teresa Johnsone1164de2016-02-10 21:55:02 +0000461 /// Original source file name recorded in a bitcode record.
462 std::string SourceFileName;
463
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000464public:
Teresa Johnson403a7872015-10-04 14:33:43 +0000465 std::error_code error(BitcodeError E, const Twine &Message);
466 std::error_code error(BitcodeError E);
467 std::error_code error(const Twine &Message);
468
Mehdi Amini354f5202015-11-19 05:52:29 +0000469 FunctionIndexBitcodeReader(MemoryBuffer *Buffer,
Teresa Johnson403a7872015-10-04 14:33:43 +0000470 DiagnosticHandlerFunction DiagnosticHandler,
471 bool IsLazy = false,
472 bool CheckFuncSummaryPresenceOnly = false);
Mehdi Amini354f5202015-11-19 05:52:29 +0000473 FunctionIndexBitcodeReader(DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson403a7872015-10-04 14:33:43 +0000474 bool IsLazy = false,
475 bool CheckFuncSummaryPresenceOnly = false);
476 ~FunctionIndexBitcodeReader() { freeState(); }
477
478 void freeState();
479
480 void releaseBuffer();
481
482 /// Check if the parser has encountered a function summary section.
483 bool foundFuncSummary() { return SeenFuncSummary; }
484
485 /// \brief Main interface to parsing a bitcode buffer.
486 /// \returns true if an error occurred.
487 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
488 FunctionInfoIndex *I);
489
490 /// \brief Interface for parsing a function summary lazily.
491 std::error_code parseFunctionSummary(std::unique_ptr<DataStreamer> Streamer,
492 FunctionInfoIndex *I,
493 size_t FunctionSummaryOffset);
494
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000495private:
Teresa Johnson403a7872015-10-04 14:33:43 +0000496 std::error_code parseModule();
497 std::error_code parseValueSymbolTable();
498 std::error_code parseEntireSummary();
499 std::error_code parseModuleStringTable();
500 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
501 std::error_code initStreamFromBuffer();
502 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
503};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000504} // end anonymous namespace
Benjamin Kramercced8be2015-03-17 20:40:24 +0000505
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000506BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
507 DiagnosticSeverity Severity,
508 const Twine &Msg)
509 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
510
511void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
512
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000513static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000514 std::error_code EC, const Twine &Message) {
515 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
516 DiagnosticHandler(DI);
517 return EC;
518}
519
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000520static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000521 std::error_code EC) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000522 return error(DiagnosticHandler, EC, EC.message());
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000523}
524
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000525static std::error_code error(LLVMContext &Context, std::error_code EC,
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000526 const Twine &Message) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000527 return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC,
528 Message);
529}
530
531static std::error_code error(LLVMContext &Context, std::error_code EC) {
532 return error(Context, EC, EC.message());
533}
534
535static std::error_code error(LLVMContext &Context, const Twine &Message) {
536 return error(Context, make_error_code(BitcodeError::CorruptedBitcode),
537 Message);
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000538}
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()) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000542 return ::error(Context, make_error_code(E),
Filipe Cabecinhasf3e167a2015-11-03 13:48:21 +0000543 Message + " (Producer: '" + ProducerIdentification +
544 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
Mehdi Amini5d303282015-10-26 18:37:00 +0000545 }
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000546 return ::error(Context, 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()) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000551 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
Filipe Cabecinhasf3e167a2015-11-03 13:48:21 +0000552 Message + " (Producer: '" + ProducerIdentification +
553 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
Mehdi Amini5d303282015-10-26 18:37:00 +0000554 }
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000555 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
556 Message);
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000557}
558
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000559std::error_code BitcodeReader::error(BitcodeError E) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000560 return ::error(Context, make_error_code(E));
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000561}
562
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000563BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context)
564 : Context(Context), Buffer(Buffer), ValueList(Context),
Teresa Johnson61b406e2015-12-29 23:00:22 +0000565 MetadataList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000566
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000567BitcodeReader::BitcodeReader(LLVMContext &Context)
568 : Context(Context), Buffer(nullptr), ValueList(Context),
Teresa Johnson61b406e2015-12-29 23:00:22 +0000569 MetadataList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000570
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000571std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
572 if (WillMaterializeAllForwardRefs)
573 return std::error_code();
574
575 // Prevent recursion.
576 WillMaterializeAllForwardRefs = true;
577
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000578 while (!BasicBlockFwdRefQueue.empty()) {
579 Function *F = BasicBlockFwdRefQueue.front();
580 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000581 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000582 if (!BasicBlockFwdRefs.count(F))
583 // Already materialized.
584 continue;
585
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000586 // Check for a function that isn't materializable to prevent an infinite
587 // loop. When parsing a blockaddress stored in a global variable, there
588 // isn't a trivial way to check if a function will have a body without a
589 // linear search through FunctionsWithBodies, so just check it here.
590 if (!F->isMaterializable())
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000591 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000592
593 // Try to materialize F.
Rafael Espindola5a52e6d2014-10-24 22:50:48 +0000594 if (std::error_code EC = materialize(F))
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000595 return EC;
Rafael Espindolab7993462012-01-02 07:49:53 +0000596 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000597 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000598
599 // Reset state.
600 WillMaterializeAllForwardRefs = false;
601 return std::error_code();
Rafael Espindolab7993462012-01-02 07:49:53 +0000602}
603
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000604void BitcodeReader::freeState() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000605 Buffer = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000606 std::vector<Type*>().swap(TypeList);
Chris Lattner9eeada92007-05-18 04:02:46 +0000607 ValueList.clear();
Teresa Johnson61b406e2015-12-29 23:00:22 +0000608 MetadataList.clear();
David Majnemerdad0a642014-06-27 18:19:56 +0000609 std::vector<Comdat *>().swap(ComdatList);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000610
Bill Wendlinge94d8432012-12-07 23:16:57 +0000611 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattner9eeada92007-05-18 04:02:46 +0000612 std::vector<BasicBlock*>().swap(FunctionBBs);
613 std::vector<Function*>().swap(FunctionsWithBodies);
614 DeferredFunctionInfo.clear();
Manman Ren4a9b0eb2015-03-13 19:24:30 +0000615 DeferredMetadataInfo.clear();
Dan Gohman43aa8f02010-07-20 21:42:28 +0000616 MDKindMap.clear();
Benjamin Kramer736a4fc2012-09-21 14:34:31 +0000617
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +0000618 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000619 BasicBlockFwdRefQueue.clear();
Chris Lattner6694f602007-04-29 07:54:31 +0000620}
621
Chris Lattnerfee5a372007-05-04 03:30:17 +0000622//===----------------------------------------------------------------------===//
623// Helper functions to implement forward reference resolution, etc.
624//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +0000625
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000626/// Convert a string from a record into an std::string, return true on failure.
627template <typename StrTy>
628static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattnerccaa4482007-04-23 21:26:05 +0000629 StrTy &Result) {
Chris Lattnere14cb882007-05-04 19:11:41 +0000630 if (Idx > Record.size())
Chris Lattner1314b992007-04-22 06:23:29 +0000631 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000632
Chris Lattnere14cb882007-05-04 19:11:41 +0000633 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
634 Result += (char)Record[i];
Chris Lattner1314b992007-04-22 06:23:29 +0000635 return false;
636}
637
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000638static bool hasImplicitComdat(size_t Val) {
639 switch (Val) {
640 default:
641 return false;
642 case 1: // Old WeakAnyLinkage
643 case 4: // Old LinkOnceAnyLinkage
644 case 10: // Old WeakODRLinkage
645 case 11: // Old LinkOnceODRLinkage
646 return true;
647 }
648}
649
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000650static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000651 switch (Val) {
652 default: // Map unknown/new linkages to external
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000653 case 0:
654 return GlobalValue::ExternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000655 case 2:
656 return GlobalValue::AppendingLinkage;
657 case 3:
658 return GlobalValue::InternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000659 case 5:
660 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
661 case 6:
662 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
663 case 7:
664 return GlobalValue::ExternalWeakLinkage;
665 case 8:
666 return GlobalValue::CommonLinkage;
667 case 9:
668 return GlobalValue::PrivateLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000669 case 12:
670 return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000671 case 13:
672 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
673 case 14:
674 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Rafael Espindolabec6af62015-01-08 15:39:50 +0000675 case 15:
676 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000677 case 1: // Old value with implicit comdat.
678 case 16:
679 return GlobalValue::WeakAnyLinkage;
680 case 10: // Old value with implicit comdat.
681 case 17:
682 return GlobalValue::WeakODRLinkage;
683 case 4: // Old value with implicit comdat.
684 case 18:
685 return GlobalValue::LinkOnceAnyLinkage;
686 case 11: // Old value with implicit comdat.
687 case 19:
688 return GlobalValue::LinkOnceODRLinkage;
Chris Lattner1314b992007-04-22 06:23:29 +0000689 }
690}
691
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000692static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000693 switch (Val) {
694 default: // Map unknown visibilities to default.
695 case 0: return GlobalValue::DefaultVisibility;
696 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000697 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000698 }
699}
700
Nico Rieck7157bb72014-01-14 15:22:47 +0000701static GlobalValue::DLLStorageClassTypes
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000702getDecodedDLLStorageClass(unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000703 switch (Val) {
704 default: // Map unknown values to default.
705 case 0: return GlobalValue::DefaultStorageClass;
706 case 1: return GlobalValue::DLLImportStorageClass;
707 case 2: return GlobalValue::DLLExportStorageClass;
708 }
709}
710
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000711static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000712 switch (Val) {
713 case 0: return GlobalVariable::NotThreadLocal;
714 default: // Map unknown non-zero value to general dynamic.
715 case 1: return GlobalVariable::GeneralDynamicTLSModel;
716 case 2: return GlobalVariable::LocalDynamicTLSModel;
717 case 3: return GlobalVariable::InitialExecTLSModel;
718 case 4: return GlobalVariable::LocalExecTLSModel;
719 }
720}
721
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000722static int getDecodedCastOpcode(unsigned Val) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000723 switch (Val) {
724 default: return -1;
725 case bitc::CAST_TRUNC : return Instruction::Trunc;
726 case bitc::CAST_ZEXT : return Instruction::ZExt;
727 case bitc::CAST_SEXT : return Instruction::SExt;
728 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
729 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
730 case bitc::CAST_UITOFP : return Instruction::UIToFP;
731 case bitc::CAST_SITOFP : return Instruction::SIToFP;
732 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
733 case bitc::CAST_FPEXT : return Instruction::FPExt;
734 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
735 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
736 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000737 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000738 }
739}
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000740
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000741static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000742 bool IsFP = Ty->isFPOrFPVectorTy();
743 // BinOps are only valid for int/fp or vector of int/fp types
744 if (!IsFP && !Ty->isIntOrIntVectorTy())
745 return -1;
746
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000747 switch (Val) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000748 default:
749 return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000750 case bitc::BINOP_ADD:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000751 return IsFP ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000752 case bitc::BINOP_SUB:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000753 return IsFP ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000754 case bitc::BINOP_MUL:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000755 return IsFP ? Instruction::FMul : Instruction::Mul;
756 case bitc::BINOP_UDIV:
757 return IsFP ? -1 : Instruction::UDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000758 case bitc::BINOP_SDIV:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000759 return IsFP ? Instruction::FDiv : Instruction::SDiv;
760 case bitc::BINOP_UREM:
761 return IsFP ? -1 : Instruction::URem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000762 case bitc::BINOP_SREM:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000763 return IsFP ? Instruction::FRem : Instruction::SRem;
764 case bitc::BINOP_SHL:
765 return IsFP ? -1 : Instruction::Shl;
766 case bitc::BINOP_LSHR:
767 return IsFP ? -1 : Instruction::LShr;
768 case bitc::BINOP_ASHR:
769 return IsFP ? -1 : Instruction::AShr;
770 case bitc::BINOP_AND:
771 return IsFP ? -1 : Instruction::And;
772 case bitc::BINOP_OR:
773 return IsFP ? -1 : Instruction::Or;
774 case bitc::BINOP_XOR:
775 return IsFP ? -1 : Instruction::Xor;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000776 }
777}
778
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000779static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000780 switch (Val) {
781 default: return AtomicRMWInst::BAD_BINOP;
782 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
783 case bitc::RMW_ADD: return AtomicRMWInst::Add;
784 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
785 case bitc::RMW_AND: return AtomicRMWInst::And;
786 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
787 case bitc::RMW_OR: return AtomicRMWInst::Or;
788 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
789 case bitc::RMW_MAX: return AtomicRMWInst::Max;
790 case bitc::RMW_MIN: return AtomicRMWInst::Min;
791 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
792 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
793 }
794}
795
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000796static AtomicOrdering getDecodedOrdering(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000797 switch (Val) {
798 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
799 case bitc::ORDERING_UNORDERED: return Unordered;
800 case bitc::ORDERING_MONOTONIC: return Monotonic;
801 case bitc::ORDERING_ACQUIRE: return Acquire;
802 case bitc::ORDERING_RELEASE: return Release;
803 case bitc::ORDERING_ACQREL: return AcquireRelease;
804 default: // Map unknown orderings to sequentially-consistent.
805 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
806 }
807}
808
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000809static SynchronizationScope getDecodedSynchScope(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000810 switch (Val) {
811 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
812 default: // Map unknown scopes to cross-thread.
813 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
814 }
815}
816
David Majnemerdad0a642014-06-27 18:19:56 +0000817static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
818 switch (Val) {
819 default: // Map unknown selection kinds to any.
820 case bitc::COMDAT_SELECTION_KIND_ANY:
821 return Comdat::Any;
822 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
823 return Comdat::ExactMatch;
824 case bitc::COMDAT_SELECTION_KIND_LARGEST:
825 return Comdat::Largest;
826 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
827 return Comdat::NoDuplicates;
828 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
829 return Comdat::SameSize;
830 }
831}
832
James Molloy88eb5352015-07-10 12:52:00 +0000833static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
834 FastMathFlags FMF;
835 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
836 FMF.setUnsafeAlgebra();
837 if (0 != (Val & FastMathFlags::NoNaNs))
838 FMF.setNoNaNs();
839 if (0 != (Val & FastMathFlags::NoInfs))
840 FMF.setNoInfs();
841 if (0 != (Val & FastMathFlags::NoSignedZeros))
842 FMF.setNoSignedZeros();
843 if (0 != (Val & FastMathFlags::AllowReciprocal))
844 FMF.setAllowReciprocal();
845 return FMF;
846}
847
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000848static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000849 switch (Val) {
850 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
851 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
852 }
853}
854
Gabor Greiff6caff662008-05-10 08:32:32 +0000855namespace llvm {
Chris Lattner1663cca2007-04-24 05:48:56 +0000856namespace {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000857/// \brief A class for maintaining the slot number definition
858/// as a placeholder for the actual definition for forward constants defs.
859class ConstantPlaceHolder : public ConstantExpr {
860 void operator=(const ConstantPlaceHolder &) = delete;
861
862public:
863 // allocate space for exactly one operand
864 void *operator new(size_t s) { return User::operator new(s, 1); }
865 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
Gabor Greiff6caff662008-05-10 08:32:32 +0000866 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000867 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
868 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000869
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000870 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
871 static bool classof(const Value *V) {
872 return isa<ConstantExpr>(V) &&
873 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
874 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000875
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000876 /// Provide fast operand accessors
877 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
878};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000879} // end anonymous namespace
Chris Lattner1663cca2007-04-24 05:48:56 +0000880
Chris Lattner2d8cd802009-03-31 22:55:09 +0000881// FIXME: can we inherit this from ConstantExpr?
Gabor Greiff6caff662008-05-10 08:32:32 +0000882template <>
Jay Foadc8adf5f2011-01-11 15:07:38 +0000883struct OperandTraits<ConstantPlaceHolder> :
884 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greiff6caff662008-05-10 08:32:32 +0000885};
Richard Trieue3d126c2014-11-21 02:42:08 +0000886DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000887} // end namespace llvm
Gabor Greiff6caff662008-05-10 08:32:32 +0000888
David Majnemer8a1c45d2015-12-12 05:38:55 +0000889void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000890 if (Idx == size()) {
891 push_back(V);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000892 return;
Chris Lattner2d8cd802009-03-31 22:55:09 +0000893 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000894
Chris Lattner2d8cd802009-03-31 22:55:09 +0000895 if (Idx >= size())
896 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000897
Chris Lattner2d8cd802009-03-31 22:55:09 +0000898 WeakVH &OldV = ValuePtrs[Idx];
Craig Topper2617dcc2014-04-15 06:32:26 +0000899 if (!OldV) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000900 OldV = V;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000901 return;
Chris Lattner2d8cd802009-03-31 22:55:09 +0000902 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000903
Chris Lattner2d8cd802009-03-31 22:55:09 +0000904 // Handle constants and non-constants (e.g. instrs) differently for
905 // efficiency.
906 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
907 ResolveConstants.push_back(std::make_pair(PHC, Idx));
908 OldV = V;
909 } else {
910 // If there was a forward reference to this value, replace it.
911 Value *PrevVal = OldV;
912 OldV->replaceAllUsesWith(V);
913 delete PrevVal;
Gabor Greiff6caff662008-05-10 08:32:32 +0000914 }
915}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000916
Chris Lattner1663cca2007-04-24 05:48:56 +0000917Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattner229907c2011-07-18 04:54:35 +0000918 Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000919 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000920 resize(Idx + 1);
Chris Lattner1663cca2007-04-24 05:48:56 +0000921
Chris Lattner2d8cd802009-03-31 22:55:09 +0000922 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhas6a92a3f2015-05-27 01:05:40 +0000923 if (Ty != V->getType())
924 report_fatal_error("Type mismatch in constant table!");
Chris Lattner83930552007-05-01 07:01:57 +0000925 return cast<Constant>(V);
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000926 }
Chris Lattner1663cca2007-04-24 05:48:56 +0000927
928 // Create and return a placeholder, which will later be RAUW'd.
Owen Andersone9f98042009-07-07 20:18:58 +0000929 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000930 ValuePtrs[Idx] = C;
Chris Lattner1663cca2007-04-24 05:48:56 +0000931 return C;
932}
933
David Majnemer8a1c45d2015-12-12 05:38:55 +0000934Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Filipe Cabecinhasbad07792015-04-30 00:52:42 +0000935 // Bail out for a clearly invalid value. This would make us call resize(0)
936 if (Idx == UINT_MAX)
937 return nullptr;
938
Chris Lattner2d8cd802009-03-31 22:55:09 +0000939 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000940 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000941
Chris Lattner2d8cd802009-03-31 22:55:09 +0000942 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhasb435d0f2015-04-28 20:18:47 +0000943 // If the types don't match, it's invalid.
944 if (Ty && Ty != V->getType())
945 return nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000946 return V;
Chris Lattner83930552007-05-01 07:01:57 +0000947 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000948
Chris Lattner1fc27f02007-05-02 05:16:49 +0000949 // No type specified, must be invalid reference.
Craig Topper2617dcc2014-04-15 06:32:26 +0000950 if (!Ty) return nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000951
Chris Lattner83930552007-05-01 07:01:57 +0000952 // Create and return a placeholder, which will later be RAUW'd.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000953 Value *V = new Argument(Ty);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000954 ValuePtrs[Idx] = V;
Chris Lattner83930552007-05-01 07:01:57 +0000955 return V;
956}
957
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000958/// Once all constants are read, this method bulk resolves any forward
959/// references. The idea behind this is that we sometimes get constants (such
960/// as large arrays) which reference *many* forward ref constants. Replacing
961/// each of these causes a lot of thrashing when building/reuniquing the
962/// constant. Instead of doing this, we look at all the uses and rewrite all
963/// the place holders at once for any constant that uses a placeholder.
964void BitcodeReaderValueList::resolveConstantForwardRefs() {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000965 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattner74429932008-08-21 02:34:16 +0000966 // binary search.
967 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000968
Chris Lattner74429932008-08-21 02:34:16 +0000969 SmallVector<Constant*, 64> NewOps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000970
Chris Lattner74429932008-08-21 02:34:16 +0000971 while (!ResolveConstants.empty()) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000972 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattner74429932008-08-21 02:34:16 +0000973 Constant *Placeholder = ResolveConstants.back().first;
974 ResolveConstants.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000975
Chris Lattner74429932008-08-21 02:34:16 +0000976 // Loop over all users of the placeholder, updating them to reference the
977 // new value. If they reference more than one placeholder, update them all
978 // at once.
979 while (!Placeholder->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000980 auto UI = Placeholder->user_begin();
Gabor Greif2c0ab482010-07-09 16:01:21 +0000981 User *U = *UI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000982
Chris Lattner74429932008-08-21 02:34:16 +0000983 // If the using object isn't uniqued, just update the operands. This
984 // handles instructions and initializers for global variables.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000985 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattner479c5d92008-08-21 17:31:45 +0000986 UI.getUse().set(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +0000987 continue;
988 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000989
Chris Lattner74429932008-08-21 02:34:16 +0000990 // Otherwise, we have a constant that uses the placeholder. Replace that
991 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000992 Constant *UserC = cast<Constant>(U);
Chris Lattner74429932008-08-21 02:34:16 +0000993 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
994 I != E; ++I) {
995 Value *NewOp;
996 if (!isa<ConstantPlaceHolder>(*I)) {
997 // Not a placeholder reference.
998 NewOp = *I;
999 } else if (*I == Placeholder) {
1000 // Common case is that it just references this one placeholder.
1001 NewOp = RealVal;
1002 } else {
1003 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001004 ResolveConstantsTy::iterator It =
1005 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattner74429932008-08-21 02:34:16 +00001006 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1007 0));
1008 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner2d8cd802009-03-31 22:55:09 +00001009 NewOp = operator[](It->second);
Chris Lattner74429932008-08-21 02:34:16 +00001010 }
1011
1012 NewOps.push_back(cast<Constant>(NewOp));
1013 }
1014
1015 // Make the new constant.
1016 Constant *NewC;
1017 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad83be3612011-06-22 09:24:39 +00001018 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001019 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnercc19efa2011-06-20 04:01:31 +00001020 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001021 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner69229312011-02-15 00:14:00 +00001022 NewC = ConstantVector::get(NewOps);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001023 } else {
1024 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foad5c984e562011-04-13 13:46:01 +00001025 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001026 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001027
Chris Lattner74429932008-08-21 02:34:16 +00001028 UserC->replaceAllUsesWith(NewC);
1029 UserC->destroyConstant();
1030 NewOps.clear();
1031 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001032
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001033 // Update all ValueHandles, they should be the only users at this point.
1034 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +00001035 delete Placeholder;
1036 }
1037}
1038
Teresa Johnson61b406e2015-12-29 23:00:22 +00001039void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +00001040 if (Idx == size()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001041 push_back(MD);
Devang Patel05eb6172009-08-04 06:00:18 +00001042 return;
1043 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001044
Devang Patel05eb6172009-08-04 06:00:18 +00001045 if (Idx >= size())
1046 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001047
Teresa Johnson61b406e2015-12-29 23:00:22 +00001048 TrackingMDRef &OldMD = MetadataPtrs[Idx];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001049 if (!OldMD) {
1050 OldMD.reset(MD);
Devang Patel05eb6172009-08-04 06:00:18 +00001051 return;
1052 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001053
Devang Patel05eb6172009-08-04 06:00:18 +00001054 // If there was a forward reference to this value, replace it.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +00001055 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001056 PrevMD->replaceAllUsesWith(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001057 --NumFwdRefs;
Devang Patel05eb6172009-08-04 06:00:18 +00001058}
1059
Teresa Johnson61b406e2015-12-29 23:00:22 +00001060Metadata *BitcodeReaderMetadataList::getValueFwdRef(unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +00001061 if (Idx >= size())
1062 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001063
Teresa Johnson61b406e2015-12-29 23:00:22 +00001064 if (Metadata *MD = MetadataPtrs[Idx])
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001065 return MD;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001066
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001067 // Track forward refs to be resolved later.
1068 if (AnyFwdRefs) {
1069 MinFwdRef = std::min(MinFwdRef, Idx);
1070 MaxFwdRef = std::max(MaxFwdRef, Idx);
1071 } else {
1072 AnyFwdRefs = true;
1073 MinFwdRef = MaxFwdRef = Idx;
1074 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001075 ++NumFwdRefs;
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001076
1077 // Create and return a placeholder, which will later be RAUW'd.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +00001078 Metadata *MD = MDNode::getTemporary(Context, None).release();
Teresa Johnson61b406e2015-12-29 23:00:22 +00001079 MetadataPtrs[Idx].reset(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001080 return MD;
1081}
1082
Teresa Johnson61b406e2015-12-29 23:00:22 +00001083void BitcodeReaderMetadataList::tryToResolveCycles() {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001084 if (!AnyFwdRefs)
1085 // Nothing to do.
1086 return;
1087
1088 if (NumFwdRefs)
1089 // Still forward references... can't resolve cycles.
1090 return;
1091
1092 // Resolve any cycles.
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001093 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
Teresa Johnson61b406e2015-12-29 23:00:22 +00001094 auto &MD = MetadataPtrs[I];
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +00001095 auto *N = dyn_cast_or_null<MDNode>(MD);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +00001096 if (!N)
1097 continue;
1098
1099 assert(!N->isTemporary() && "Unexpected forward reference");
1100 N->resolveCycles();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001101 }
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001102
1103 // Make sure we return early again until there's another forward ref.
1104 AnyFwdRefs = false;
Devang Patel05eb6172009-08-04 06:00:18 +00001105}
Chris Lattner1314b992007-04-22 06:23:29 +00001106
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001107Type *BitcodeReader::getTypeByID(unsigned ID) {
1108 // The type table size is always specified correctly.
1109 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +00001110 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +00001111
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001112 if (Type *Ty = TypeList[ID])
1113 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001114
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001115 // If we have a forward reference, the only possible case is when it is to a
1116 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001117 return TypeList[ID] = createIdentifiedStructType(Context);
1118}
1119
1120StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1121 StringRef Name) {
1122 auto *Ret = StructType::create(Context, Name);
1123 IdentifiedStructTypes.push_back(Ret);
1124 return Ret;
1125}
1126
1127StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1128 auto *Ret = StructType::create(Context);
1129 IdentifiedStructTypes.push_back(Ret);
1130 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +00001131}
1132
Chris Lattnerfee5a372007-05-04 03:30:17 +00001133//===----------------------------------------------------------------------===//
1134// Functions for parsing blocks from the bitcode file
1135//===----------------------------------------------------------------------===//
1136
Bill Wendling56aeccc2013-02-04 23:32:23 +00001137
1138/// \brief This fills an AttrBuilder object with the LLVM attributes that have
1139/// been decoded from the given integer. This function must stay in sync with
1140/// 'encodeLLVMAttributesForBitcode'.
1141static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1142 uint64_t EncodedAttrs) {
1143 // FIXME: Remove in 4.0.
1144
1145 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1146 // the bits above 31 down by 11 bits.
1147 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1148 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1149 "Alignment must be a power of two.");
1150
1151 if (Alignment)
1152 B.addAlignmentAttr(Alignment);
Kostya Serebryanyd688bab2013-02-11 08:13:54 +00001153 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
Bill Wendling56aeccc2013-02-04 23:32:23 +00001154 (EncodedAttrs & 0xffff));
1155}
1156
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001157std::error_code BitcodeReader::parseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001158 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001159 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001160
Devang Patela05633e2008-09-26 22:53:05 +00001161 if (!MAttributes.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001162 return error("Invalid multiple blocks");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001163
Chris Lattnerfee5a372007-05-04 03:30:17 +00001164 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001165
Bill Wendling71173cb2013-01-27 00:36:48 +00001166 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001167
Chris Lattnerfee5a372007-05-04 03:30:17 +00001168 // Read all the records.
1169 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001170 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001171
Chris Lattner27d38752013-01-20 02:13:19 +00001172 switch (Entry.Kind) {
1173 case BitstreamEntry::SubBlock: // Handled for us already.
1174 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001175 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001176 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001177 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001178 case BitstreamEntry::Record:
1179 // The interesting case.
1180 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001181 }
Joe Abbey97b7a172013-02-06 22:14:06 +00001182
Chris Lattnerfee5a372007-05-04 03:30:17 +00001183 // Read a record.
1184 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001185 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +00001186 default: // Default behavior: ignore.
1187 break;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001188 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1189 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +00001190 if (Record.size() & 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001191 return error("Invalid record");
Chris Lattnerfee5a372007-05-04 03:30:17 +00001192
Chris Lattnerfee5a372007-05-04 03:30:17 +00001193 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +00001194 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001195 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling60011b82013-01-29 01:43:29 +00001196 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +00001197 }
Devang Patela05633e2008-09-26 22:53:05 +00001198
Bill Wendlinge94d8432012-12-07 23:16:57 +00001199 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +00001200 Attrs.clear();
1201 break;
1202 }
Bill Wendling0dc08912013-02-12 08:13:50 +00001203 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1204 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1205 Attrs.push_back(MAttributeGroups[Record[i]]);
1206
1207 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1208 Attrs.clear();
1209 break;
1210 }
Duncan Sands04eb67e2007-11-20 14:09:29 +00001211 }
Chris Lattnerfee5a372007-05-04 03:30:17 +00001212 }
1213}
1214
Reid Klecknere9f36af2013-11-12 01:31:00 +00001215// Returns Attribute::None on unrecognized codes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001216static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
Reid Klecknere9f36af2013-11-12 01:31:00 +00001217 switch (Code) {
1218 default:
1219 return Attribute::None;
1220 case bitc::ATTR_KIND_ALIGNMENT:
1221 return Attribute::Alignment;
1222 case bitc::ATTR_KIND_ALWAYS_INLINE:
1223 return Attribute::AlwaysInline;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001224 case bitc::ATTR_KIND_ARGMEMONLY:
1225 return Attribute::ArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001226 case bitc::ATTR_KIND_BUILTIN:
1227 return Attribute::Builtin;
1228 case bitc::ATTR_KIND_BY_VAL:
1229 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +00001230 case bitc::ATTR_KIND_IN_ALLOCA:
1231 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001232 case bitc::ATTR_KIND_COLD:
1233 return Attribute::Cold;
Owen Anderson85fa7d52015-05-26 23:48:40 +00001234 case bitc::ATTR_KIND_CONVERGENT:
1235 return Attribute::Convergent;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001236 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1237 return Attribute::InaccessibleMemOnly;
1238 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1239 return Attribute::InaccessibleMemOrArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001240 case bitc::ATTR_KIND_INLINE_HINT:
1241 return Attribute::InlineHint;
1242 case bitc::ATTR_KIND_IN_REG:
1243 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +00001244 case bitc::ATTR_KIND_JUMP_TABLE:
1245 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001246 case bitc::ATTR_KIND_MIN_SIZE:
1247 return Attribute::MinSize;
1248 case bitc::ATTR_KIND_NAKED:
1249 return Attribute::Naked;
1250 case bitc::ATTR_KIND_NEST:
1251 return Attribute::Nest;
1252 case bitc::ATTR_KIND_NO_ALIAS:
1253 return Attribute::NoAlias;
1254 case bitc::ATTR_KIND_NO_BUILTIN:
1255 return Attribute::NoBuiltin;
1256 case bitc::ATTR_KIND_NO_CAPTURE:
1257 return Attribute::NoCapture;
1258 case bitc::ATTR_KIND_NO_DUPLICATE:
1259 return Attribute::NoDuplicate;
1260 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1261 return Attribute::NoImplicitFloat;
1262 case bitc::ATTR_KIND_NO_INLINE:
1263 return Attribute::NoInline;
James Molloye6f87ca2015-11-06 10:32:53 +00001264 case bitc::ATTR_KIND_NO_RECURSE:
1265 return Attribute::NoRecurse;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001266 case bitc::ATTR_KIND_NON_LAZY_BIND:
1267 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001268 case bitc::ATTR_KIND_NON_NULL:
1269 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001270 case bitc::ATTR_KIND_DEREFERENCEABLE:
1271 return Attribute::Dereferenceable;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001272 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1273 return Attribute::DereferenceableOrNull;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001274 case bitc::ATTR_KIND_NO_RED_ZONE:
1275 return Attribute::NoRedZone;
1276 case bitc::ATTR_KIND_NO_RETURN:
1277 return Attribute::NoReturn;
1278 case bitc::ATTR_KIND_NO_UNWIND:
1279 return Attribute::NoUnwind;
1280 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1281 return Attribute::OptimizeForSize;
1282 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1283 return Attribute::OptimizeNone;
1284 case bitc::ATTR_KIND_READ_NONE:
1285 return Attribute::ReadNone;
1286 case bitc::ATTR_KIND_READ_ONLY:
1287 return Attribute::ReadOnly;
1288 case bitc::ATTR_KIND_RETURNED:
1289 return Attribute::Returned;
1290 case bitc::ATTR_KIND_RETURNS_TWICE:
1291 return Attribute::ReturnsTwice;
1292 case bitc::ATTR_KIND_S_EXT:
1293 return Attribute::SExt;
1294 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1295 return Attribute::StackAlignment;
1296 case bitc::ATTR_KIND_STACK_PROTECT:
1297 return Attribute::StackProtect;
1298 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1299 return Attribute::StackProtectReq;
1300 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1301 return Attribute::StackProtectStrong;
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001302 case bitc::ATTR_KIND_SAFESTACK:
1303 return Attribute::SafeStack;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001304 case bitc::ATTR_KIND_STRUCT_RET:
1305 return Attribute::StructRet;
1306 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1307 return Attribute::SanitizeAddress;
1308 case bitc::ATTR_KIND_SANITIZE_THREAD:
1309 return Attribute::SanitizeThread;
1310 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1311 return Attribute::SanitizeMemory;
1312 case bitc::ATTR_KIND_UW_TABLE:
1313 return Attribute::UWTable;
1314 case bitc::ATTR_KIND_Z_EXT:
1315 return Attribute::ZExt;
1316 }
1317}
1318
JF Bastien30bf96b2015-02-22 19:32:03 +00001319std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1320 unsigned &Alignment) {
1321 // Note: Alignment in bitcode files is incremented by 1, so that zero
1322 // can be used for default alignment.
1323 if (Exponent > Value::MaxAlignmentExponent + 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001324 return error("Invalid alignment value");
JF Bastien30bf96b2015-02-22 19:32:03 +00001325 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1326 return std::error_code();
1327}
1328
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001329std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001330 Attribute::AttrKind *Kind) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001331 *Kind = getAttrFromCode(Code);
Reid Klecknere9f36af2013-11-12 01:31:00 +00001332 if (*Kind == Attribute::None)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001333 return error(BitcodeError::CorruptedBitcode,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001334 "Unknown attribute kind (" + Twine(Code) + ")");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001335 return std::error_code();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001336}
1337
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001338std::error_code BitcodeReader::parseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +00001339 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001340 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001341
1342 if (!MAttributeGroups.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001343 return error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +00001344
1345 SmallVector<uint64_t, 64> Record;
1346
1347 // Read all the records.
1348 while (1) {
1349 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1350
1351 switch (Entry.Kind) {
1352 case BitstreamEntry::SubBlock: // Handled for us already.
1353 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001354 return error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +00001355 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001356 return std::error_code();
Bill Wendlingba629332013-02-10 23:24:25 +00001357 case BitstreamEntry::Record:
1358 // The interesting case.
1359 break;
1360 }
1361
1362 // Read a record.
1363 Record.clear();
1364 switch (Stream.readRecord(Entry.ID, Record)) {
1365 default: // Default behavior: ignore.
1366 break;
1367 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1368 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001369 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001370
Bill Wendlinge46707e2013-02-11 22:32:29 +00001371 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +00001372 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1373
1374 AttrBuilder B;
1375 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1376 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001377 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001378 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001379 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001380
1381 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +00001382 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001383 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001384 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001385 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001386 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001387 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001388 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001389 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001390 else if (Kind == Attribute::Dereferenceable)
1391 B.addDereferenceableAttr(Record[++i]);
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001392 else if (Kind == Attribute::DereferenceableOrNull)
1393 B.addDereferenceableOrNullAttr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +00001394 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +00001395 assert((Record[i] == 3 || Record[i] == 4) &&
1396 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +00001397 bool HasValue = (Record[i++] == 4);
1398 SmallString<64> KindStr;
1399 SmallString<64> ValStr;
1400
1401 while (Record[i] != 0 && i != e)
1402 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001403 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001404
1405 if (HasValue) {
1406 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +00001407 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +00001408 while (Record[i] != 0 && i != e)
1409 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001410 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001411 }
1412
1413 B.addAttribute(KindStr.str(), ValStr.str());
1414 }
1415 }
1416
Bill Wendlinge46707e2013-02-11 22:32:29 +00001417 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +00001418 break;
1419 }
1420 }
1421 }
1422}
1423
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001424std::error_code BitcodeReader::parseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001425 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001426 return error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +00001427
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001428 return parseTypeTableBody();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001429}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001430
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001431std::error_code BitcodeReader::parseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +00001432 if (!TypeList.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001433 return error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +00001434
1435 SmallVector<uint64_t, 64> Record;
1436 unsigned NumRecords = 0;
1437
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001438 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +00001439
Chris Lattner1314b992007-04-22 06:23:29 +00001440 // Read all the records for this type table.
1441 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001442 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001443
Chris Lattner27d38752013-01-20 02:13:19 +00001444 switch (Entry.Kind) {
1445 case BitstreamEntry::SubBlock: // Handled for us already.
1446 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001447 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001448 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +00001449 if (NumRecords != TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001450 return error("Malformed block");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001451 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001452 case BitstreamEntry::Record:
1453 // The interesting case.
1454 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001455 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001456
Chris Lattner1314b992007-04-22 06:23:29 +00001457 // Read a record.
1458 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001459 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001460 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001461 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001462 return error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +00001463 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1464 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1465 // type list. This allows us to reserve space.
1466 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001467 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001468 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001469 continue;
Chris Lattner1314b992007-04-22 06:23:29 +00001470 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +00001471 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001472 break;
Dan Gohman518cda42011-12-17 00:04:22 +00001473 case bitc::TYPE_CODE_HALF: // HALF
1474 ResultTy = Type::getHalfTy(Context);
1475 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001476 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +00001477 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001478 break;
1479 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +00001480 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001481 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001482 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +00001483 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001484 break;
1485 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001486 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001487 break;
1488 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001489 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001490 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001491 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +00001492 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001493 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001494 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +00001495 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001496 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +00001497 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1498 ResultTy = Type::getX86_MMXTy(Context);
1499 break;
David Majnemerb611e3f2015-08-14 05:09:07 +00001500 case bitc::TYPE_CODE_TOKEN: // TOKEN
1501 ResultTy = Type::getTokenTy(Context);
1502 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001503 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
Chris Lattner1314b992007-04-22 06:23:29 +00001504 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001505 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001506
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001507 uint64_t NumBits = Record[0];
1508 if (NumBits < IntegerType::MIN_INT_BITS ||
1509 NumBits > IntegerType::MAX_INT_BITS)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001510 return error("Bitwidth for integer type out of range");
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001511 ResultTy = IntegerType::get(Context, NumBits);
Chris Lattner1314b992007-04-22 06:23:29 +00001512 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001513 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001514 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001515 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +00001516 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001517 return error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001518 unsigned AddressSpace = 0;
1519 if (Record.size() == 2)
1520 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001521 ResultTy = getTypeByID(Record[0]);
Filipe Cabecinhasd8a1bcd2015-04-29 02:27:28 +00001522 if (!ResultTy ||
1523 !PointerType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001524 return error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001525 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +00001526 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001527 }
Nuno Lopes561dae02012-05-23 15:19:39 +00001528 case bitc::TYPE_CODE_FUNCTION_OLD: {
1529 // FIXME: attrid is dead, remove it in LLVM 4.0
1530 // FUNCTION: [vararg, attrid, retty, paramty x N]
1531 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001532 return error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +00001533 SmallVector<Type*, 8> ArgTys;
1534 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1535 if (Type *T = getTypeByID(Record[i]))
1536 ArgTys.push_back(T);
1537 else
1538 break;
1539 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001540
Nuno Lopes561dae02012-05-23 15:19:39 +00001541 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001542 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001543 return error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +00001544
1545 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1546 break;
1547 }
Chad Rosier95898722011-11-03 00:14:01 +00001548 case bitc::TYPE_CODE_FUNCTION: {
1549 // FUNCTION: [vararg, retty, paramty x N]
1550 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001551 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001552 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +00001553 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001554 if (Type *T = getTypeByID(Record[i])) {
1555 if (!FunctionType::isValidArgumentType(T))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001556 return error("Invalid function argument type");
Chad Rosier95898722011-11-03 00:14:01 +00001557 ArgTys.push_back(T);
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001558 }
Chad Rosier95898722011-11-03 00:14:01 +00001559 else
1560 break;
1561 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001562
Chad Rosier95898722011-11-03 00:14:01 +00001563 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001564 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001565 return error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +00001566
1567 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1568 break;
1569 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001570 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +00001571 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001572 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001573 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001574 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1575 if (Type *T = getTypeByID(Record[i]))
1576 EltTys.push_back(T);
1577 else
1578 break;
1579 }
1580 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001581 return error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001582 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001583 break;
1584 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001585 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001586 if (convertToString(Record, 0, TypeName))
1587 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001588 continue;
1589
1590 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1591 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001592 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001593
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001594 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001595 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001596
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001597 // Check to see if this was forward referenced, if so fill in the temp.
1598 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1599 if (Res) {
1600 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001601 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001602 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001603 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001604 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001605
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001606 SmallVector<Type*, 8> EltTys;
1607 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1608 if (Type *T = getTypeByID(Record[i]))
1609 EltTys.push_back(T);
1610 else
1611 break;
1612 }
1613 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001614 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001615 Res->setBody(EltTys, Record[0]);
1616 ResultTy = Res;
1617 break;
1618 }
1619 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1620 if (Record.size() != 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001621 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001622
1623 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001624 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001625
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001626 // Check to see if this was forward referenced, if so fill in the temp.
1627 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1628 if (Res) {
1629 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001630 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001631 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001632 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001633 TypeName.clear();
1634 ResultTy = Res;
1635 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001636 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001637 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1638 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001639 return error("Invalid record");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001640 ResultTy = getTypeByID(Record[1]);
1641 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001642 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001643 ResultTy = ArrayType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001644 break;
1645 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1646 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001647 return error("Invalid record");
Filipe Cabecinhas8e421902015-06-03 00:05:30 +00001648 if (Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001649 return error("Invalid vector length");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001650 ResultTy = getTypeByID(Record[1]);
1651 if (!ResultTy || !StructType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001652 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001653 ResultTy = VectorType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001654 break;
1655 }
1656
1657 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001658 return error("Invalid TYPE table");
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001659 if (TypeList[NumRecords])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001660 return error(
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001661 "Invalid TYPE table: Only named structs can be forward referenced");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001662 assert(ResultTy && "Didn't read a type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001663 TypeList[NumRecords++] = ResultTy;
1664 }
1665}
1666
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001667std::error_code BitcodeReader::parseOperandBundleTags() {
1668 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1669 return error("Invalid record");
1670
1671 if (!BundleTags.empty())
1672 return error("Invalid multiple blocks");
1673
1674 SmallVector<uint64_t, 64> Record;
1675
1676 while (1) {
1677 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1678
1679 switch (Entry.Kind) {
1680 case BitstreamEntry::SubBlock: // Handled for us already.
1681 case BitstreamEntry::Error:
1682 return error("Malformed block");
1683 case BitstreamEntry::EndBlock:
1684 return std::error_code();
1685 case BitstreamEntry::Record:
1686 // The interesting case.
1687 break;
1688 }
1689
1690 // Tags are implicitly mapped to integers by their order.
1691
1692 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1693 return error("Invalid record");
1694
1695 // OPERAND_BUNDLE_TAG: [strchr x N]
1696 BundleTags.emplace_back();
1697 if (convertToString(Record, 0, BundleTags.back()))
1698 return error("Invalid record");
1699 Record.clear();
1700 }
1701}
1702
Teresa Johnsonff642b92015-09-17 20:12:00 +00001703/// Associate a value with its name from the given index in the provided record.
1704ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1705 unsigned NameIndex, Triple &TT) {
1706 SmallString<128> ValueName;
1707 if (convertToString(Record, NameIndex, ValueName))
1708 return error("Invalid record");
1709 unsigned ValueID = Record[0];
1710 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1711 return error("Invalid record");
1712 Value *V = ValueList[ValueID];
1713
Filipe Cabecinhasa2b0ac42015-11-04 14:53:36 +00001714 StringRef NameStr(ValueName.data(), ValueName.size());
1715 if (NameStr.find_first_of(0) != StringRef::npos)
1716 return error("Invalid value name");
1717 V->setName(NameStr);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001718 auto *GO = dyn_cast<GlobalObject>(V);
1719 if (GO) {
1720 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1721 if (TT.isOSBinFormatMachO())
1722 GO->setComdat(nullptr);
1723 else
1724 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1725 }
1726 }
1727 return V;
1728}
1729
1730/// Parse the value symbol table at either the current parsing location or
1731/// at the given bit offset if provided.
Peter Collingbourne128a9762015-10-27 23:01:25 +00001732std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001733 uint64_t CurrentBit;
1734 // Pass in the Offset to distinguish between calling for the module-level
1735 // VST (where we want to jump to the VST offset) and the function-level
1736 // VST (where we don't).
1737 if (Offset > 0) {
1738 // Save the current parsing location so we can jump back at the end
1739 // of the VST read.
1740 CurrentBit = Stream.GetCurrentBitNo();
1741 Stream.JumpToBit(Offset * 32);
1742#ifndef NDEBUG
1743 // Do some checking if we are in debug mode.
1744 BitstreamEntry Entry = Stream.advance();
1745 assert(Entry.Kind == BitstreamEntry::SubBlock);
1746 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1747#else
1748 // In NDEBUG mode ignore the output so we don't get an unused variable
1749 // warning.
1750 Stream.advance();
1751#endif
1752 }
1753
1754 // Compute the delta between the bitcode indices in the VST (the word offset
1755 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1756 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1757 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1758 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1759 // just before entering the VST subblock because: 1) the EnterSubBlock
1760 // changes the AbbrevID width; 2) the VST block is nested within the same
1761 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1762 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1763 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1764 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1765 unsigned FuncBitcodeOffsetDelta =
1766 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1767
Chris Lattner982ec1e2007-05-05 00:17:00 +00001768 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001769 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001770
1771 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001772
David Majnemer3087b222015-01-20 05:58:07 +00001773 Triple TT(TheModule->getTargetTriple());
1774
Chris Lattnerccaa4482007-04-23 21:26:05 +00001775 // Read all the records for this value table.
1776 SmallString<128> ValueName;
1777 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001778 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001779
Chris Lattner27d38752013-01-20 02:13:19 +00001780 switch (Entry.Kind) {
1781 case BitstreamEntry::SubBlock: // Handled for us already.
1782 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001783 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001784 case BitstreamEntry::EndBlock:
Teresa Johnsonff642b92015-09-17 20:12:00 +00001785 if (Offset > 0)
1786 Stream.JumpToBit(CurrentBit);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001787 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001788 case BitstreamEntry::Record:
1789 // The interesting case.
1790 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001791 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001792
Chris Lattnerccaa4482007-04-23 21:26:05 +00001793 // Read a record.
1794 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001795 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001796 default: // Default behavior: unknown type.
1797 break;
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001798 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
Teresa Johnsonff642b92015-09-17 20:12:00 +00001799 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1800 if (std::error_code EC = ValOrErr.getError())
1801 return EC;
1802 ValOrErr.get();
1803 break;
1804 }
1805 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001806 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonff642b92015-09-17 20:12:00 +00001807 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1808 if (std::error_code EC = ValOrErr.getError())
1809 return EC;
1810 Value *V = ValOrErr.get();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001811
Teresa Johnsonff642b92015-09-17 20:12:00 +00001812 auto *GO = dyn_cast<GlobalObject>(V);
1813 if (!GO) {
1814 // If this is an alias, need to get the actual Function object
1815 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1816 auto *GA = dyn_cast<GlobalAlias>(V);
1817 if (GA)
1818 GO = GA->getBaseObject();
1819 assert(GO);
Rafael Espindola12ca34f2015-01-19 15:16:06 +00001820 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001821
1822 uint64_t FuncWordOffset = Record[1];
1823 Function *F = dyn_cast<Function>(GO);
1824 assert(F);
1825 uint64_t FuncBitOffset = FuncWordOffset * 32;
1826 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
Teresa Johnson1493ad92015-10-10 14:18:36 +00001827 // Set the LastFunctionBlockBit to point to the last function block.
Teresa Johnsonff642b92015-09-17 20:12:00 +00001828 // Later when parsing is resumed after function materialization,
1829 // we can simply skip that last function block.
Teresa Johnson1493ad92015-10-10 14:18:36 +00001830 if (FuncBitOffset > LastFunctionBlockBit)
1831 LastFunctionBlockBit = FuncBitOffset;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001832 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00001833 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00001834 case bitc::VST_CODE_BBENTRY: {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001835 if (convertToString(Record, 1, ValueName))
1836 return error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00001837 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001838 if (!BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001839 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001840
Daniel Dunbard786b512009-07-26 00:34:27 +00001841 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00001842 ValueName.clear();
1843 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001844 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00001845 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001846 }
1847}
1848
Teresa Johnson12545072015-11-15 02:00:09 +00001849/// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1850std::error_code
1851BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
1852 if (Record.size() < 2)
1853 return error("Invalid record");
1854
1855 unsigned Kind = Record[0];
1856 SmallString<8> Name(Record.begin() + 1, Record.end());
1857
1858 unsigned NewKind = TheModule->getMDKindID(Name.str());
1859 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1860 return error("Conflicting METADATA_KIND records");
1861 return std::error_code();
1862}
1863
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001864static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1865
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00001866/// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
1867/// module level metadata.
1868std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00001869 IsMetadataMaterialized = true;
Teresa Johnson61b406e2015-12-29 23:00:22 +00001870 unsigned NextMetadataNo = MetadataList.size();
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00001871 if (ModuleLevel && SeenModuleValuesRecord) {
1872 // Now that we are parsing the module level metadata, we want to restart
1873 // the numbering of the MD values, and replace temp MD created earlier
1874 // with their real values. If we saw a METADATA_VALUE record then we
Teresa Johnson61b406e2015-12-29 23:00:22 +00001875 // would have set the MetadataList size to the number specified in that
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00001876 // record, to support parsing function-level metadata first, and we need
Teresa Johnson61b406e2015-12-29 23:00:22 +00001877 // to reset back to 0 to fill the MetadataList in with the parsed module
1878 // The function-level metadata parsing should have reset the MetadataList
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00001879 // size back to the value reported by the METADATA_VALUE record, saved in
1880 // NumModuleMDs.
Teresa Johnson61b406e2015-12-29 23:00:22 +00001881 assert(NumModuleMDs == MetadataList.size() &&
1882 "Expected MetadataList to only contain module level values");
1883 NextMetadataNo = 0;
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00001884 }
Devang Patel7428d8a2009-07-22 17:43:22 +00001885
1886 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001887 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001888
Devang Patel7428d8a2009-07-22 17:43:22 +00001889 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001890
Teresa Johnson61b406e2015-12-29 23:00:22 +00001891 auto getMD = [&](unsigned ID) -> Metadata * {
1892 return MetadataList.getValueFwdRef(ID);
1893 };
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001894 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1895 if (ID)
1896 return getMD(ID - 1);
1897 return nullptr;
1898 };
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001899 auto getMDString = [&](unsigned ID) -> MDString *{
1900 // This requires that the ID is not really a forward reference. In
1901 // particular, the MDString must already have been resolved.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001902 return cast_or_null<MDString>(getMDOrNull(ID));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001903 };
1904
1905#define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1906 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1907
Devang Patel7428d8a2009-07-22 17:43:22 +00001908 // Read all the records.
1909 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001910 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001911
Chris Lattner27d38752013-01-20 02:13:19 +00001912 switch (Entry.Kind) {
1913 case BitstreamEntry::SubBlock: // Handled for us already.
1914 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001915 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001916 case BitstreamEntry::EndBlock:
Teresa Johnson61b406e2015-12-29 23:00:22 +00001917 MetadataList.tryToResolveCycles();
Teresa Johnson16e2a9e2015-11-21 03:51:23 +00001918 assert((!(ModuleLevel && SeenModuleValuesRecord) ||
Teresa Johnson61b406e2015-12-29 23:00:22 +00001919 NumModuleMDs == MetadataList.size()) &&
Teresa Johnson16e2a9e2015-11-21 03:51:23 +00001920 "Inconsistent bitcode: METADATA_VALUES mismatch");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001921 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001922 case BitstreamEntry::Record:
1923 // The interesting case.
1924 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00001925 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001926
Devang Patel7428d8a2009-07-22 17:43:22 +00001927 // Read a record.
1928 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001929 unsigned Code = Stream.readRecord(Entry.ID, Record);
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001930 bool IsDistinct = false;
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00001931 switch (Code) {
Devang Patel7428d8a2009-07-22 17:43:22 +00001932 default: // Default behavior: ignore.
1933 break;
Devang Patel27c87ff2009-07-29 22:34:41 +00001934 case bitc::METADATA_NAME: {
Chris Lattner8d140532013-01-20 02:54:05 +00001935 // Read name of the named metadata.
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001936 SmallString<8> Name(Record.begin(), Record.end());
Devang Patel27c87ff2009-07-29 22:34:41 +00001937 Record.clear();
1938 Code = Stream.ReadCode();
1939
Chris Lattner27d38752013-01-20 02:13:19 +00001940 unsigned NextBitCode = Stream.readRecord(Code, Record);
Filipe Cabecinhas14e68672015-05-30 00:17:20 +00001941 if (NextBitCode != bitc::METADATA_NAMED_NODE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001942 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
Devang Patel27c87ff2009-07-29 22:34:41 +00001943
1944 // Read named metadata elements.
1945 unsigned Size = Record.size();
Dan Gohman2637cc12010-07-21 23:38:33 +00001946 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patel27c87ff2009-07-29 22:34:41 +00001947 for (unsigned i = 0; i != Size; ++i) {
Teresa Johnson61b406e2015-12-29 23:00:22 +00001948 MDNode *MD =
1949 dyn_cast_or_null<MDNode>(MetadataList.getValueFwdRef(Record[i]));
Craig Topper2617dcc2014-04-15 06:32:26 +00001950 if (!MD)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001951 return error("Invalid record");
Dan Gohman2637cc12010-07-21 23:38:33 +00001952 NMD->addOperand(MD);
Devang Patel27c87ff2009-07-29 22:34:41 +00001953 }
Devang Patel27c87ff2009-07-29 22:34:41 +00001954 break;
1955 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00001956 case bitc::METADATA_OLD_FN_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00001957 // FIXME: Remove in 4.0.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001958 // This is a LocalAsMetadata record, the only type of function-local
1959 // metadata.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001960 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001961 return error("Invalid record");
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001962
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001963 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1964 // to be legal, but there's no upgrade path.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001965 auto dropRecord = [&] {
Teresa Johnson61b406e2015-12-29 23:00:22 +00001966 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001967 };
1968 if (Record.size() != 2) {
1969 dropRecord();
1970 break;
1971 }
1972
1973 Type *Ty = getTypeByID(Record[0]);
1974 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1975 dropRecord();
1976 break;
1977 }
1978
Teresa Johnson61b406e2015-12-29 23:00:22 +00001979 MetadataList.assignValue(
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001980 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00001981 NextMetadataNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001982 break;
1983 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00001984 case bitc::METADATA_OLD_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00001985 // FIXME: Remove in 4.0.
Dan Gohman1e0213a2010-07-13 19:33:27 +00001986 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001987 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001988
Devang Patele059ba6e2009-07-23 01:07:34 +00001989 unsigned Size = Record.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001990 SmallVector<Metadata *, 8> Elts;
Devang Patele059ba6e2009-07-23 01:07:34 +00001991 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00001992 Type *Ty = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00001993 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001994 return error("Invalid record");
Chris Lattnerfdd87902009-10-05 05:54:46 +00001995 if (Ty->isMetadataTy())
Teresa Johnson61b406e2015-12-29 23:00:22 +00001996 Elts.push_back(MetadataList.getValueFwdRef(Record[i + 1]));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001997 else if (!Ty->isVoidTy()) {
1998 auto *MD =
1999 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2000 assert(isa<ConstantAsMetadata>(MD) &&
2001 "Expected non-function-local metadata");
2002 Elts.push_back(MD);
2003 } else
Craig Topper2617dcc2014-04-15 06:32:26 +00002004 Elts.push_back(nullptr);
Devang Patele059ba6e2009-07-23 01:07:34 +00002005 }
Teresa Johnson61b406e2015-12-29 23:00:22 +00002006 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++);
Devang Patele059ba6e2009-07-23 01:07:34 +00002007 break;
2008 }
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002009 case bitc::METADATA_VALUE: {
2010 if (Record.size() != 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002011 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002012
2013 Type *Ty = getTypeByID(Record[0]);
2014 if (Ty->isMetadataTy() || Ty->isVoidTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002015 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002016
Teresa Johnson61b406e2015-12-29 23:00:22 +00002017 MetadataList.assignValue(
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002018 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002019 NextMetadataNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002020 break;
2021 }
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00002022 case bitc::METADATA_DISTINCT_NODE:
2023 IsDistinct = true;
2024 // fallthrough...
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002025 case bitc::METADATA_NODE: {
2026 SmallVector<Metadata *, 8> Elts;
2027 Elts.reserve(Record.size());
2028 for (unsigned ID : Record)
Teresa Johnson61b406e2015-12-29 23:00:22 +00002029 Elts.push_back(ID ? MetadataList.getValueFwdRef(ID - 1) : nullptr);
2030 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2031 : MDNode::get(Context, Elts),
2032 NextMetadataNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002033 break;
2034 }
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002035 case bitc::METADATA_LOCATION: {
2036 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002037 return error("Invalid record");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002038
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002039 unsigned Line = Record[1];
2040 unsigned Column = Record[2];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002041 MDNode *Scope = cast<MDNode>(MetadataList.getValueFwdRef(Record[3]));
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002042 Metadata *InlinedAt =
Teresa Johnson61b406e2015-12-29 23:00:22 +00002043 Record[4] ? MetadataList.getValueFwdRef(Record[4] - 1) : nullptr;
2044 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002045 GET_OR_DISTINCT(DILocation, Record[0],
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00002046 (Context, Line, Column, Scope, InlinedAt)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002047 NextMetadataNo++);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002048 break;
2049 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002050 case bitc::METADATA_GENERIC_DEBUG: {
2051 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002052 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002053
2054 unsigned Tag = Record[1];
2055 unsigned Version = Record[2];
2056
2057 if (Tag >= 1u << 16 || Version != 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002058 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002059
2060 auto *Header = getMDString(Record[3]);
2061 SmallVector<Metadata *, 8> DwarfOps;
2062 for (unsigned I = 4, E = Record.size(); I != E; ++I)
Teresa Johnson61b406e2015-12-29 23:00:22 +00002063 DwarfOps.push_back(
2064 Record[I] ? MetadataList.getValueFwdRef(Record[I] - 1) : nullptr);
2065 MetadataList.assignValue(
2066 GET_OR_DISTINCT(GenericDINode, Record[0],
2067 (Context, Tag, Header, DwarfOps)),
2068 NextMetadataNo++);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002069 break;
2070 }
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002071 case bitc::METADATA_SUBRANGE: {
2072 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002073 return error("Invalid record");
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002074
Teresa Johnson61b406e2015-12-29 23:00:22 +00002075 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002076 GET_OR_DISTINCT(DISubrange, Record[0],
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002077 (Context, Record[1], unrotateSign(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002078 NextMetadataNo++);
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002079 break;
2080 }
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002081 case bitc::METADATA_ENUMERATOR: {
2082 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002083 return error("Invalid record");
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002084
Teresa Johnson61b406e2015-12-29 23:00:22 +00002085 MetadataList.assignValue(
2086 GET_OR_DISTINCT(
2087 DIEnumerator, Record[0],
2088 (Context, unrotateSign(Record[1]), getMDString(Record[2]))),
2089 NextMetadataNo++);
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002090 break;
2091 }
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002092 case bitc::METADATA_BASIC_TYPE: {
2093 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002094 return error("Invalid record");
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002095
Teresa Johnson61b406e2015-12-29 23:00:22 +00002096 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002097 GET_OR_DISTINCT(DIBasicType, Record[0],
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002098 (Context, Record[1], getMDString(Record[2]),
2099 Record[3], Record[4], Record[5])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002100 NextMetadataNo++);
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002101 break;
2102 }
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002103 case bitc::METADATA_DERIVED_TYPE: {
2104 if (Record.size() != 12)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002105 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002106
Teresa Johnson61b406e2015-12-29 23:00:22 +00002107 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002108 GET_OR_DISTINCT(DIDerivedType, Record[0],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002109 (Context, Record[1], getMDString(Record[2]),
2110 getMDOrNull(Record[3]), Record[4],
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00002111 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2112 Record[7], Record[8], Record[9], Record[10],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002113 getMDOrNull(Record[11]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002114 NextMetadataNo++);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002115 break;
2116 }
2117 case bitc::METADATA_COMPOSITE_TYPE: {
2118 if (Record.size() != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002119 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002120
Teresa Johnson61b406e2015-12-29 23:00:22 +00002121 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002122 GET_OR_DISTINCT(DICompositeType, Record[0],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002123 (Context, Record[1], getMDString(Record[2]),
2124 getMDOrNull(Record[3]), Record[4],
2125 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2126 Record[7], Record[8], Record[9], Record[10],
2127 getMDOrNull(Record[11]), Record[12],
2128 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2129 getMDString(Record[15]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002130 NextMetadataNo++);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002131 break;
2132 }
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002133 case bitc::METADATA_SUBROUTINE_TYPE: {
2134 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002135 return error("Invalid record");
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002136
Teresa Johnson61b406e2015-12-29 23:00:22 +00002137 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002138 GET_OR_DISTINCT(DISubroutineType, Record[0],
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002139 (Context, Record[1], getMDOrNull(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002140 NextMetadataNo++);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002141 break;
2142 }
Adrian Prantlab1243f2015-06-29 23:03:47 +00002143
2144 case bitc::METADATA_MODULE: {
2145 if (Record.size() != 6)
2146 return error("Invalid record");
2147
Teresa Johnson61b406e2015-12-29 23:00:22 +00002148 MetadataList.assignValue(
Adrian Prantlab1243f2015-06-29 23:03:47 +00002149 GET_OR_DISTINCT(DIModule, Record[0],
2150 (Context, getMDOrNull(Record[1]),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002151 getMDString(Record[2]), getMDString(Record[3]),
2152 getMDString(Record[4]), getMDString(Record[5]))),
2153 NextMetadataNo++);
Adrian Prantlab1243f2015-06-29 23:03:47 +00002154 break;
2155 }
2156
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002157 case bitc::METADATA_FILE: {
2158 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002159 return error("Invalid record");
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002160
Teresa Johnson61b406e2015-12-29 23:00:22 +00002161 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002162 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002163 getMDString(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002164 NextMetadataNo++);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002165 break;
2166 }
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002167 case bitc::METADATA_COMPILE_UNIT: {
Amjad Abouda9bcf162015-12-10 12:56:35 +00002168 if (Record.size() < 14 || Record.size() > 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002169 return error("Invalid record");
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002170
Amjad Abouda9bcf162015-12-10 12:56:35 +00002171 // Ignore Record[0], which indicates whether this compile unit is
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00002172 // distinct. It's always distinct.
Teresa Johnson61b406e2015-12-29 23:00:22 +00002173 MetadataList.assignValue(
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00002174 DICompileUnit::getDistinct(
2175 Context, Record[1], getMDOrNull(Record[2]),
2176 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2177 Record[6], getMDString(Record[7]), Record[8],
2178 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2179 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
Amjad Abouda9bcf162015-12-10 12:56:35 +00002180 getMDOrNull(Record[13]),
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00002181 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
Amjad Abouda9bcf162015-12-10 12:56:35 +00002182 Record.size() <= 14 ? 0 : Record[14]),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002183 NextMetadataNo++);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002184 break;
2185 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002186 case bitc::METADATA_SUBPROGRAM: {
Peter Collingbourned4bff302015-11-05 22:03:56 +00002187 if (Record.size() != 18 && Record.size() != 19)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002188 return error("Invalid record");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002189
Peter Collingbourned4bff302015-11-05 22:03:56 +00002190 bool HasFn = Record.size() == 19;
2191 DISubprogram *SP = GET_OR_DISTINCT(
2192 DISubprogram,
2193 Record[0] || Record[8], // All definitions should be distinct.
2194 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2195 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2196 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2197 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2198 Record[14], getMDOrNull(Record[15 + HasFn]),
2199 getMDOrNull(Record[16 + HasFn]), getMDOrNull(Record[17 + HasFn])));
Teresa Johnson61b406e2015-12-29 23:00:22 +00002200 MetadataList.assignValue(SP, NextMetadataNo++);
Peter Collingbourned4bff302015-11-05 22:03:56 +00002201
2202 // Upgrade sp->function mapping to function->sp mapping.
2203 if (HasFn && Record[15]) {
2204 if (auto *CMD = dyn_cast<ConstantAsMetadata>(getMDOrNull(Record[15])))
2205 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2206 if (F->isMaterializable())
2207 // Defer until materialized; unmaterialized functions may not have
2208 // metadata.
2209 FunctionsWithSPs[F] = SP;
2210 else if (!F->empty())
2211 F->setSubprogram(SP);
2212 }
2213 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002214 break;
2215 }
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002216 case bitc::METADATA_LEXICAL_BLOCK: {
2217 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002218 return error("Invalid record");
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002219
Teresa Johnson61b406e2015-12-29 23:00:22 +00002220 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002221 GET_OR_DISTINCT(DILexicalBlock, Record[0],
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002222 (Context, getMDOrNull(Record[1]),
2223 getMDOrNull(Record[2]), Record[3], Record[4])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002224 NextMetadataNo++);
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002225 break;
2226 }
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002227 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2228 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002229 return error("Invalid record");
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002230
Teresa Johnson61b406e2015-12-29 23:00:22 +00002231 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002232 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002233 (Context, getMDOrNull(Record[1]),
2234 getMDOrNull(Record[2]), Record[3])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002235 NextMetadataNo++);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002236 break;
2237 }
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002238 case bitc::METADATA_NAMESPACE: {
2239 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002240 return error("Invalid record");
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002241
Teresa Johnson61b406e2015-12-29 23:00:22 +00002242 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002243 GET_OR_DISTINCT(DINamespace, Record[0],
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002244 (Context, getMDOrNull(Record[1]),
2245 getMDOrNull(Record[2]), getMDString(Record[3]),
2246 Record[4])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002247 NextMetadataNo++);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002248 break;
2249 }
Amjad Abouda9bcf162015-12-10 12:56:35 +00002250 case bitc::METADATA_MACRO: {
2251 if (Record.size() != 5)
2252 return error("Invalid record");
2253
Teresa Johnson61b406e2015-12-29 23:00:22 +00002254 MetadataList.assignValue(
Amjad Abouda9bcf162015-12-10 12:56:35 +00002255 GET_OR_DISTINCT(DIMacro, Record[0],
2256 (Context, Record[1], Record[2],
2257 getMDString(Record[3]), getMDString(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002258 NextMetadataNo++);
Amjad Abouda9bcf162015-12-10 12:56:35 +00002259 break;
2260 }
2261 case bitc::METADATA_MACRO_FILE: {
2262 if (Record.size() != 5)
2263 return error("Invalid record");
2264
Teresa Johnson61b406e2015-12-29 23:00:22 +00002265 MetadataList.assignValue(
Amjad Abouda9bcf162015-12-10 12:56:35 +00002266 GET_OR_DISTINCT(DIMacroFile, Record[0],
2267 (Context, Record[1], Record[2],
2268 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002269 NextMetadataNo++);
Amjad Abouda9bcf162015-12-10 12:56:35 +00002270 break;
2271 }
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002272 case bitc::METADATA_TEMPLATE_TYPE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002273 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002274 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002275
Teresa Johnson61b406e2015-12-29 23:00:22 +00002276 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2277 Record[0],
2278 (Context, getMDString(Record[1]),
2279 getMDOrNull(Record[2]))),
2280 NextMetadataNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002281 break;
2282 }
2283 case bitc::METADATA_TEMPLATE_VALUE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002284 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002285 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002286
Teresa Johnson61b406e2015-12-29 23:00:22 +00002287 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002288 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002289 (Context, Record[1], getMDString(Record[2]),
2290 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002291 NextMetadataNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002292 break;
2293 }
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002294 case bitc::METADATA_GLOBAL_VAR: {
2295 if (Record.size() != 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002296 return error("Invalid record");
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002297
Teresa Johnson61b406e2015-12-29 23:00:22 +00002298 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002299 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002300 (Context, getMDOrNull(Record[1]),
2301 getMDString(Record[2]), getMDString(Record[3]),
2302 getMDOrNull(Record[4]), Record[5],
2303 getMDOrNull(Record[6]), Record[7], Record[8],
2304 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002305 NextMetadataNo++);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002306 break;
2307 }
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002308 case bitc::METADATA_LOCAL_VAR: {
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00002309 // 10th field is for the obseleted 'inlinedAt:' field.
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002310 if (Record.size() < 8 || Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002311 return error("Invalid record");
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002312
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002313 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2314 // DW_TAG_arg_variable.
2315 bool HasTag = Record.size() > 8;
Teresa Johnson61b406e2015-12-29 23:00:22 +00002316 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002317 GET_OR_DISTINCT(DILocalVariable, Record[0],
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002318 (Context, getMDOrNull(Record[1 + HasTag]),
2319 getMDString(Record[2 + HasTag]),
2320 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2321 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2322 Record[7 + HasTag])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002323 NextMetadataNo++);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002324 break;
2325 }
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002326 case bitc::METADATA_EXPRESSION: {
2327 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002328 return error("Invalid record");
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002329
Teresa Johnson61b406e2015-12-29 23:00:22 +00002330 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002331 GET_OR_DISTINCT(DIExpression, Record[0],
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002332 (Context, makeArrayRef(Record).slice(1))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002333 NextMetadataNo++);
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002334 break;
2335 }
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002336 case bitc::METADATA_OBJC_PROPERTY: {
2337 if (Record.size() != 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002338 return error("Invalid record");
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002339
Teresa Johnson61b406e2015-12-29 23:00:22 +00002340 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002341 GET_OR_DISTINCT(DIObjCProperty, Record[0],
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002342 (Context, getMDString(Record[1]),
2343 getMDOrNull(Record[2]), Record[3],
2344 getMDString(Record[4]), getMDString(Record[5]),
2345 Record[6], getMDOrNull(Record[7]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002346 NextMetadataNo++);
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002347 break;
2348 }
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002349 case bitc::METADATA_IMPORTED_ENTITY: {
2350 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002351 return error("Invalid record");
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002352
Teresa Johnson61b406e2015-12-29 23:00:22 +00002353 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002354 GET_OR_DISTINCT(DIImportedEntity, Record[0],
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002355 (Context, Record[1], getMDOrNull(Record[2]),
2356 getMDOrNull(Record[3]), Record[4],
2357 getMDString(Record[5]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002358 NextMetadataNo++);
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002359 break;
2360 }
Devang Patel7428d8a2009-07-22 17:43:22 +00002361 case bitc::METADATA_STRING: {
Eli Bendersky5d5e18d2014-06-25 15:41:00 +00002362 std::string String(Record.begin(), Record.end());
2363 llvm::UpgradeMDStringConstant(String);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002364 Metadata *MD = MDString::get(Context, String);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002365 MetadataList.assignValue(MD, NextMetadataNo++);
Devang Patel7428d8a2009-07-22 17:43:22 +00002366 break;
2367 }
Devang Patelaf206b82009-09-18 19:26:43 +00002368 case bitc::METADATA_KIND: {
Teresa Johnson12545072015-11-15 02:00:09 +00002369 // Support older bitcode files that had METADATA_KIND records in a
2370 // block with METADATA_BLOCK_ID.
2371 if (std::error_code EC = parseMetadataKindRecord(Record))
2372 return EC;
Devang Patelaf206b82009-09-18 19:26:43 +00002373 break;
2374 }
Devang Patel7428d8a2009-07-22 17:43:22 +00002375 }
2376 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002377#undef GET_OR_DISTINCT
Devang Patel7428d8a2009-07-22 17:43:22 +00002378}
2379
Teresa Johnson12545072015-11-15 02:00:09 +00002380/// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2381std::error_code BitcodeReader::parseMetadataKinds() {
2382 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2383 return error("Invalid record");
2384
2385 SmallVector<uint64_t, 64> Record;
2386
2387 // Read all the records.
2388 while (1) {
2389 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2390
2391 switch (Entry.Kind) {
2392 case BitstreamEntry::SubBlock: // Handled for us already.
2393 case BitstreamEntry::Error:
2394 return error("Malformed block");
2395 case BitstreamEntry::EndBlock:
2396 return std::error_code();
2397 case BitstreamEntry::Record:
2398 // The interesting case.
2399 break;
2400 }
2401
2402 // Read a record.
2403 Record.clear();
2404 unsigned Code = Stream.readRecord(Entry.ID, Record);
2405 switch (Code) {
2406 default: // Default behavior: ignore.
2407 break;
2408 case bitc::METADATA_KIND: {
2409 if (std::error_code EC = parseMetadataKindRecord(Record))
2410 return EC;
2411 break;
2412 }
2413 }
2414 }
2415}
2416
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002417/// Decode a signed value stored with the sign bit in the LSB for dense VBR
2418/// encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002419uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00002420 if ((V & 1) == 0)
2421 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002422 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00002423 return -(V >> 1);
2424 // There is no such thing as -0 with integers. "-0" really means MININT.
2425 return 1ULL << 63;
2426}
2427
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002428/// Resolve all of the initializers for global values and aliases that we can.
2429std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00002430 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2431 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002432 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002433 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
David Majnemer7fddecc2015-06-17 20:52:32 +00002434 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002435
Chris Lattner44c17072007-04-26 02:46:40 +00002436 GlobalInitWorklist.swap(GlobalInits);
2437 AliasInitWorklist.swap(AliasInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002438 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002439 FunctionPrologueWorklist.swap(FunctionPrologues);
David Majnemer7fddecc2015-06-17 20:52:32 +00002440 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
Chris Lattner44c17072007-04-26 02:46:40 +00002441
2442 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00002443 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002444 if (ValID >= ValueList.size()) {
2445 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00002446 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002447 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002448 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00002449 GlobalInitWorklist.back().first->setInitializer(C);
2450 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002451 return error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00002452 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002453 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002454 }
2455
2456 while (!AliasInitWorklist.empty()) {
2457 unsigned ValID = AliasInitWorklist.back().second;
2458 if (ValID >= ValueList.size()) {
2459 AliasInits.push_back(AliasInitWorklist.back());
2460 } else {
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002461 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2462 if (!C)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002463 return error("Expected a constant");
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002464 GlobalAlias *Alias = AliasInitWorklist.back().first;
2465 if (C->getType() != Alias->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002466 return error("Alias and aliasee types don't match");
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002467 Alias->setAliasee(C);
Chris Lattner44c17072007-04-26 02:46:40 +00002468 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002469 AliasInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002470 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002471
2472 while (!FunctionPrefixWorklist.empty()) {
2473 unsigned ValID = FunctionPrefixWorklist.back().second;
2474 if (ValID >= ValueList.size()) {
2475 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2476 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002477 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002478 FunctionPrefixWorklist.back().first->setPrefixData(C);
2479 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002480 return error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002481 }
2482 FunctionPrefixWorklist.pop_back();
2483 }
2484
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002485 while (!FunctionPrologueWorklist.empty()) {
2486 unsigned ValID = FunctionPrologueWorklist.back().second;
2487 if (ValID >= ValueList.size()) {
2488 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2489 } else {
2490 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2491 FunctionPrologueWorklist.back().first->setPrologueData(C);
2492 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002493 return error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002494 }
2495 FunctionPrologueWorklist.pop_back();
2496 }
2497
David Majnemer7fddecc2015-06-17 20:52:32 +00002498 while (!FunctionPersonalityFnWorklist.empty()) {
2499 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2500 if (ValID >= ValueList.size()) {
2501 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2502 } else {
2503 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2504 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2505 else
2506 return error("Expected a constant");
2507 }
2508 FunctionPersonalityFnWorklist.pop_back();
2509 }
2510
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002511 return std::error_code();
Chris Lattner44c17072007-04-26 02:46:40 +00002512}
2513
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002514static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002515 SmallVector<uint64_t, 8> Words(Vals.size());
2516 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00002517 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002518
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002519 return APInt(TypeBits, Words);
2520}
2521
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002522std::error_code BitcodeReader::parseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002523 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002524 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002525
2526 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002527
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002528 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00002529 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00002530 unsigned NextCstNo = ValueList.size();
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002531 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002532 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002533
Chris Lattner27d38752013-01-20 02:13:19 +00002534 switch (Entry.Kind) {
2535 case BitstreamEntry::SubBlock: // Handled for us already.
2536 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002537 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002538 case BitstreamEntry::EndBlock:
2539 if (NextCstNo != ValueList.size())
George Burgess IV1030d682016-01-20 22:15:23 +00002540 return error("Invalid constant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00002541
Chris Lattner27d38752013-01-20 02:13:19 +00002542 // Once all the constants have been read, go through and resolve forward
2543 // references.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002544 ValueList.resolveConstantForwardRefs();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002545 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002546 case BitstreamEntry::Record:
2547 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00002548 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002549 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002550
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002551 // Read a record.
2552 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00002553 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002554 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002555 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002556 default: // Default behavior: unknown constant
2557 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00002558 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002559 break;
2560 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2561 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002562 return error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00002563 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002564 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002565 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00002566 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002567 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00002568 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002569 break;
2570 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002571 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002572 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002573 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00002574 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00002575 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002576 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002577 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002578
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002579 APInt VInt =
2580 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002581 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002582
Chris Lattner08feb1e2007-04-24 04:04:35 +00002583 break;
2584 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002585 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00002586 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002587 return error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00002588 if (CurTy->isHalfTy())
Tim Northover29178a32013-01-22 09:46:31 +00002589 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2590 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00002591 else if (CurTy->isFloatTy())
Tim Northover29178a32013-01-22 09:46:31 +00002592 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2593 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002594 else if (CurTy->isDoubleTy())
Tim Northover29178a32013-01-22 09:46:31 +00002595 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2596 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002597 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00002598 // Bits are not stored the same way as a normal i80 APInt, compensate.
2599 uint64_t Rearrange[2];
2600 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2601 Rearrange[1] = Record[0] >> 48;
Tim Northover29178a32013-01-22 09:46:31 +00002602 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2603 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002604 } else if (CurTy->isFP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002605 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2606 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002607 else if (CurTy->isPPC_FP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002608 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2609 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002610 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00002611 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002612 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00002613 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002614
Chris Lattnere14cb882007-05-04 19:11:41 +00002615 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2616 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002617 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002618
Chris Lattnere14cb882007-05-04 19:11:41 +00002619 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00002620 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002621
Chris Lattner229907c2011-07-18 04:54:35 +00002622 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00002623 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002624 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00002625 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00002626 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002627 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2628 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002629 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002630 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00002631 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002632 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2633 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002634 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002635 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00002636 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00002637 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002638 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00002639 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002640 break;
2641 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002642 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00002643 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2644 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002645 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002646
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002647 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002648 V = ConstantDataArray::getString(Context, Elts,
2649 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00002650 break;
2651 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002652 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2653 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002654 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002655
Chris Lattner372dd1e2012-01-30 00:51:16 +00002656 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
Chris Lattner372dd1e2012-01-30 00:51:16 +00002657 if (EltTy->isIntegerTy(8)) {
2658 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2659 if (isa<VectorType>(CurTy))
2660 V = ConstantDataVector::get(Context, Elts);
2661 else
2662 V = ConstantDataArray::get(Context, Elts);
2663 } else if (EltTy->isIntegerTy(16)) {
2664 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2665 if (isa<VectorType>(CurTy))
2666 V = ConstantDataVector::get(Context, Elts);
2667 else
2668 V = ConstantDataArray::get(Context, Elts);
2669 } else if (EltTy->isIntegerTy(32)) {
2670 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2671 if (isa<VectorType>(CurTy))
2672 V = ConstantDataVector::get(Context, Elts);
2673 else
2674 V = ConstantDataArray::get(Context, Elts);
2675 } else if (EltTy->isIntegerTy(64)) {
2676 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2677 if (isa<VectorType>(CurTy))
2678 V = ConstantDataVector::get(Context, Elts);
2679 else
2680 V = ConstantDataArray::get(Context, Elts);
Justin Bognera43eacb2016-01-06 22:31:32 +00002681 } else if (EltTy->isHalfTy()) {
2682 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2683 if (isa<VectorType>(CurTy))
2684 V = ConstantDataVector::getFP(Context, Elts);
2685 else
2686 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002687 } else if (EltTy->isFloatTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00002688 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002689 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00002690 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002691 else
Justin Bognera43eacb2016-01-06 22:31:32 +00002692 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002693 } else if (EltTy->isDoubleTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00002694 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002695 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00002696 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002697 else
Justin Bognera43eacb2016-01-06 22:31:32 +00002698 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002699 } else {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002700 return error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00002701 }
2702 break;
2703 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002704 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002705 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002706 return error("Invalid record");
2707 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002708 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002709 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00002710 } else {
2711 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2712 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00002713 unsigned Flags = 0;
2714 if (Record.size() >= 4) {
2715 if (Opc == Instruction::Add ||
2716 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002717 Opc == Instruction::Mul ||
2718 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00002719 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2720 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2721 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2722 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002723 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002724 Opc == Instruction::UDiv ||
2725 Opc == Instruction::LShr ||
2726 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00002727 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00002728 Flags |= SDivOperator::IsExact;
2729 }
2730 }
2731 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00002732 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002733 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002734 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002735 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002736 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002737 return error("Invalid record");
2738 int Opc = getDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00002739 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002740 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00002741 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002742 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002743 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002744 return error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00002745 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002746 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2747 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002748 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002749 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002750 }
Dan Gohman1639c392009-07-27 21:53:46 +00002751 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002752 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
David Blaikieb9263572015-03-13 21:03:36 +00002753 unsigned OpNum = 0;
2754 Type *PointeeType = nullptr;
2755 if (Record.size() % 2)
2756 PointeeType = getTypeByID(Record[OpNum++]);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002757 SmallVector<Constant*, 16> Elts;
David Blaikieb9263572015-03-13 21:03:36 +00002758 while (OpNum != Record.size()) {
2759 Type *ElTy = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002760 if (!ElTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002761 return error("Invalid record");
David Blaikieb9263572015-03-13 21:03:36 +00002762 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002763 }
David Blaikieb9263572015-03-13 21:03:36 +00002764
David Blaikieb9263572015-03-13 21:03:36 +00002765 if (PointeeType &&
David Blaikie4a2e73b2015-04-02 18:55:32 +00002766 PointeeType !=
2767 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2768 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002769 return error("Explicit gep operator type does not match pointee type "
David Blaikie12cf5d702015-03-16 22:03:50 +00002770 "of pointer operand");
David Blaikie4a2e73b2015-04-02 18:55:32 +00002771
2772 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2773 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2774 BitCode ==
2775 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattner890683d2007-04-24 18:15:21 +00002776 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002777 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00002778 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002779 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002780 return error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00002781
2782 Type *SelectorTy = Type::getInt1Ty(Context);
2783
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00002784 // The selector might be an i1 or an <n x i1>
2785 // Get the type from the ValueList before getting a forward ref.
Joe Abbey1a6e7702013-09-12 22:02:31 +00002786 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00002787 if (Value *V = ValueList[Record[0]])
2788 if (SelectorTy != V->getType())
2789 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
Joe Abbey1a6e7702013-09-12 22:02:31 +00002790
2791 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2792 SelectorTy),
2793 ValueList.getConstantFwdRef(Record[1],CurTy),
2794 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002795 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00002796 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002797 case bitc::CST_CODE_CE_EXTRACTELT
2798 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002799 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002800 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002801 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002802 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002803 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002804 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002805 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002806 Constant *Op1 = nullptr;
2807 if (Record.size() == 4) {
2808 Type *IdxTy = getTypeByID(Record[2]);
2809 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002810 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002811 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2812 } else // TODO: Remove with llvm 4.0
2813 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2814 if (!Op1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002815 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002816 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002817 break;
2818 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002819 case bitc::CST_CODE_CE_INSERTELT
2820 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002821 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002822 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002823 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002824 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2825 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2826 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002827 Constant *Op2 = nullptr;
2828 if (Record.size() == 4) {
2829 Type *IdxTy = getTypeByID(Record[2]);
2830 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002831 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002832 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2833 } else // TODO: Remove with llvm 4.0
2834 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2835 if (!Op2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002836 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002837 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002838 break;
2839 }
2840 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002841 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002842 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002843 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002844 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2845 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002846 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002847 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002848 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002849 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002850 break;
2851 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00002852 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002853 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2854 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00002855 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002856 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002857 return error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002858 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2859 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002860 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002861 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00002862 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002863 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00002864 break;
2865 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002866 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002867 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002868 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002869 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002870 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002871 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002872 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2873 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2874
Duncan Sands9dff9be2010-02-15 16:12:20 +00002875 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002876 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00002877 else
Owen Anderson487375e2009-07-29 18:55:55 +00002878 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002879 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00002880 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002881 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00002882 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002883 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002884 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002885 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002886 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00002887 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002888 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002889 unsigned AsmStrSize = Record[1];
2890 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002891 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002892 unsigned ConstStrSize = Record[2+AsmStrSize];
2893 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002894 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002895
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002896 for (unsigned i = 0; i != AsmStrSize; ++i)
2897 AsmStr += (char)Record[2+i];
2898 for (unsigned i = 0; i != ConstStrSize; ++i)
2899 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00002900 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002901 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002902 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002903 break;
2904 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002905 // This version adds support for the asm dialect keywords (e.g.,
2906 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002907 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002908 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002909 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002910 std::string AsmStr, ConstrStr;
2911 bool HasSideEffects = Record[0] & 1;
2912 bool IsAlignStack = (Record[0] >> 1) & 1;
2913 unsigned AsmDialect = Record[0] >> 2;
2914 unsigned AsmStrSize = Record[1];
2915 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002916 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56: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");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002920
2921 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];
2925 PointerType *PTy = cast<PointerType>(CurTy);
2926 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2927 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00002928 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002929 break;
2930 }
Chris Lattner5956dc82009-10-28 05:53:48 +00002931 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00002932 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002933 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002934 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002935 if (!FnTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002936 return error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00002937 Function *Fn =
2938 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00002939 if (!Fn)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002940 return error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002941
2942 // If the function is already parsed we can insert the block address right
2943 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002944 BasicBlock *BB;
2945 unsigned BBID = Record[2];
2946 if (!BBID)
2947 // Invalid reference to entry block.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002948 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002949 if (!Fn->empty()) {
2950 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002951 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002952 if (BBI == BBE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002953 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002954 ++BBI;
2955 }
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00002956 BB = &*BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002957 } else {
2958 // Otherwise insert a placeholder and remember it so it can be inserted
2959 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00002960 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2961 if (FwdBBs.empty())
2962 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00002963 if (FwdBBs.size() < BBID + 1)
2964 FwdBBs.resize(BBID + 1);
2965 if (!FwdBBs[BBID])
2966 FwdBBs[BBID] = BasicBlock::Create(Context);
2967 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002968 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002969 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00002970 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002971 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002972 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002973
David Majnemer8a1c45d2015-12-12 05:38:55 +00002974 ValueList.assignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00002975 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002976 }
2977}
Chris Lattner1314b992007-04-22 06:23:29 +00002978
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002979std::error_code BitcodeReader::parseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00002980 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002981 return error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00002982
Chad Rosierca2567b2011-12-07 21:44:12 +00002983 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002984 SmallVector<uint64_t, 64> Record;
Chad Rosierca2567b2011-12-07 21:44:12 +00002985 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002986 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002987
Chris Lattner27d38752013-01-20 02:13:19 +00002988 switch (Entry.Kind) {
2989 case BitstreamEntry::SubBlock: // Handled for us already.
2990 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002991 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002992 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002993 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002994 case BitstreamEntry::Record:
2995 // The interesting case.
2996 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00002997 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002998
Chad Rosierca2567b2011-12-07 21:44:12 +00002999 // Read a use list record.
3000 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003001 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00003002 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00003003 default: // Default behavior: unknown type.
3004 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003005 case bitc::USELIST_CODE_BB:
3006 IsBB = true;
3007 // fallthrough
3008 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00003009 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003010 if (RecordLength < 3)
3011 // Records should have at least an ID and two indexes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003012 return error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003013 unsigned ID = Record.back();
3014 Record.pop_back();
3015
3016 Value *V;
3017 if (IsBB) {
3018 assert(ID < FunctionBBs.size() && "Basic block not found");
3019 V = FunctionBBs[ID];
3020 } else
3021 V = ValueList[ID];
3022 unsigned NumUses = 0;
3023 SmallDenseMap<const Use *, unsigned, 16> Order;
Rafael Espindola257a3532016-01-15 19:00:20 +00003024 for (const Use &U : V->materialized_uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00003025 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003026 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00003027 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003028 }
3029 if (Order.size() != Record.size() || NumUses > Record.size())
3030 // Mismatches can happen if the functions are being materialized lazily
3031 // (out-of-order), or a value has been upgraded.
3032 break;
3033
3034 V->sortUseList([&](const Use &L, const Use &R) {
3035 return Order.lookup(&L) < Order.lookup(&R);
3036 });
Chad Rosierca2567b2011-12-07 21:44:12 +00003037 break;
3038 }
3039 }
3040 }
3041}
3042
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003043/// When we see the block for metadata, remember where it is and then skip it.
3044/// This lets us lazily deserialize the metadata.
3045std::error_code BitcodeReader::rememberAndSkipMetadata() {
3046 // Save the current stream state.
3047 uint64_t CurBit = Stream.GetCurrentBitNo();
3048 DeferredMetadataInfo.push_back(CurBit);
3049
3050 // Skip over the block for now.
3051 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003052 return error("Invalid record");
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003053 return std::error_code();
3054}
3055
3056std::error_code BitcodeReader::materializeMetadata() {
3057 for (uint64_t BitPos : DeferredMetadataInfo) {
3058 // Move the bit stream to the saved position.
3059 Stream.JumpToBit(BitPos);
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003060 if (std::error_code EC = parseMetadata(true))
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003061 return EC;
3062 }
3063 DeferredMetadataInfo.clear();
3064 return std::error_code();
3065}
3066
Rafael Espindola468b8682015-04-01 14:44:59 +00003067void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00003068
Teresa Johnson61b406e2015-12-29 23:00:22 +00003069void BitcodeReader::saveMetadataList(
3070 DenseMap<const Metadata *, unsigned> &MetadataToIDs, bool OnlyTempMD) {
3071 for (unsigned ID = 0; ID < MetadataList.size(); ++ID) {
3072 Metadata *MD = MetadataList[ID];
Teresa Johnsone5a61912015-12-17 17:14:09 +00003073 auto *N = dyn_cast_or_null<MDNode>(MD);
Teresa Johnson26aa9352015-12-30 19:13:57 +00003074 assert((!N || (N->isResolved() || N->isTemporary())) &&
3075 "Found non-resolved non-temp MDNode while saving metadata");
Teresa Johnsone5a61912015-12-17 17:14:09 +00003076 // Save all values if !OnlyTempMD, otherwise just the temporary metadata.
Teresa Johnson26aa9352015-12-30 19:13:57 +00003077 // Note that in the !OnlyTempMD case we need to save all Metadata, not
3078 // just MDNode, as we may have references to other types of module-level
3079 // metadata (e.g. ValueAsMetadata) from instructions.
Teresa Johnsone5a61912015-12-17 17:14:09 +00003080 if (!OnlyTempMD || (N && N->isTemporary())) {
3081 // Will call this after materializing each function, in order to
3082 // handle remapping of the function's instructions/metadata.
Teresa Johnson6f508af2016-01-21 16:46:40 +00003083 auto IterBool = MetadataToIDs.insert(std::make_pair(MD, ID));
Teresa Johnsone5a61912015-12-17 17:14:09 +00003084 // See if we already have an entry in that case.
Teresa Johnson6f508af2016-01-21 16:46:40 +00003085 if (OnlyTempMD && !IterBool.second) {
3086 assert(IterBool.first->second == ID &&
3087 "Inconsistent metadata value id");
Teresa Johnsone5a61912015-12-17 17:14:09 +00003088 continue;
3089 }
Teresa Johnsoncc428572015-12-30 19:32:24 +00003090 if (N && N->isTemporary())
3091 // Ensure that we assert if someone tries to RAUW this temporary
3092 // metadata while it is the key of a map. The flag will be set back
3093 // to true when the saved metadata list is destroyed.
3094 N->setCanReplace(false);
Teresa Johnsone5a61912015-12-17 17:14:09 +00003095 }
3096 }
3097}
3098
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003099/// When we see the block for a function body, remember where it is and then
3100/// skip it. This lets us lazily deserialize the functions.
3101std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003102 // Get the function we are talking about.
3103 if (FunctionsWithBodies.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003104 return error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003105
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003106 Function *Fn = FunctionsWithBodies.back();
3107 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003108
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003109 // Save the current stream state.
3110 uint64_t CurBit = Stream.GetCurrentBitNo();
Teresa Johnson1493ad92015-10-10 14:18:36 +00003111 assert(
3112 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3113 "Mismatch between VST and scanned function offsets");
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003114 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003115
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003116 // Skip over the function block for now.
3117 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003118 return error("Invalid record");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003119 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003120}
3121
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003122std::error_code BitcodeReader::globalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003123 // Patch the initializers for globals and aliases up.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003124 resolveGlobalAndAliasInits();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003125 if (!GlobalInits.empty() || !AliasInits.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003126 return error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003127
3128 // Look for intrinsic functions which need to be upgraded at some point
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003129 for (Function &F : *TheModule) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003130 Function *NewFn;
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003131 if (UpgradeIntrinsicFunction(&F, NewFn))
Rafael Espindola4e721212015-07-02 16:22:40 +00003132 UpgradedIntrinsics[&F] = NewFn;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003133 }
3134
3135 // Look for global variables which need to be renamed.
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003136 for (GlobalVariable &GV : TheModule->globals())
3137 UpgradeGlobalVariable(&GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00003138
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003139 // Force deallocation of memory for these vectors to favor the client that
3140 // want lazy deserialization.
3141 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3142 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003143 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003144}
3145
Teresa Johnson1493ad92015-10-10 14:18:36 +00003146/// Support for lazy parsing of function bodies. This is required if we
3147/// either have an old bitcode file without a VST forward declaration record,
3148/// or if we have an anonymous function being materialized, since anonymous
3149/// functions do not have a name and are therefore not in the VST.
3150std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3151 Stream.JumpToBit(NextUnreadBit);
3152
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003153 if (Stream.AtEndOfStream())
3154 return error("Could not find function in stream");
Teresa Johnson1493ad92015-10-10 14:18:36 +00003155
Filipe Cabecinhas7aae2f22015-11-03 13:48:26 +00003156 if (!SeenFirstFunctionBody)
3157 return error("Trying to materialize functions before seeing function blocks");
3158
Teresa Johnson1493ad92015-10-10 14:18:36 +00003159 // An old bitcode file with the symbol table at the end would have
3160 // finished the parse greedily.
3161 assert(SeenValueSymbolTable);
3162
3163 SmallVector<uint64_t, 64> Record;
3164
3165 while (1) {
3166 BitstreamEntry Entry = Stream.advance();
3167 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003168 default:
3169 return error("Expect SubBlock");
3170 case BitstreamEntry::SubBlock:
3171 switch (Entry.ID) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003172 default:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003173 return error("Expect function block");
3174 case bitc::FUNCTION_BLOCK_ID:
3175 if (std::error_code EC = rememberAndSkipFunctionBody())
3176 return EC;
3177 NextUnreadBit = Stream.GetCurrentBitNo();
3178 return std::error_code();
3179 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00003180 }
3181 }
3182}
3183
Mehdi Amini5d303282015-10-26 18:37:00 +00003184std::error_code BitcodeReader::parseBitcodeVersion() {
3185 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3186 return error("Invalid record");
3187
3188 // Read all the records.
3189 SmallVector<uint64_t, 64> Record;
3190 while (1) {
3191 BitstreamEntry Entry = Stream.advance();
3192
3193 switch (Entry.Kind) {
3194 default:
3195 case BitstreamEntry::Error:
3196 return error("Malformed block");
3197 case BitstreamEntry::EndBlock:
3198 return std::error_code();
3199 case BitstreamEntry::Record:
3200 // The interesting case.
3201 break;
3202 }
3203
3204 // Read a record.
3205 Record.clear();
3206 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3207 switch (BitCode) {
3208 default: // Default behavior: reject
3209 return error("Invalid value");
3210 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3211 // N]
3212 convertToString(Record, 0, ProducerIdentification);
3213 break;
3214 }
3215 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3216 unsigned epoch = (unsigned)Record[0];
3217 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
Oleksiy Vyalov6c2403f2015-10-26 22:37:36 +00003218 return error(
3219 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3220 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
Mehdi Amini5d303282015-10-26 18:37:00 +00003221 }
3222 }
3223 }
3224 }
3225}
3226
Teresa Johnson1493ad92015-10-10 14:18:36 +00003227std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003228 bool ShouldLazyLoadMetadata) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003229 if (ResumeBit)
3230 Stream.JumpToBit(ResumeBit);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003231 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003232 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003233
Chris Lattner1314b992007-04-22 06:23:29 +00003234 SmallVector<uint64_t, 64> Record;
3235 std::vector<std::string> SectionTable;
Gordon Henriksend930f912008-08-17 18:44:35 +00003236 std::vector<std::string> GCTable;
Chris Lattner1314b992007-04-22 06:23:29 +00003237
3238 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00003239 while (1) {
3240 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003241
Chris Lattner27d38752013-01-20 02:13:19 +00003242 switch (Entry.Kind) {
3243 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003244 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003245 case BitstreamEntry::EndBlock:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003246 return globalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00003247
Chris Lattner27d38752013-01-20 02:13:19 +00003248 case BitstreamEntry::SubBlock:
3249 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00003250 default: // Skip unknown content.
3251 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003252 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003253 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003254 case bitc::BLOCKINFO_BLOCK_ID:
3255 if (Stream.ReadBlockInfoBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003256 return error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003257 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003258 case bitc::PARAMATTR_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003259 if (std::error_code EC = parseAttributeBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003260 return EC;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003261 break;
Bill Wendlingba629332013-02-10 23:24:25 +00003262 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003263 if (std::error_code EC = parseAttributeGroupBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003264 return EC;
Bill Wendlingba629332013-02-10 23:24:25 +00003265 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003266 case bitc::TYPE_BLOCK_ID_NEW:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003267 if (std::error_code EC = parseTypeTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003268 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00003269 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00003270 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnsonff642b92015-09-17 20:12:00 +00003271 if (!SeenValueSymbolTable) {
3272 // Either this is an old form VST without function index and an
3273 // associated VST forward declaration record (which would have caused
3274 // the VST to be jumped to and parsed before it was encountered
3275 // normally in the stream), or there were no function blocks to
3276 // trigger an earlier parsing of the VST.
3277 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3278 if (std::error_code EC = parseValueSymbolTable())
3279 return EC;
3280 SeenValueSymbolTable = true;
3281 } else {
3282 // We must have had a VST forward declaration record, which caused
3283 // the parser to jump to and parse the VST earlier.
3284 assert(VSTOffset > 0);
3285 if (Stream.SkipBlock())
3286 return error("Invalid record");
3287 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00003288 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003289 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003290 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003291 return EC;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003292 if (std::error_code EC = resolveGlobalAndAliasInits())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003293 return EC;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003294 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00003295 case bitc::METADATA_BLOCK_ID:
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003296 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3297 if (std::error_code EC = rememberAndSkipMetadata())
3298 return EC;
3299 break;
3300 }
3301 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003302 if (std::error_code EC = parseMetadata(true))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003303 return EC;
Devang Patel7428d8a2009-07-22 17:43:22 +00003304 break;
Teresa Johnson12545072015-11-15 02:00:09 +00003305 case bitc::METADATA_KIND_BLOCK_ID:
3306 if (std::error_code EC = parseMetadataKinds())
3307 return EC;
3308 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003309 case bitc::FUNCTION_BLOCK_ID:
3310 // If this is the first function body we've seen, reverse the
3311 // FunctionsWithBodies list.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003312 if (!SeenFirstFunctionBody) {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003313 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003314 if (std::error_code EC = globalCleanup())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003315 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003316 SeenFirstFunctionBody = true;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003317 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003318
Teresa Johnsonff642b92015-09-17 20:12:00 +00003319 if (VSTOffset > 0) {
3320 // If we have a VST forward declaration record, make sure we
3321 // parse the VST now if we haven't already. It is needed to
3322 // set up the DeferredFunctionInfo vector for lazy reading.
3323 if (!SeenValueSymbolTable) {
3324 if (std::error_code EC =
3325 BitcodeReader::parseValueSymbolTable(VSTOffset))
3326 return EC;
3327 SeenValueSymbolTable = true;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003328 // Fall through so that we record the NextUnreadBit below.
3329 // This is necessary in case we have an anonymous function that
3330 // is later materialized. Since it will not have a VST entry we
3331 // need to fall back to the lazy parse to find its offset.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003332 } else {
3333 // If we have a VST forward declaration record, but have already
3334 // parsed the VST (just above, when the first function body was
3335 // encountered here), then we are resuming the parse after
Teresa Johnson1493ad92015-10-10 14:18:36 +00003336 // materializing functions. The ResumeBit points to the
3337 // start of the last function block recorded in the
3338 // DeferredFunctionInfo map. Skip it.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003339 if (Stream.SkipBlock())
3340 return error("Invalid record");
3341 continue;
3342 }
3343 }
3344
3345 // Support older bitcode files that did not have the function
Teresa Johnson1493ad92015-10-10 14:18:36 +00003346 // index in the VST, nor a VST forward declaration record, as
3347 // well as anonymous functions that do not have VST entries.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003348 // Build the DeferredFunctionInfo vector on the fly.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003349 if (std::error_code EC = rememberAndSkipFunctionBody())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003350 return EC;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003351
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003352 // Suspend parsing when we reach the function bodies. Subsequent
3353 // materialization calls will resume it when necessary. If the bitcode
3354 // file is old, the symbol table will be at the end instead and will not
3355 // have been seen yet. In this case, just finish the parse now.
3356 if (SeenValueSymbolTable) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003357 NextUnreadBit = Stream.GetCurrentBitNo();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003358 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003359 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003360 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003361 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003362 if (std::error_code EC = parseUseLists())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003363 return EC;
Chad Rosierca2567b2011-12-07 21:44:12 +00003364 break;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003365 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3366 if (std::error_code EC = parseOperandBundleTags())
3367 return EC;
3368 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003369 }
3370 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003371
Chris Lattner27d38752013-01-20 02:13:19 +00003372 case BitstreamEntry::Record:
3373 // The interesting case.
3374 break;
Chris Lattner1314b992007-04-22 06:23:29 +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
Teresa Johnson61b406e2015-12-29 23:00:22 +00003693 // MetadataList when we are lazy loading metadata during function
3694 // importing. Initialize the MetadataList size here based on the
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003695 // 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;
Teresa Johnson61b406e2015-12-29 23:00:22 +00003700 assert(MetadataList.size() == 0);
3701 MetadataList.resize(NumModuleMDs);
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003702 break;
Teresa Johnsone1164de2016-02-10 21:55:02 +00003703 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3704 case bitc::MODULE_CODE_SOURCE_FILENAME:
3705 SmallString<128> ValueName;
3706 if (convertToString(Record, 0, ValueName))
3707 return error("Invalid record");
3708 TheModule->setSourceFileName(ValueName);
3709 break;
Chris Lattner831d4202007-04-26 03:27:58 +00003710 }
Chris Lattner1314b992007-04-22 06:23:29 +00003711 Record.clear();
3712 }
Chris Lattner1314b992007-04-22 06:23:29 +00003713}
3714
Teresa Johnson403a7872015-10-04 14:33:43 +00003715/// Helper to read the header common to all bitcode files.
3716static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3717 // Sniff for the signature.
3718 if (Stream.Read(8) != 'B' ||
3719 Stream.Read(8) != 'C' ||
3720 Stream.Read(4) != 0x0 ||
3721 Stream.Read(4) != 0xC ||
3722 Stream.Read(4) != 0xE ||
3723 Stream.Read(4) != 0xD)
3724 return false;
3725 return true;
3726}
3727
Rafael Espindola1aabf982015-06-16 23:29:49 +00003728std::error_code
3729BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3730 Module *M, bool ShouldLazyLoadMetadata) {
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003731 TheModule = M;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003732
Rafael Espindola1aabf982015-06-16 23:29:49 +00003733 if (std::error_code EC = initStream(std::move(Streamer)))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003734 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003735
Chris Lattner1314b992007-04-22 06:23:29 +00003736 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003737 if (!hasValidBitcodeHeader(Stream))
3738 return error("Invalid bitcode signature");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003739
Chris Lattner1314b992007-04-22 06:23:29 +00003740 // We expect a number of well-defined blocks, though we don't necessarily
3741 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00003742 while (1) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003743 if (Stream.AtEndOfStream()) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003744 // We didn't really read a proper Module.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003745 return error("Malformed IR file");
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003746 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003747
Chris Lattner27d38752013-01-20 02:13:19 +00003748 BitstreamEntry Entry =
3749 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbey97b7a172013-02-06 22:14:06 +00003750
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003751 if (Entry.Kind != BitstreamEntry::SubBlock)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003752 return error("Malformed block");
Joe Abbey97b7a172013-02-06 22:14:06 +00003753
Mehdi Amini5d303282015-10-26 18:37:00 +00003754 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3755 parseBitcodeVersion();
3756 continue;
3757 }
3758
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003759 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Teresa Johnson1493ad92015-10-10 14:18:36 +00003760 return parseModule(0, ShouldLazyLoadMetadata);
Joe Abbey97b7a172013-02-06 22:14:06 +00003761
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003762 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003763 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003764 }
Chris Lattner1314b992007-04-22 06:23:29 +00003765}
Chris Lattner6694f602007-04-29 07:54:31 +00003766
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003767ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
Bill Wendling0198ce02010-10-06 01:22:42 +00003768 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003769 return error("Invalid record");
Bill Wendling0198ce02010-10-06 01:22:42 +00003770
3771 SmallVector<uint64_t, 64> Record;
3772
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003773 std::string Triple;
Bill Wendling0198ce02010-10-06 01:22:42 +00003774 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00003775 while (1) {
3776 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003777
Chris Lattner27d38752013-01-20 02:13:19 +00003778 switch (Entry.Kind) {
3779 case BitstreamEntry::SubBlock: // Handled for us already.
3780 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003781 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003782 case BitstreamEntry::EndBlock:
Rafael Espindolae6107792014-07-04 20:05:56 +00003783 return Triple;
Chris Lattner27d38752013-01-20 02:13:19 +00003784 case BitstreamEntry::Record:
3785 // The interesting case.
3786 break;
Bill Wendling0198ce02010-10-06 01:22:42 +00003787 }
3788
3789 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00003790 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling0198ce02010-10-06 01:22:42 +00003791 default: break; // Default behavior, ignore unknown content.
Bill Wendling0198ce02010-10-06 01:22:42 +00003792 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003793 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003794 if (convertToString(Record, 0, S))
3795 return error("Invalid record");
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003796 Triple = S;
Bill Wendling0198ce02010-10-06 01:22:42 +00003797 break;
3798 }
3799 }
3800 Record.clear();
3801 }
Rafael Espindolae6107792014-07-04 20:05:56 +00003802 llvm_unreachable("Exit infinite loop");
Bill Wendling0198ce02010-10-06 01:22:42 +00003803}
3804
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003805ErrorOr<std::string> BitcodeReader::parseTriple() {
Rafael Espindola1aabf982015-06-16 23:29:49 +00003806 if (std::error_code EC = initStream(nullptr))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003807 return EC;
Bill Wendling0198ce02010-10-06 01:22:42 +00003808
3809 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003810 if (!hasValidBitcodeHeader(Stream))
3811 return error("Invalid bitcode signature");
Bill Wendling0198ce02010-10-06 01:22:42 +00003812
3813 // We expect a number of well-defined blocks, though we don't necessarily
3814 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00003815 while (1) {
3816 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003817
Chris Lattner27d38752013-01-20 02:13:19 +00003818 switch (Entry.Kind) {
3819 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003820 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003821 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003822 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00003823
Chris Lattner27d38752013-01-20 02:13:19 +00003824 case BitstreamEntry::SubBlock:
3825 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Rafael Espindolad346cc82014-07-04 13:52:01 +00003826 return parseModuleTriple();
Joe Abbey97b7a172013-02-06 22:14:06 +00003827
Chris Lattner27d38752013-01-20 02:13:19 +00003828 // Ignore other sub-blocks.
Rafael Espindola48da4f42013-11-04 16:16:24 +00003829 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003830 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003831 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003832
Chris Lattner27d38752013-01-20 02:13:19 +00003833 case BitstreamEntry::Record:
3834 Stream.skipRecord(Entry.ID);
3835 continue;
Bill Wendling0198ce02010-10-06 01:22:42 +00003836 }
3837 }
Bill Wendling0198ce02010-10-06 01:22:42 +00003838}
3839
Mehdi Amini3383ccc2015-11-09 02:46:41 +00003840ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
3841 if (std::error_code EC = initStream(nullptr))
3842 return EC;
3843
3844 // Sniff for the signature.
3845 if (!hasValidBitcodeHeader(Stream))
3846 return error("Invalid bitcode signature");
3847
3848 // We expect a number of well-defined blocks, though we don't necessarily
3849 // need to understand them all.
3850 while (1) {
3851 BitstreamEntry Entry = Stream.advance();
3852 switch (Entry.Kind) {
3853 case BitstreamEntry::Error:
3854 return error("Malformed block");
3855 case BitstreamEntry::EndBlock:
3856 return std::error_code();
3857
3858 case BitstreamEntry::SubBlock:
3859 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3860 if (std::error_code EC = parseBitcodeVersion())
3861 return EC;
3862 return ProducerIdentification;
3863 }
3864 // Ignore other sub-blocks.
3865 if (Stream.SkipBlock())
3866 return error("Malformed block");
3867 continue;
3868 case BitstreamEntry::Record:
3869 Stream.skipRecord(Entry.ID);
3870 continue;
3871 }
3872 }
3873}
3874
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003875/// Parse metadata attachments.
3876std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
Devang Patelaf206b82009-09-18 19:26:43 +00003877 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003878 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003879
Devang Patelaf206b82009-09-18 19:26:43 +00003880 SmallVector<uint64_t, 64> Record;
Chris Lattner27d38752013-01-20 02:13:19 +00003881 while (1) {
3882 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003883
Chris Lattner27d38752013-01-20 02:13:19 +00003884 switch (Entry.Kind) {
3885 case BitstreamEntry::SubBlock: // Handled for us already.
3886 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003887 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003888 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003889 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003890 case BitstreamEntry::Record:
3891 // The interesting case.
Devang Patelaf206b82009-09-18 19:26:43 +00003892 break;
3893 }
Chris Lattner27d38752013-01-20 02:13:19 +00003894
Devang Patelaf206b82009-09-18 19:26:43 +00003895 // Read a metadata attachment record.
3896 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00003897 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patelaf206b82009-09-18 19:26:43 +00003898 default: // Default behavior: ignore.
3899 break;
Chris Lattnerb8778552011-06-17 17:50:30 +00003900 case bitc::METADATA_ATTACHMENT: {
Devang Patelaf206b82009-09-18 19:26:43 +00003901 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003902 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003903 return error("Invalid record");
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003904 if (RecordLength % 2 == 0) {
3905 // A function attachment.
3906 for (unsigned I = 0; I != RecordLength; I += 2) {
3907 auto K = MDKindMap.find(Record[I]);
3908 if (K == MDKindMap.end())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003909 return error("Invalid ID");
Teresa Johnson61b406e2015-12-29 23:00:22 +00003910 Metadata *MD = MetadataList.getValueFwdRef(Record[I + 1]);
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003911 F.setMetadata(K->second, cast<MDNode>(MD));
3912 }
3913 continue;
3914 }
3915
3916 // An instruction attachment.
Devang Patelaf206b82009-09-18 19:26:43 +00003917 Instruction *Inst = InstructionList[Record[0]];
3918 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patelb1a44772009-09-28 21:14:55 +00003919 unsigned Kind = Record[i];
Dan Gohman43aa8f02010-07-20 21:42:28 +00003920 DenseMap<unsigned, unsigned>::iterator I =
3921 MDKindMap.find(Kind);
3922 if (I == MDKindMap.end())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003923 return error("Invalid ID");
Teresa Johnson61b406e2015-12-29 23:00:22 +00003924 Metadata *Node = MetadataList.getValueFwdRef(Record[i + 1]);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003925 if (isa<LocalAsMetadata>(Node))
Duncan P. N. Exon Smith35303fd2014-12-06 02:29:44 +00003926 // Drop the attachment. This used to be legal, but there's no
3927 // upgrade path.
3928 break;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003929 Inst->setMetadata(I->second, cast<MDNode>(Node));
Manman Ren209b17c2013-09-28 00:22:27 +00003930 if (I->second == LLVMContext::MD_tbaa)
3931 InstsWithTBAATag.push_back(Inst);
Devang Patelaf206b82009-09-18 19:26:43 +00003932 }
3933 break;
3934 }
3935 }
3936 }
Devang Patelaf206b82009-09-18 19:26:43 +00003937}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003938
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00003939static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3940 LLVMContext &Context = PtrType->getContext();
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003941 if (!isa<PointerType>(PtrType))
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00003942 return error(Context, "Load/Store operand is not a pointer type");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003943 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3944
3945 if (ValType && ValType != ElemType)
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00003946 return error(Context, "Explicit load/store type does not match pointee "
3947 "type of pointer operand");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003948 if (!PointerType::isLoadableOrStorableType(ElemType))
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00003949 return error(Context, "Cannot load/store from pointer");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003950 return std::error_code();
3951}
3952
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003953/// Lazily parse the specified function body block.
3954std::error_code BitcodeReader::parseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00003955 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003956 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003957
Nick Lewyckya72e1af2010-02-25 08:30:17 +00003958 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00003959 unsigned ModuleValueListSize = ValueList.size();
Teresa Johnson61b406e2015-12-29 23:00:22 +00003960 unsigned ModuleMetadataListSize = MetadataList.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003961
Chris Lattner85b7b402007-05-01 05:52:21 +00003962 // Add all the function arguments to the value table.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00003963 for (Argument &I : F->args())
3964 ValueList.push_back(&I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003965
Chris Lattner83930552007-05-01 07:01:57 +00003966 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00003967 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00003968 unsigned CurBBNo = 0;
3969
Chris Lattner07d09ed2010-04-03 02:17:50 +00003970 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003971 auto getLastInstruction = [&]() -> Instruction * {
3972 if (CurBB && !CurBB->empty())
3973 return &CurBB->back();
3974 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3975 !FunctionBBs[CurBBNo - 1]->empty())
3976 return &FunctionBBs[CurBBNo - 1]->back();
3977 return nullptr;
3978 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003979
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003980 std::vector<OperandBundleDef> OperandBundles;
3981
Chris Lattner85b7b402007-05-01 05:52:21 +00003982 // Read all the records.
3983 SmallVector<uint64_t, 64> Record;
3984 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00003985 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003986
Chris Lattner27d38752013-01-20 02:13:19 +00003987 switch (Entry.Kind) {
3988 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003989 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003990 case BitstreamEntry::EndBlock:
3991 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00003992
Chris Lattner27d38752013-01-20 02:13:19 +00003993 case BitstreamEntry::SubBlock:
3994 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00003995 default: // Skip unknown content.
3996 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003997 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00003998 break;
3999 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004000 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004001 return EC;
Chris Lattner83930552007-05-01 07:01:57 +00004002 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00004003 break;
4004 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004005 if (std::error_code EC = parseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004006 return EC;
Chris Lattner85b7b402007-05-01 05:52:21 +00004007 break;
Devang Patelaf206b82009-09-18 19:26:43 +00004008 case bitc::METADATA_ATTACHMENT_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004009 if (std::error_code EC = parseMetadataAttachment(*F))
Rafael Espindola48da4f42013-11-04 16:16:24 +00004010 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004011 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00004012 case bitc::METADATA_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004013 if (std::error_code EC = parseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004014 return EC;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00004015 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004016 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004017 if (std::error_code EC = parseUseLists())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004018 return EC;
4019 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00004020 }
4021 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00004022
Chris Lattner27d38752013-01-20 02:13:19 +00004023 case BitstreamEntry::Record:
4024 // The interesting case.
4025 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00004026 }
Joe Abbey97b7a172013-02-06 22:14:06 +00004027
Chris Lattner85b7b402007-05-01 05:52:21 +00004028 // Read a record.
4029 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00004030 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00004031 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00004032 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00004033 default: // Default behavior: reject
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004034 return error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004035 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00004036 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004037 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00004038 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00004039 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004040
4041 // See if anything took the address of blocks in this function.
4042 auto BBFRI = BasicBlockFwdRefs.find(F);
4043 if (BBFRI == BasicBlockFwdRefs.end()) {
4044 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4045 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
4046 } else {
4047 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00004048 // Check for invalid basic block references.
4049 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004050 return error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00004051 assert(!BBRefs.empty() && "Unexpected empty array");
4052 assert(!BBRefs.front() && "Invalid reference to entry block");
4053 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4054 ++I)
4055 if (I < RE && BBRefs[I]) {
4056 BBRefs[I]->insertInto(F);
4057 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004058 } else {
4059 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4060 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004061
4062 // Erase from the table.
4063 BasicBlockFwdRefs.erase(BBFRI);
4064 }
4065
Chris Lattner83930552007-05-01 07:01:57 +00004066 CurBB = FunctionBBs[0];
4067 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004068 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004069
Chris Lattner07d09ed2010-04-03 02:17:50 +00004070 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4071 // This record indicates that the last instruction is at the same
4072 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004073 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004074
Craig Topper2617dcc2014-04-15 06:32:26 +00004075 if (!I)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004076 return error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00004077 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004078 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004079 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004080
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00004081 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004082 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00004083 if (!I || Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004084 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004085
Chris Lattner07d09ed2010-04-03 02:17:50 +00004086 unsigned Line = Record[0], Col = Record[1];
4087 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004088
Craig Topper2617dcc2014-04-15 06:32:26 +00004089 MDNode *Scope = nullptr, *IA = nullptr;
Teresa Johnson61b406e2015-12-29 23:00:22 +00004090 if (ScopeID)
4091 Scope = cast<MDNode>(MetadataList.getValueFwdRef(ScopeID - 1));
4092 if (IAID)
4093 IA = cast<MDNode>(MetadataList.getValueFwdRef(IAID - 1));
Chris Lattner07d09ed2010-04-03 02:17:50 +00004094 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4095 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004096 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004097 continue;
4098 }
4099
Chris Lattnere9759c22007-05-06 00:21:25 +00004100 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4101 unsigned OpNum = 0;
4102 Value *LHS, *RHS;
4103 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004104 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00004105 OpNum+1 > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004106 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004107
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004108 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00004109 if (Opc == -1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004110 return error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004111 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00004112 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00004113 if (OpNum < Record.size()) {
4114 if (Opc == Instruction::Add ||
4115 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00004116 Opc == Instruction::Mul ||
4117 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00004118 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00004119 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00004120 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00004121 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00004122 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00004123 Opc == Instruction::UDiv ||
4124 Opc == Instruction::LShr ||
4125 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00004126 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00004127 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004128 } else if (isa<FPMathOperator>(I)) {
James Molloy88eb5352015-07-10 12:52:00 +00004129 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004130 if (FMF.any())
4131 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00004132 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004133
Dan Gohman1b849082009-09-07 23:54:19 +00004134 }
Chris Lattner85b7b402007-05-01 05:52:21 +00004135 break;
4136 }
Chris Lattnere9759c22007-05-06 00:21:25 +00004137 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4138 unsigned OpNum = 0;
4139 Value *Op;
4140 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4141 OpNum+2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004142 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004143
Chris Lattner229907c2011-07-18 04:54:35 +00004144 Type *ResTy = getTypeByID(Record[OpNum]);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004145 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004146 if (Opc == -1 || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004147 return error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00004148 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004149 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4150 if (Temp) {
4151 InstructionList.push_back(Temp);
4152 CurBB->getInstList().push_back(Temp);
4153 }
4154 } else {
Filipe Cabecinhasb70fd872015-10-06 12:37:54 +00004155 auto CastOp = (Instruction::CastOps)Opc;
4156 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4157 return error("Invalid cast");
4158 I = CastInst::Create(CastOp, Op, ResTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004159 }
Devang Patelaf206b82009-09-18 19:26:43 +00004160 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004161 break;
4162 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00004163 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4164 case bitc::FUNC_CODE_INST_GEP_OLD:
4165 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004166 unsigned OpNum = 0;
David Blaikieb5b5efd2015-02-25 01:08:52 +00004167
4168 Type *Ty;
4169 bool InBounds;
4170
4171 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4172 InBounds = Record[OpNum++];
4173 Ty = getTypeByID(Record[OpNum++]);
4174 } else {
4175 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4176 Ty = nullptr;
4177 }
4178
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004179 Value *BasePtr;
4180 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004181 return error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00004182
David Blaikie60310f22015-05-08 00:42:26 +00004183 if (!Ty)
4184 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4185 ->getElementType();
4186 else if (Ty !=
4187 cast<SequentialType>(BasePtr->getType()->getScalarType())
4188 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004189 return error(
David Blaikie675e8cb2015-03-16 21:35:48 +00004190 "Explicit gep type does not match pointee type of pointer operand");
4191
Chris Lattner5285b5e2007-05-02 05:46:45 +00004192 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004193 while (OpNum != Record.size()) {
4194 Value *Op;
4195 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004196 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004197 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004198 }
4199
David Blaikie096b1da2015-03-14 19:53:33 +00004200 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
David Blaikie675e8cb2015-03-16 21:35:48 +00004201
Devang Patelaf206b82009-09-18 19:26:43 +00004202 InstructionList.push_back(I);
David Blaikieb5b5efd2015-02-25 01:08:52 +00004203 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004204 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004205 break;
4206 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004207
Dan Gohman1ecaf452008-05-31 00:58:22 +00004208 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4209 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00004210 unsigned OpNum = 0;
4211 Value *Agg;
4212 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004213 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004214
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004215 unsigned RecSize = Record.size();
4216 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004217 return error("EXTRACTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004218
Dan Gohman1ecaf452008-05-31 00:58:22 +00004219 SmallVector<unsigned, 4> EXTRACTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004220 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004221 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004222 bool IsArray = CurTy->isArrayTy();
4223 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00004224 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004225
4226 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004227 return error("EXTRACTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004228 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004229 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004230 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004231 return error("EXTRACTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004232 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004233 return error("EXTRACTVAL: Invalid array index");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004234 EXTRACTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004235
4236 if (IsStruct)
4237 CurTy = CurTy->subtypes()[Index];
4238 else
4239 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00004240 }
4241
Jay Foad57aa6362011-07-13 10:26:04 +00004242 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00004243 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00004244 break;
4245 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004246
Dan Gohman1ecaf452008-05-31 00:58:22 +00004247 case bitc::FUNC_CODE_INST_INSERTVAL: {
4248 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00004249 unsigned OpNum = 0;
4250 Value *Agg;
4251 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004252 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004253 Value *Val;
4254 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004255 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004256
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004257 unsigned RecSize = Record.size();
4258 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004259 return error("INSERTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004260
Dan Gohman1ecaf452008-05-31 00:58:22 +00004261 SmallVector<unsigned, 4> INSERTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004262 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004263 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004264 bool IsArray = CurTy->isArrayTy();
4265 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00004266 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004267
4268 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004269 return error("INSERTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004270 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004271 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004272 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004273 return error("INSERTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004274 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004275 return error("INSERTVAL: Invalid array index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004276
Dan Gohman1ecaf452008-05-31 00:58:22 +00004277 INSERTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004278 if (IsStruct)
4279 CurTy = CurTy->subtypes()[Index];
4280 else
4281 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00004282 }
4283
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00004284 if (CurTy != Val->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004285 return error("Inserted value type doesn't match aggregate type");
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00004286
Jay Foad57aa6362011-07-13 10:26:04 +00004287 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00004288 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00004289 break;
4290 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004291
Chris Lattnere9759c22007-05-06 00:21:25 +00004292 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00004293 // obsolete form of select
4294 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00004295 unsigned OpNum = 0;
4296 Value *TrueVal, *FalseVal, *Cond;
4297 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004298 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4299 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004300 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004301
Dan Gohmanc5d28922008-09-16 01:01:33 +00004302 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00004303 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00004304 break;
4305 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004306
Dan Gohmanc5d28922008-09-16 01:01:33 +00004307 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4308 // new form of select
4309 // handles select i1 or select [N x i1]
4310 unsigned OpNum = 0;
4311 Value *TrueVal, *FalseVal, *Cond;
4312 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004313 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00004314 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004315 return error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00004316
4317 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00004318 if (VectorType* vector_type =
4319 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00004320 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004321 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004322 return error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00004323 } else {
4324 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004325 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004326 return error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004327 }
4328
Gabor Greife9ecc682008-04-06 20:25:17 +00004329 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00004330 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004331 break;
4332 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004333
Chris Lattner1fc27f02007-05-02 05:16:49 +00004334 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00004335 unsigned OpNum = 0;
4336 Value *Vec, *Idx;
4337 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00004338 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004339 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004340 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004341 return error("Invalid type for value");
Eric Christopherc9742252009-07-25 02:28:41 +00004342 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00004343 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004344 break;
4345 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004346
Chris Lattner1fc27f02007-05-02 05:16:49 +00004347 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00004348 unsigned OpNum = 0;
4349 Value *Vec, *Elt, *Idx;
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004350 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004351 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004352 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004353 return error("Invalid type for value");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004354 if (popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00004355 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00004356 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004357 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00004358 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00004359 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004360 break;
4361 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004362
Chris Lattnere9759c22007-05-06 00:21:25 +00004363 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4364 unsigned OpNum = 0;
4365 Value *Vec1, *Vec2, *Mask;
4366 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004367 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004368 return error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00004369
Mon P Wang25f01062008-11-10 04:46:22 +00004370 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004371 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004372 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004373 return error("Invalid type for value");
Chris Lattner1fc27f02007-05-02 05:16:49 +00004374 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00004375 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004376 break;
4377 }
Mon P Wang25f01062008-11-10 04:46:22 +00004378
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004379 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4380 // Old form of ICmp/FCmp returning bool
4381 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4382 // both legal on vectors but had different behaviour.
4383 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4384 // FCmp/ICmp returning bool or vector of bool
4385
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004386 unsigned OpNum = 0;
4387 Value *LHS, *RHS;
4388 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
James Molloy88eb5352015-07-10 12:52:00 +00004389 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4390 return error("Invalid record");
4391
4392 unsigned PredVal = Record[OpNum];
4393 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4394 FastMathFlags FMF;
4395 if (IsFP && Record.size() > OpNum+1)
4396 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4397
4398 if (OpNum+1 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004399 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004400
Duncan Sands9dff9be2010-02-15 16:12:20 +00004401 if (LHS->getType()->isFPOrFPVectorTy())
James Molloy88eb5352015-07-10 12:52:00 +00004402 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004403 else
James Molloy88eb5352015-07-10 12:52:00 +00004404 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4405
4406 if (FMF.any())
4407 I->setFastMathFlags(FMF);
Devang Patelaf206b82009-09-18 19:26:43 +00004408 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00004409 break;
4410 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004411
Chris Lattnere53603e2007-05-02 04:27:25 +00004412 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00004413 {
4414 unsigned Size = Record.size();
4415 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00004416 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004417 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00004418 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004419 }
Devang Patelbbfd8742008-02-26 01:29:32 +00004420
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004421 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004422 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00004423 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004424 return error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00004425 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004426 return error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004427
Chris Lattnerf1c87102011-06-17 18:09:11 +00004428 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004429 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004430 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00004431 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004432 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00004433 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004434 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004435 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004436 if (!TrueDest)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004437 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004438
Devang Patelaf206b82009-09-18 19:26:43 +00004439 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00004440 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004441 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00004442 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004443 else {
4444 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004445 Value *Cond = getValue(Record, 2, NextValueNo,
4446 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00004447 if (!FalseDest || !Cond)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004448 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00004449 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004450 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004451 }
4452 break;
4453 }
David Majnemerb01aa9f2015-08-23 19:22:31 +00004454 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004455 if (Record.size() != 1 && Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00004456 return error("Invalid record");
4457 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004458 Value *CleanupPad =
4459 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004460 if (!CleanupPad)
David Majnemer654e1302015-07-31 17:58:14 +00004461 return error("Invalid record");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004462 BasicBlock *UnwindDest = nullptr;
4463 if (Record.size() == 2) {
David Majnemer654e1302015-07-31 17:58:14 +00004464 UnwindDest = getBasicBlock(Record[Idx++]);
4465 if (!UnwindDest)
4466 return error("Invalid record");
4467 }
4468
David Majnemer8a1c45d2015-12-12 05:38:55 +00004469 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
David Majnemer654e1302015-07-31 17:58:14 +00004470 InstructionList.push_back(I);
4471 break;
4472 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004473 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4474 if (Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00004475 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004476 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004477 Value *CatchPad =
4478 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004479 if (!CatchPad)
4480 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004481 BasicBlock *BB = getBasicBlock(Record[Idx++]);
David Majnemer654e1302015-07-31 17:58:14 +00004482 if (!BB)
4483 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004484
David Majnemer8a1c45d2015-12-12 05:38:55 +00004485 I = CatchReturnInst::Create(CatchPad, BB);
David Majnemer654e1302015-07-31 17:58:14 +00004486 InstructionList.push_back(I);
4487 break;
4488 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004489 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4490 // We must have, at minimum, the outer scope and the number of arguments.
4491 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00004492 return error("Invalid record");
4493
David Majnemer654e1302015-07-31 17:58:14 +00004494 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004495
4496 Value *ParentPad =
4497 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4498
4499 unsigned NumHandlers = Record[Idx++];
4500
4501 SmallVector<BasicBlock *, 2> Handlers;
4502 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4503 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4504 if (!BB)
David Majnemer654e1302015-07-31 17:58:14 +00004505 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004506 Handlers.push_back(BB);
4507 }
4508
4509 BasicBlock *UnwindDest = nullptr;
4510 if (Idx + 1 == Record.size()) {
David Majnemer654e1302015-07-31 17:58:14 +00004511 UnwindDest = getBasicBlock(Record[Idx++]);
4512 if (!UnwindDest)
4513 return error("Invalid record");
4514 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004515
4516 if (Record.size() != Idx)
4517 return error("Invalid record");
4518
4519 auto *CatchSwitch =
4520 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4521 for (BasicBlock *Handler : Handlers)
4522 CatchSwitch->addHandler(Handler);
4523 I = CatchSwitch;
4524 InstructionList.push_back(I);
4525 break;
4526 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004527 case bitc::FUNC_CODE_INST_CATCHPAD:
4528 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4529 // We must have, at minimum, the outer scope and the number of arguments.
4530 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00004531 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004532
David Majnemer654e1302015-07-31 17:58:14 +00004533 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004534
4535 Value *ParentPad =
4536 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4537
David Majnemer654e1302015-07-31 17:58:14 +00004538 unsigned NumArgOperands = Record[Idx++];
David Majnemer8a1c45d2015-12-12 05:38:55 +00004539
David Majnemer654e1302015-07-31 17:58:14 +00004540 SmallVector<Value *, 2> Args;
4541 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4542 Value *Val;
4543 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4544 return error("Invalid record");
4545 Args.push_back(Val);
4546 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004547
David Majnemer654e1302015-07-31 17:58:14 +00004548 if (Record.size() != Idx)
4549 return error("Invalid record");
4550
David Majnemer8a1c45d2015-12-12 05:38:55 +00004551 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4552 I = CleanupPadInst::Create(ParentPad, Args);
4553 else
4554 I = CatchPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00004555 InstructionList.push_back(I);
4556 break;
4557 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00004558 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004559 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004560 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00004561 // "New" SwitchInst format with case ranges. The changes to write this
4562 // format were reverted but we still recognize bitcode that uses it.
4563 // Hopefully someday we will have support for case ranges and can use
4564 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004565
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004566 Type *OpTy = getTypeByID(Record[1]);
4567 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4568
Jan Wen Voungafaced02012-10-11 20:20:40 +00004569 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004570 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004571 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004572 return error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004573
4574 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004575
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004576 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4577 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004578
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004579 unsigned CurIdx = 5;
4580 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00004581 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004582 unsigned NumItems = Record[CurIdx++];
4583 for (unsigned ci = 0; ci != NumItems; ++ci) {
4584 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004585
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004586 APInt Low;
4587 unsigned ActiveWords = 1;
4588 if (ValueBitWidth > 64)
4589 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004590 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
Benjamin Kramer9704ed02012-05-28 14:10:31 +00004591 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004592 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00004593
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004594 if (!isSingleNumber) {
4595 ActiveWords = 1;
4596 if (ValueBitWidth > 64)
4597 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004598 APInt High = readWideAPInt(
4599 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004600 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00004601
4602 // FIXME: It is not clear whether values in the range should be
4603 // compared as signed or unsigned values. The partially
4604 // implemented changes that used this format in the past used
4605 // unsigned comparisons.
4606 for ( ; Low.ule(High); ++Low)
4607 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004608 } else
Bob Wilsone4077362013-09-09 19:14:35 +00004609 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004610 }
4611 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00004612 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4613 cve = CaseVals.end(); cvi != cve; ++cvi)
4614 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004615 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004616 I = SI;
4617 break;
4618 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004619
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004620 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004621
Chris Lattner5285b5e2007-05-02 05:46:45 +00004622 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004623 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004624 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004625 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004626 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004627 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004628 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004629 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00004630 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00004631 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004632 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004633 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00004634 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4635 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004636 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00004637 delete SI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004638 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004639 }
4640 SI->addCase(CaseVal, DestBB);
4641 }
4642 I = SI;
4643 break;
4644 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004645 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00004646 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004647 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004648 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004649 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00004650 if (!OpTy || !Address)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004651 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004652 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004653 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00004654 InstructionList.push_back(IBI);
4655 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4656 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4657 IBI->addDestination(DestBB);
4658 } else {
4659 delete IBI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004660 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004661 }
4662 }
4663 I = IBI;
4664 break;
4665 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004666
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004667 case bitc::FUNC_CODE_INST_INVOKE: {
4668 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00004669 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004670 return error("Invalid record");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004671 unsigned OpNum = 0;
4672 AttributeSet PAL = getAttributes(Record[OpNum++]);
4673 unsigned CCInfo = Record[OpNum++];
4674 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4675 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004676
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004677 FunctionType *FTy = nullptr;
4678 if (CCInfo >> 13 & 1 &&
4679 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004680 return error("Explicit invoke type is not a function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004681
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004682 Value *Callee;
4683 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004684 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004685
Chris Lattner229907c2011-07-18 04:54:35 +00004686 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004687 if (!CalleeTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004688 return error("Callee is not a pointer");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004689 if (!FTy) {
4690 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4691 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004692 return error("Callee is not of pointer to function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004693 } else if (CalleeTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004694 return error("Explicit invoke type does not match pointee type of "
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004695 "callee operand");
4696 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004697 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004698
Chris Lattner5285b5e2007-05-02 05:46:45 +00004699 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004700 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004701 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4702 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004703 if (!Ops.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004704 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004705 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004706
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004707 if (!FTy->isVarArg()) {
4708 if (Record.size() != OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004709 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004710 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004711 // Read type/value pairs for varargs params.
4712 while (OpNum != Record.size()) {
4713 Value *Op;
4714 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004715 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004716 Ops.push_back(Op);
4717 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004718 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004719
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004720 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4721 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00004722 InstructionList.push_back(I);
Vedant Kumarad6d6e72015-10-27 21:17:06 +00004723 cast<InvokeInst>(I)->setCallingConv(
4724 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00004725 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004726 break;
4727 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00004728 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4729 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004730 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004731 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004732 return error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00004733 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00004734 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004735 break;
4736 }
Chris Lattnere53603e2007-05-02 04:27:25 +00004737 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00004738 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00004739 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004740 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00004741 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00004742 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004743 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004744 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004745 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004746 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004747
Jay Foad52131342011-03-30 11:28:46 +00004748 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00004749 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004750
Chris Lattnere14cb882007-05-04 19:11:41 +00004751 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004752 Value *V;
4753 // With the new function encoding, it is possible that operands have
4754 // negative IDs (for forward references). Use a signed VBR
4755 // representation to keep the encoding small.
4756 if (UseRelativeIDs)
4757 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4758 else
4759 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00004760 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004761 if (!V || !BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004762 return error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00004763 PN->addIncoming(V, BB);
4764 }
4765 I = PN;
4766 break;
4767 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004768
David Majnemer7fddecc2015-06-17 20:52:32 +00004769 case bitc::FUNC_CODE_INST_LANDINGPAD:
4770 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
Bill Wendlingfae14752011-08-12 20:24:12 +00004771 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4772 unsigned Idx = 0;
David Majnemer7fddecc2015-06-17 20:52:32 +00004773 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4774 if (Record.size() < 3)
4775 return error("Invalid record");
4776 } else {
4777 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4778 if (Record.size() < 4)
4779 return error("Invalid record");
4780 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004781 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004782 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004783 return error("Invalid record");
David Majnemer7fddecc2015-06-17 20:52:32 +00004784 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4785 Value *PersFn = nullptr;
4786 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4787 return error("Invalid record");
4788
4789 if (!F->hasPersonalityFn())
4790 F->setPersonalityFn(cast<Constant>(PersFn));
4791 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4792 return error("Personality function mismatch");
4793 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004794
4795 bool IsCleanup = !!Record[Idx++];
4796 unsigned NumClauses = Record[Idx++];
David Majnemer7fddecc2015-06-17 20:52:32 +00004797 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
Bill Wendlingfae14752011-08-12 20:24:12 +00004798 LP->setCleanup(IsCleanup);
4799 for (unsigned J = 0; J != NumClauses; ++J) {
4800 LandingPadInst::ClauseType CT =
4801 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4802 Value *Val;
4803
4804 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4805 delete LP;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004806 return error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00004807 }
4808
4809 assert((CT != LandingPadInst::Catch ||
4810 !isa<ArrayType>(Val->getType())) &&
4811 "Catch clause has a invalid type!");
4812 assert((CT != LandingPadInst::Filter ||
4813 isa<ArrayType>(Val->getType())) &&
4814 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004815 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00004816 }
4817
4818 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00004819 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00004820 break;
4821 }
4822
Chris Lattnerf1c87102011-06-17 18:09:11 +00004823 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4824 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004825 return error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00004826 uint64_t AlignRecord = Record[3];
4827 const uint64_t InAllocaMask = uint64_t(1) << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00004828 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
Bob Wilson043ee652015-07-28 04:05:45 +00004829 // Reserve bit 7 for SwiftError flag.
4830 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
David Blaikiebdb49102015-04-28 16:51:01 +00004831 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
JF Bastien30bf96b2015-02-22 19:32:03 +00004832 bool InAlloca = AlignRecord & InAllocaMask;
David Blaikiebdb49102015-04-28 16:51:01 +00004833 Type *Ty = getTypeByID(Record[0]);
4834 if ((AlignRecord & ExplicitTypeMask) == 0) {
4835 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4836 if (!PTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004837 return error("Old-style alloca with a non-pointer type");
David Blaikiebdb49102015-04-28 16:51:01 +00004838 Ty = PTy->getElementType();
4839 }
4840 Type *OpTy = getTypeByID(Record[1]);
4841 Value *Size = getFnValueByID(Record[2], OpTy);
JF Bastien30bf96b2015-02-22 19:32:03 +00004842 unsigned Align;
4843 if (std::error_code EC =
David Blaikiebdb49102015-04-28 16:51:01 +00004844 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
JF Bastien30bf96b2015-02-22 19:32:03 +00004845 return EC;
4846 }
Rafael Espindola48da4f42013-11-04 16:16:24 +00004847 if (!Ty || !Size)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004848 return error("Invalid record");
David Blaikiebdb49102015-04-28 16:51:01 +00004849 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00004850 AI->setUsedWithInAlloca(InAlloca);
4851 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00004852 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00004853 break;
4854 }
Chris Lattner9f600c52007-05-03 22:04:19 +00004855 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004856 unsigned OpNum = 0;
4857 Value *Op;
4858 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004859 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004860 return error("Invalid record");
David Blaikie85035652015-02-25 01:07:20 +00004861
4862 Type *Ty = nullptr;
4863 if (OpNum + 3 == Record.size())
4864 Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004865 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004866 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00004867 if (!Ty)
4868 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004869
JF Bastien30bf96b2015-02-22 19:32:03 +00004870 unsigned Align;
4871 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4872 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00004873 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
David Blaikie85035652015-02-25 01:07:20 +00004874
Devang Patelaf206b82009-09-18 19:26:43 +00004875 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00004876 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00004877 }
Eli Friedman59b66882011-08-09 23:02:53 +00004878 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4879 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4880 unsigned OpNum = 0;
4881 Value *Op;
4882 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004883 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004884 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004885
David Blaikie85035652015-02-25 01:07:20 +00004886 Type *Ty = nullptr;
4887 if (OpNum + 5 == Record.size())
4888 Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004889 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004890 return EC;
4891 if (!Ty)
4892 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004893
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004894 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman59b66882011-08-09 23:02:53 +00004895 if (Ordering == NotAtomic || Ordering == Release ||
4896 Ordering == AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004897 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004898 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004899 return error("Invalid record");
4900 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00004901
JF Bastien30bf96b2015-02-22 19:32:03 +00004902 unsigned Align;
4903 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4904 return EC;
4905 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
David Blaikie85035652015-02-25 01:07:20 +00004906
Eli Friedman59b66882011-08-09 23:02:53 +00004907 InstructionList.push_back(I);
4908 break;
4909 }
David Blaikie612ddbf2015-04-22 04:14:42 +00004910 case bitc::FUNC_CODE_INST_STORE:
4911 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004912 unsigned OpNum = 0;
4913 Value *Val, *Ptr;
4914 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie612ddbf2015-04-22 04:14:42 +00004915 (BitCode == bitc::FUNC_CODE_INST_STORE
4916 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4917 : popValue(Record, OpNum, NextValueNo,
4918 cast<PointerType>(Ptr->getType())->getElementType(),
4919 Val)) ||
4920 OpNum + 2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004921 return error("Invalid record");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004922
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004923 if (std::error_code EC =
4924 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004925 return EC;
JF Bastien30bf96b2015-02-22 19:32:03 +00004926 unsigned Align;
4927 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4928 return EC;
4929 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
Devang Patelaf206b82009-09-18 19:26:43 +00004930 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004931 break;
4932 }
David Blaikie50a06152015-04-22 04:14:46 +00004933 case bitc::FUNC_CODE_INST_STOREATOMIC:
4934 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
Eli Friedman59b66882011-08-09 23:02:53 +00004935 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4936 unsigned OpNum = 0;
4937 Value *Val, *Ptr;
4938 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie50a06152015-04-22 04:14:46 +00004939 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4940 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4941 : popValue(Record, OpNum, NextValueNo,
4942 cast<PointerType>(Ptr->getType())->getElementType(),
4943 Val)) ||
4944 OpNum + 4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004945 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004946
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004947 if (std::error_code EC =
4948 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004949 return EC;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004950 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman222b5a42011-09-19 19:41:28 +00004951 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman59b66882011-08-09 23:02:53 +00004952 Ordering == AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004953 return error("Invalid record");
4954 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00004955 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004956 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004957
JF Bastien30bf96b2015-02-22 19:32:03 +00004958 unsigned Align;
4959 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4960 return EC;
4961 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
Eli Friedman59b66882011-08-09 23:02:53 +00004962 InstructionList.push_back(I);
4963 break;
4964 }
David Blaikie2a661cd2015-04-28 04:30:29 +00004965 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004966 case bitc::FUNC_CODE_INST_CMPXCHG: {
Tim Northovere94a5182014-03-11 10:48:52 +00004967 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
Tim Northover420a2162014-06-13 14:24:07 +00004968 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004969 unsigned OpNum = 0;
4970 Value *Ptr, *Cmp, *New;
4971 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie2a661cd2015-04-28 04:30:29 +00004972 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4973 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4974 : popValue(Record, OpNum, NextValueNo,
4975 cast<PointerType>(Ptr->getType())->getElementType(),
4976 Cmp)) ||
4977 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4978 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004979 return error("Invalid record");
4980 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
Tim Northovere94a5182014-03-11 10:48:52 +00004981 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004982 return error("Invalid record");
4983 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
Tim Northovere94a5182014-03-11 10:48:52 +00004984
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004985 if (std::error_code EC =
4986 typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004987 return EC;
Tim Northovere94a5182014-03-11 10:48:52 +00004988 AtomicOrdering FailureOrdering;
4989 if (Record.size() < 7)
4990 FailureOrdering =
4991 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4992 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004993 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
Tim Northovere94a5182014-03-11 10:48:52 +00004994
4995 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4996 SynchScope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004997 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00004998
4999 if (Record.size() < 8) {
5000 // Before weak cmpxchgs existed, the instruction simply returned the
5001 // value loaded from memory, so bitcode files from that era will be
5002 // expecting the first component of a modern cmpxchg.
5003 CurBB->getInstList().push_back(I);
5004 I = ExtractValueInst::Create(I, 0);
5005 } else {
5006 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
5007 }
5008
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005009 InstructionList.push_back(I);
5010 break;
5011 }
5012 case bitc::FUNC_CODE_INST_ATOMICRMW: {
5013 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
5014 unsigned OpNum = 0;
5015 Value *Ptr, *Val;
5016 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00005017 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005018 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
5019 OpNum+4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005020 return error("Invalid record");
5021 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005022 if (Operation < AtomicRMWInst::FIRST_BINOP ||
5023 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005024 return error("Invalid record");
5025 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman59b66882011-08-09 23:02:53 +00005026 if (Ordering == NotAtomic || Ordering == Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005027 return error("Invalid record");
5028 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005029 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
5030 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
5031 InstructionList.push_back(I);
5032 break;
5033 }
Eli Friedmanfee02c62011-07-25 23:16:38 +00005034 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
5035 if (2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005036 return error("Invalid record");
5037 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005038 if (Ordering == NotAtomic || Ordering == Unordered ||
5039 Ordering == Monotonic)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005040 return error("Invalid record");
5041 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005042 I = new FenceInst(Context, Ordering, SynchScope);
5043 InstructionList.push_back(I);
5044 break;
5045 }
Chris Lattnerc44070802011-06-17 18:17:37 +00005046 case bitc::FUNC_CODE_INST_CALL: {
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005047 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00005048 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005049 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005050
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005051 unsigned OpNum = 0;
5052 AttributeSet PAL = getAttributes(Record[OpNum++]);
5053 unsigned CCInfo = Record[OpNum++];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005054
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005055 FastMathFlags FMF;
5056 if ((CCInfo >> bitc::CALL_FMF) & 1) {
5057 FMF = getDecodedFastMathFlags(Record[OpNum++]);
5058 if (!FMF.any())
5059 return error("Fast math flags indicator set for call with no FMF");
5060 }
5061
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005062 FunctionType *FTy = nullptr;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005063 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005064 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005065 return error("Explicit call type is not a function type");
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005066
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005067 Value *Callee;
5068 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005069 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005070
Chris Lattner229907c2011-07-18 04:54:35 +00005071 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005072 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005073 return error("Callee is not a pointer type");
David Blaikie348de692015-04-23 21:36:23 +00005074 if (!FTy) {
5075 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5076 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005077 return error("Callee is not of pointer to function type");
David Blaikie348de692015-04-23 21:36:23 +00005078 } else if (OpTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005079 return error("Explicit call type does not match pointee type of "
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005080 "callee operand");
5081 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005082 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005083
Chris Lattner9f600c52007-05-03 22:04:19 +00005084 SmallVector<Value*, 16> Args;
5085 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005086 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005087 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00005088 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00005089 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00005090 Args.push_back(getValue(Record, OpNum, NextValueNo,
5091 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00005092 if (!Args.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005093 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005094 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005095
Chris Lattner9f600c52007-05-03 22:04:19 +00005096 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00005097 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005098 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005099 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005100 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005101 while (OpNum != Record.size()) {
5102 Value *Op;
5103 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005104 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005105 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00005106 }
5107 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005108
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005109 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5110 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00005111 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00005112 cast<CallInst>(I)->setCallingConv(
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005113 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
Reid Kleckner5772b772014-04-24 20:14:34 +00005114 CallInst::TailCallKind TCK = CallInst::TCK_None;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005115 if (CCInfo & 1 << bitc::CALL_TAIL)
Reid Kleckner5772b772014-04-24 20:14:34 +00005116 TCK = CallInst::TCK_Tail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005117 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
Reid Kleckner5772b772014-04-24 20:14:34 +00005118 TCK = CallInst::TCK_MustTail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005119 if (CCInfo & (1 << bitc::CALL_NOTAIL))
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005120 TCK = CallInst::TCK_NoTail;
Reid Kleckner5772b772014-04-24 20:14:34 +00005121 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00005122 cast<CallInst>(I)->setAttributes(PAL);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005123 if (FMF.any()) {
5124 if (!isa<FPMathOperator>(I))
5125 return error("Fast-math-flags specified for call without "
5126 "floating-point scalar or vector return type");
5127 I->setFastMathFlags(FMF);
5128 }
Chris Lattner9f600c52007-05-03 22:04:19 +00005129 break;
5130 }
5131 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5132 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005133 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00005134 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00005135 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00005136 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00005137 if (!OpTy || !Op || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005138 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005139 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00005140 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00005141 break;
5142 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005143
5144 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5145 // A call or an invoke can be optionally prefixed with some variable
5146 // number of operand bundle blocks. These blocks are read into
5147 // OperandBundles and consumed at the next call or invoke instruction.
5148
5149 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5150 return error("Invalid record");
5151
Sanjoy Dasf79d3442015-11-18 08:30:07 +00005152 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005153
5154 unsigned OpNum = 1;
5155 while (OpNum != Record.size()) {
5156 Value *Op;
5157 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5158 return error("Invalid record");
5159 Inputs.push_back(Op);
5160 }
5161
Sanjoy Dasf79d3442015-11-18 08:30:07 +00005162 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005163 continue;
5164 }
Chris Lattner83930552007-05-01 07:01:57 +00005165 }
5166
5167 // Add instruction to end of current BB. If there is no current BB, reject
5168 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00005169 if (!CurBB) {
Chris Lattner83930552007-05-01 07:01:57 +00005170 delete I;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005171 return error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00005172 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005173 if (!OperandBundles.empty()) {
5174 delete I;
5175 return error("Operand bundles found with no consumer");
5176 }
Chris Lattner83930552007-05-01 07:01:57 +00005177 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005178
Chris Lattner83930552007-05-01 07:01:57 +00005179 // If this was a terminator instruction, move to the next block.
5180 if (isa<TerminatorInst>(I)) {
5181 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00005182 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00005183 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005184
Chris Lattner83930552007-05-01 07:01:57 +00005185 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00005186 if (I && !I->getType()->isVoidTy())
David Majnemer8a1c45d2015-12-12 05:38:55 +00005187 ValueList.assignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00005188 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005189
Chris Lattner27d38752013-01-20 02:13:19 +00005190OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00005191
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005192 if (!OperandBundles.empty())
5193 return error("Operand bundles found with no consumer");
5194
Chris Lattner83930552007-05-01 07:01:57 +00005195 // Check the function list for unresolved values.
5196 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005197 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00005198 // We found at least one unresolved value. Nuke them all to avoid leaks.
5199 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00005200 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00005201 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00005202 delete A;
5203 }
5204 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005205 return error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00005206 }
Chris Lattner83930552007-05-01 07:01:57 +00005207 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005208
Dan Gohman9b9ff462010-08-25 20:23:38 +00005209 // FIXME: Check for unresolved forward-declared metadata references
5210 // and clean up leaks.
5211
Chris Lattner85b7b402007-05-01 05:52:21 +00005212 // Trim the value list down to the size it was before we parsed this function.
5213 ValueList.shrinkTo(ModuleValueListSize);
Teresa Johnson61b406e2015-12-29 23:00:22 +00005214 MetadataList.shrinkTo(ModuleMetadataListSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00005215 std::vector<BasicBlock*>().swap(FunctionBBs);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005216 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00005217}
5218
Rafael Espindola7d712032013-11-05 17:16:08 +00005219/// Find the function body in the bitcode stream
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005220std::error_code BitcodeReader::findFunctionInStream(
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005221 Function *F,
5222 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005223 while (DeferredFunctionInfoIterator->second == 0) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00005224 // This is the fallback handling for the old format bitcode that
Teresa Johnson1493ad92015-10-10 14:18:36 +00005225 // didn't contain the function index in the VST, or when we have
5226 // an anonymous function which would not have a VST entry.
5227 // Assert that we have one of those two cases.
5228 assert(VSTOffset == 0 || !F->hasName());
5229 // Parse the next body in the stream and set its position in the
5230 // DeferredFunctionInfo map.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005231 if (std::error_code EC = rememberAndSkipFunctionBodies())
5232 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005233 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005234 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005235}
5236
Chris Lattner9eeada92007-05-18 04:02:46 +00005237//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005238// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00005239//===----------------------------------------------------------------------===//
5240
Rafael Espindolac3f9b5a2014-06-23 21:53:12 +00005241void BitcodeReader::releaseBuffer() { Buffer.release(); }
Chris Lattner9eeada92007-05-18 04:02:46 +00005242
Rafael Espindola5a52e6d2014-10-24 22:50:48 +00005243std::error_code BitcodeReader::materialize(GlobalValue *GV) {
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00005244 // In older bitcode we must materialize the metadata before parsing
Teresa Johnson61b406e2015-12-29 23:00:22 +00005245 // any functions, in order to set up the MetadataList properly.
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00005246 if (!SeenModuleValuesRecord) {
5247 if (std::error_code EC = materializeMetadata())
5248 return EC;
5249 }
Manman Ren4a9b0eb2015-03-13 19:24:30 +00005250
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005251 Function *F = dyn_cast<Function>(GV);
5252 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005253 if (!F || !F->isMaterializable())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005254 return std::error_code();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005255
5256 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00005257 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005258 // If its position is recorded as 0, its body is somewhere in the stream
5259 // but we haven't seen it yet.
Rafael Espindola1c863ca2015-06-22 18:06:15 +00005260 if (DFII->second == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005261 if (std::error_code EC = findFunctionInStream(F, DFII))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005262 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005263
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005264 // Move the bit stream to the saved position of the deferred function body.
5265 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005266
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005267 if (std::error_code EC = parseFunctionBody(F))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005268 return EC;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00005269 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00005270
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00005271 if (StripDebugInfo)
5272 stripDebugInfo(*F);
5273
Chandler Carruth7132e002007-08-04 01:51:18 +00005274 // Upgrade any old intrinsic calls in the function.
Rafael Espindola86e33402015-07-02 15:55:09 +00005275 for (auto &I : UpgradedIntrinsics) {
Rafael Espindola257a3532016-01-15 19:00:20 +00005276 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5277 UI != UE;) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005278 User *U = *UI;
5279 ++UI;
5280 if (CallInst *CI = dyn_cast<CallInst>(U))
5281 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00005282 }
5283 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005284
Peter Collingbourned4bff302015-11-05 22:03:56 +00005285 // Finish fn->subprogram upgrade for materialized functions.
5286 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5287 F->setSubprogram(SP);
5288
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005289 // Bring in any functions that this function forward-referenced via
5290 // blockaddresses.
5291 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00005292}
5293
Rafael Espindola79753a02015-12-18 21:18:57 +00005294std::error_code BitcodeReader::materializeModule() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00005295 if (std::error_code EC = materializeMetadata())
5296 return EC;
5297
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005298 // Promise to materialize all forward references.
5299 WillMaterializeAllForwardRefs = true;
5300
Chris Lattner06310bf2009-06-16 05:15:21 +00005301 // Iterate over the module, deserializing any functions that are still on
5302 // disk.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00005303 for (Function &F : *TheModule) {
5304 if (std::error_code EC = materialize(&F))
Rafael Espindola246c4fb2014-11-01 16:46:18 +00005305 return EC;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005306 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00005307 // At this point, if there are any function bodies, parse the rest of
5308 // the bits in the module past the last function block we have recorded
5309 // through either lazy scanning or the VST.
5310 if (LastFunctionBlockBit || NextUnreadBit)
5311 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5312 : NextUnreadBit);
Derek Schuff92ef9752012-02-29 00:07:09 +00005313
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005314 // Check that all block address forward references got resolved (as we
5315 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00005316 if (!BasicBlockFwdRefs.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005317 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005318
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005319 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5320 // delete the old functions to clean up. We can't do this unless the entire
5321 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00005322 // with calls to the old function.
Rafael Espindola86e33402015-07-02 15:55:09 +00005323 for (auto &I : UpgradedIntrinsics) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005324 for (auto *U : I.first->users()) {
5325 if (CallInst *CI = dyn_cast<CallInst>(U))
5326 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00005327 }
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005328 if (!I.first->use_empty())
5329 I.first->replaceAllUsesWith(I.second);
5330 I.first->eraseFromParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00005331 }
Rafael Espindola4e721212015-07-02 16:22:40 +00005332 UpgradedIntrinsics.clear();
Devang Patel80ae3492009-08-28 23:24:31 +00005333
Manman Ren209b17c2013-09-28 00:22:27 +00005334 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5335 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5336
Rafael Espindola79753a02015-12-18 21:18:57 +00005337 UpgradeDebugInfo(*TheModule);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005338 return std::error_code();
Chris Lattner9eeada92007-05-18 04:02:46 +00005339}
5340
Rafael Espindola2fa1e432014-12-03 07:18:23 +00005341std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5342 return IdentifiedStructTypes;
5343}
5344
Rafael Espindola1aabf982015-06-16 23:29:49 +00005345std::error_code
5346BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
Rafael Espindola4223a1f2015-06-15 20:08:17 +00005347 if (Streamer)
Rafael Espindola1aabf982015-06-16 23:29:49 +00005348 return initLazyStream(std::move(Streamer));
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005349 return initStreamFromBuffer();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005350}
5351
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005352std::error_code BitcodeReader::initStreamFromBuffer() {
Roman Divacky4717a8d2012-09-06 15:42:13 +00005353 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005354 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5355
Rafael Espindola27435252014-07-29 21:01:24 +00005356 if (Buffer->getBufferSize() & 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005357 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005358
5359 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5360 // The magic number is 0x0B17C0DE stored in little endian.
5361 if (isBitcodeWrapper(BufPtr, BufEnd))
5362 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005363 return error("Invalid bitcode wrapper header");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005364
5365 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00005366 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005367
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005368 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005369}
5370
Rafael Espindola1aabf982015-06-16 23:29:49 +00005371std::error_code
5372BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005373 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5374 // see it.
Rafael Espindola1aabf982015-06-16 23:29:49 +00005375 auto OwnedBytes =
5376 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
Rafael Espindola7d727b52014-12-18 05:08:43 +00005377 StreamingMemoryObject &Bytes = *OwnedBytes;
Yaron Keren06d69302014-12-18 10:03:35 +00005378 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00005379 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005380
5381 unsigned char buf[16];
Rafael Espindola7d727b52014-12-18 05:08:43 +00005382 if (Bytes.readBytes(buf, 16, 0) != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005383 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005384
5385 if (!isBitcode(buf, buf + 16))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005386 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005387
5388 if (isBitcodeWrapper(buf, buf + 4)) {
5389 const unsigned char *bitcodeStart = buf;
5390 const unsigned char *bitcodeEnd = buf + 16;
5391 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
Rafael Espindola7d727b52014-12-18 05:08:43 +00005392 Bytes.dropLeadingBytes(bitcodeStart - buf);
5393 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005394 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005395 return std::error_code();
Rafael Espindola48da4f42013-11-04 16:16:24 +00005396}
5397
Teresa Johnson403a7872015-10-04 14:33:43 +00005398std::error_code FunctionIndexBitcodeReader::error(BitcodeError E,
5399 const Twine &Message) {
5400 return ::error(DiagnosticHandler, make_error_code(E), Message);
5401}
5402
5403std::error_code FunctionIndexBitcodeReader::error(const Twine &Message) {
5404 return ::error(DiagnosticHandler,
5405 make_error_code(BitcodeError::CorruptedBitcode), Message);
5406}
5407
5408std::error_code FunctionIndexBitcodeReader::error(BitcodeError E) {
5409 return ::error(DiagnosticHandler, make_error_code(E));
5410}
5411
5412FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
Mehdi Amini354f5202015-11-19 05:52:29 +00005413 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
5414 bool IsLazy, bool CheckFuncSummaryPresenceOnly)
5415 : DiagnosticHandler(DiagnosticHandler), Buffer(Buffer), IsLazy(IsLazy),
Teresa Johnson403a7872015-10-04 14:33:43 +00005416 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5417
5418FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
Mehdi Amini354f5202015-11-19 05:52:29 +00005419 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
5420 bool CheckFuncSummaryPresenceOnly)
5421 : DiagnosticHandler(DiagnosticHandler), Buffer(nullptr), IsLazy(IsLazy),
Teresa Johnson403a7872015-10-04 14:33:43 +00005422 CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5423
5424void FunctionIndexBitcodeReader::freeState() { Buffer = nullptr; }
5425
5426void FunctionIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5427
5428// Specialized value symbol table parser used when reading function index
5429// blocks where we don't actually create global values.
5430// At the end of this routine the function index is populated with a map
5431// from function name to FunctionInfo. The function info contains
5432// the function block's bitcode offset as well as the offset into the
5433// function summary section.
5434std::error_code FunctionIndexBitcodeReader::parseValueSymbolTable() {
5435 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5436 return error("Invalid record");
5437
5438 SmallVector<uint64_t, 64> Record;
5439
5440 // Read all the records for this value table.
5441 SmallString<128> ValueName;
5442 while (1) {
5443 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5444
5445 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005446 case BitstreamEntry::SubBlock: // Handled for us already.
5447 case BitstreamEntry::Error:
5448 return error("Malformed block");
5449 case BitstreamEntry::EndBlock:
5450 return std::error_code();
5451 case BitstreamEntry::Record:
5452 // The interesting case.
5453 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005454 }
5455
5456 // Read a record.
5457 Record.clear();
5458 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005459 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5460 break;
5461 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00005462 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005463 if (convertToString(Record, 2, ValueName))
5464 return error("Invalid record");
5465 unsigned ValueID = Record[0];
5466 uint64_t FuncOffset = Record[1];
Teresa Johnsone1164de2016-02-10 21:55:02 +00005467 assert(!IsLazy && "Lazy summary read only supported for combined index");
5468 // Gracefully handle bitcode without a function summary section,
5469 // which will simply not populate the index.
5470 if (foundFuncSummary()) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005471 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5472 SummaryMap.find(ValueID);
5473 assert(SMI != SummaryMap.end() && "Summary info not found");
Teresa Johnsone1164de2016-02-10 21:55:02 +00005474 std::unique_ptr<FunctionInfo> FuncInfo =
5475 llvm::make_unique<FunctionInfo>(FuncOffset);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005476 FuncInfo->setFunctionSummary(std::move(SMI->second));
Teresa Johnsone1164de2016-02-10 21:55:02 +00005477 assert(!SourceFileName.empty());
5478 std::string FunctionGlobalId = Function::getGlobalIdentifier(
5479 ValueName, FuncInfo->functionSummary()->getFunctionLinkage(),
5480 SourceFileName);
5481 TheIndex->addFunctionInfo(FunctionGlobalId, std::move(FuncInfo));
Teresa Johnson403a7872015-10-04 14:33:43 +00005482 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005483
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005484 ValueName.clear();
5485 break;
5486 }
5487 case bitc::VST_CODE_COMBINED_FNENTRY: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00005488 // VST_CODE_COMBINED_FNENTRY: [offset, funcguid]
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005489 uint64_t FuncSummaryOffset = Record[0];
Teresa Johnsone1164de2016-02-10 21:55:02 +00005490 uint64_t FuncGUID = Record[1];
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005491 std::unique_ptr<FunctionInfo> FuncInfo =
5492 llvm::make_unique<FunctionInfo>(FuncSummaryOffset);
5493 if (foundFuncSummary() && !IsLazy) {
5494 DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5495 SummaryMap.find(FuncSummaryOffset);
5496 assert(SMI != SummaryMap.end() && "Summary info not found");
5497 FuncInfo->setFunctionSummary(std::move(SMI->second));
Teresa Johnson403a7872015-10-04 14:33:43 +00005498 }
Teresa Johnsone1164de2016-02-10 21:55:02 +00005499 TheIndex->addFunctionInfo(FuncGUID, std::move(FuncInfo));
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005500
5501 ValueName.clear();
5502 break;
5503 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005504 }
5505 }
5506}
5507
5508// Parse just the blocks needed for function index building out of the module.
5509// At the end of this routine the function Index is populated with a map
5510// from function name to FunctionInfo. The function info contains
5511// either the parsed function summary information (when parsing summaries
5512// eagerly), or just to the function summary record's offset
5513// if parsing lazily (IsLazy).
5514std::error_code FunctionIndexBitcodeReader::parseModule() {
5515 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5516 return error("Invalid record");
5517
Teresa Johnsone1164de2016-02-10 21:55:02 +00005518 SmallVector<uint64_t, 64> Record;
5519
Teresa Johnson403a7872015-10-04 14:33:43 +00005520 // Read the function index for this module.
5521 while (1) {
5522 BitstreamEntry Entry = Stream.advance();
5523
5524 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005525 case BitstreamEntry::Error:
5526 return error("Malformed block");
5527 case BitstreamEntry::EndBlock:
5528 return std::error_code();
5529
5530 case BitstreamEntry::SubBlock:
5531 if (CheckFuncSummaryPresenceOnly) {
Teresa Johnson6290dbc2015-11-21 21:55:48 +00005532 if (Entry.ID == bitc::FUNCTION_SUMMARY_BLOCK_ID) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005533 SeenFuncSummary = true;
Teresa Johnson6290dbc2015-11-21 21:55:48 +00005534 // No need to parse the rest since we found the summary.
5535 return std::error_code();
5536 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005537 if (Stream.SkipBlock())
5538 return error("Invalid record");
Teresa Johnson6290dbc2015-11-21 21:55:48 +00005539 continue;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005540 }
5541 switch (Entry.ID) {
5542 default: // Skip unknown content.
5543 if (Stream.SkipBlock())
5544 return error("Invalid record");
5545 break;
5546 case bitc::BLOCKINFO_BLOCK_ID:
5547 // Need to parse these to get abbrev ids (e.g. for VST)
5548 if (Stream.ReadBlockInfoBlock())
5549 return error("Malformed block");
5550 break;
5551 case bitc::VALUE_SYMTAB_BLOCK_ID:
5552 if (std::error_code EC = parseValueSymbolTable())
5553 return EC;
5554 break;
5555 case bitc::FUNCTION_SUMMARY_BLOCK_ID:
5556 SeenFuncSummary = true;
5557 if (IsLazy) {
5558 // Lazy parsing of summary info, skip it.
5559 if (Stream.SkipBlock())
5560 return error("Invalid record");
5561 } else if (std::error_code EC = parseEntireSummary())
5562 return EC;
5563 break;
5564 case bitc::MODULE_STRTAB_BLOCK_ID:
5565 if (std::error_code EC = parseModuleStringTable())
5566 return EC;
5567 break;
5568 }
5569 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00005570
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005571 case BitstreamEntry::Record:
Teresa Johnsone1164de2016-02-10 21:55:02 +00005572 // Once we find the single record of interest, skip the rest.
5573 if (!SourceFileName.empty())
5574 Stream.skipRecord(Entry.ID);
5575 else {
5576 Record.clear();
5577 auto BitCode = Stream.readRecord(Entry.ID, Record);
5578 switch (BitCode) {
5579 default:
5580 break; // Default behavior, ignore unknown content.
5581 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5582 case bitc::MODULE_CODE_SOURCE_FILENAME:
5583 SmallString<128> ValueName;
5584 if (convertToString(Record, 0, ValueName))
5585 return error("Invalid record");
5586 SourceFileName = ValueName.c_str();
5587 break;
5588 }
5589 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005590 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00005591 }
5592 }
5593}
5594
5595// Eagerly parse the entire function summary block (i.e. for all functions
5596// in the index). This populates the FunctionSummary objects in
5597// the index.
5598std::error_code FunctionIndexBitcodeReader::parseEntireSummary() {
5599 if (Stream.EnterSubBlock(bitc::FUNCTION_SUMMARY_BLOCK_ID))
5600 return error("Invalid record");
5601
5602 SmallVector<uint64_t, 64> Record;
5603
5604 while (1) {
5605 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5606
5607 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005608 case BitstreamEntry::SubBlock: // Handled for us already.
5609 case BitstreamEntry::Error:
5610 return error("Malformed block");
5611 case BitstreamEntry::EndBlock:
5612 return std::error_code();
5613 case BitstreamEntry::Record:
5614 // The interesting case.
5615 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005616 }
5617
5618 // Read a record. The record format depends on whether this
5619 // is a per-module index or a combined index file. In the per-module
5620 // case the records contain the associated value's ID for correlation
5621 // with VST entries. In the combined index the correlation is done
5622 // via the bitcode offset of the summary records (which were saved
5623 // in the combined index VST entries). The records also contain
5624 // information used for ThinLTO renaming and importing.
5625 Record.clear();
5626 uint64_t CurRecordBit = Stream.GetCurrentBitNo();
5627 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005628 default: // Default behavior: ignore.
5629 break;
Teresa Johnson5e22e442016-02-06 16:07:35 +00005630 // FS_PERMODULE_ENTRY: [valueid, linkage, instcount]
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005631 case bitc::FS_CODE_PERMODULE_ENTRY: {
5632 unsigned ValueID = Record[0];
Teresa Johnson5e22e442016-02-06 16:07:35 +00005633 uint64_t RawLinkage = Record[1];
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005634 unsigned InstCount = Record[2];
5635 std::unique_ptr<FunctionSummary> FS =
5636 llvm::make_unique<FunctionSummary>(InstCount);
Teresa Johnson5e22e442016-02-06 16:07:35 +00005637 FS->setFunctionLinkage(getDecodedLinkage(RawLinkage));
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005638 // The module path string ref set in the summary must be owned by the
5639 // index's module string table. Since we don't have a module path
5640 // string table section in the per-module index, we create a single
5641 // module path string table entry with an empty (0) ID to take
5642 // ownership.
5643 FS->setModulePath(
5644 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0));
5645 SummaryMap[ValueID] = std::move(FS);
Teresa Johnsonbbe05452016-02-24 17:57:28 +00005646 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005647 }
Teresa Johnson5e22e442016-02-06 16:07:35 +00005648 // FS_COMBINED_ENTRY: [modid, linkage, instcount]
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005649 case bitc::FS_CODE_COMBINED_ENTRY: {
5650 uint64_t ModuleId = Record[0];
Teresa Johnson5e22e442016-02-06 16:07:35 +00005651 uint64_t RawLinkage = Record[1];
5652 unsigned InstCount = Record[2];
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005653 std::unique_ptr<FunctionSummary> FS =
5654 llvm::make_unique<FunctionSummary>(InstCount);
Teresa Johnson5e22e442016-02-06 16:07:35 +00005655 FS->setFunctionLinkage(getDecodedLinkage(RawLinkage));
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005656 FS->setModulePath(ModuleIdMap[ModuleId]);
5657 SummaryMap[CurRecordBit] = std::move(FS);
Teresa Johnsonbbe05452016-02-24 17:57:28 +00005658 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005659 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005660 }
5661 }
5662 llvm_unreachable("Exit infinite loop");
5663}
5664
5665// Parse the module string table block into the Index.
5666// This populates the ModulePathStringTable map in the index.
5667std::error_code FunctionIndexBitcodeReader::parseModuleStringTable() {
5668 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5669 return error("Invalid record");
5670
5671 SmallVector<uint64_t, 64> Record;
5672
5673 SmallString<128> ModulePath;
5674 while (1) {
5675 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5676
5677 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005678 case BitstreamEntry::SubBlock: // Handled for us already.
5679 case BitstreamEntry::Error:
5680 return error("Malformed block");
5681 case BitstreamEntry::EndBlock:
5682 return std::error_code();
5683 case BitstreamEntry::Record:
5684 // The interesting case.
5685 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005686 }
5687
5688 Record.clear();
5689 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005690 default: // Default behavior: ignore.
5691 break;
5692 case bitc::MST_CODE_ENTRY: {
5693 // MST_ENTRY: [modid, namechar x N]
5694 if (convertToString(Record, 1, ModulePath))
5695 return error("Invalid record");
5696 uint64_t ModuleId = Record[0];
5697 StringRef ModulePathInMap = TheIndex->addModulePath(ModulePath, ModuleId);
5698 ModuleIdMap[ModuleId] = ModulePathInMap;
5699 ModulePath.clear();
5700 break;
5701 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005702 }
5703 }
5704 llvm_unreachable("Exit infinite loop");
5705}
5706
5707// Parse the function info index from the bitcode streamer into the given index.
5708std::error_code FunctionIndexBitcodeReader::parseSummaryIndexInto(
5709 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I) {
5710 TheIndex = I;
5711
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005712 if (std::error_code EC = initStream(std::move(Streamer)))
5713 return EC;
Teresa Johnson403a7872015-10-04 14:33:43 +00005714
5715 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005716 if (!hasValidBitcodeHeader(Stream))
5717 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00005718
5719 // We expect a number of well-defined blocks, though we don't necessarily
5720 // need to understand them all.
5721 while (1) {
5722 if (Stream.AtEndOfStream()) {
5723 // We didn't really read a proper Module block.
5724 return error("Malformed block");
5725 }
5726
5727 BitstreamEntry Entry =
5728 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
5729
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005730 if (Entry.Kind != BitstreamEntry::SubBlock)
5731 return error("Malformed block");
Teresa Johnson403a7872015-10-04 14:33:43 +00005732
5733 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
5734 // building the function summary index.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005735 if (Entry.ID == bitc::MODULE_BLOCK_ID)
5736 return parseModule();
Teresa Johnson403a7872015-10-04 14:33:43 +00005737
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005738 if (Stream.SkipBlock())
5739 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00005740 }
5741}
5742
5743// Parse the function information at the given offset in the buffer into
5744// the index. Used to support lazy parsing of function summaries from the
5745// combined index during importing.
5746// TODO: This function is not yet complete as it won't have a consumer
5747// until ThinLTO function importing is added.
5748std::error_code FunctionIndexBitcodeReader::parseFunctionSummary(
5749 std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I,
5750 size_t FunctionSummaryOffset) {
5751 TheIndex = I;
5752
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005753 if (std::error_code EC = initStream(std::move(Streamer)))
5754 return EC;
Teresa Johnson403a7872015-10-04 14:33:43 +00005755
5756 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005757 if (!hasValidBitcodeHeader(Stream))
5758 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00005759
5760 Stream.JumpToBit(FunctionSummaryOffset);
5761
5762 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5763
5764 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005765 default:
5766 return error("Malformed block");
5767 case BitstreamEntry::Record:
5768 // The expected case.
5769 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005770 }
5771
5772 // TODO: Read a record. This interface will be completed when ThinLTO
5773 // importing is added so that it can be tested.
5774 SmallVector<uint64_t, 64> Record;
5775 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005776 case bitc::FS_CODE_COMBINED_ENTRY:
5777 default:
5778 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00005779 }
5780
5781 return std::error_code();
5782}
5783
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005784std::error_code
5785FunctionIndexBitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5786 if (Streamer)
5787 return initLazyStream(std::move(Streamer));
Teresa Johnson403a7872015-10-04 14:33:43 +00005788 return initStreamFromBuffer();
5789}
5790
5791std::error_code FunctionIndexBitcodeReader::initStreamFromBuffer() {
5792 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
5793 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
5794
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005795 if (Buffer->getBufferSize() & 3)
5796 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00005797
5798 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5799 // The magic number is 0x0B17C0DE stored in little endian.
5800 if (isBitcodeWrapper(BufPtr, BufEnd))
5801 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5802 return error("Invalid bitcode wrapper header");
5803
5804 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5805 Stream.init(&*StreamFile);
5806
5807 return std::error_code();
5808}
5809
5810std::error_code FunctionIndexBitcodeReader::initLazyStream(
5811 std::unique_ptr<DataStreamer> Streamer) {
5812 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5813 // see it.
5814 auto OwnedBytes =
5815 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5816 StreamingMemoryObject &Bytes = *OwnedBytes;
5817 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5818 Stream.init(&*StreamFile);
5819
5820 unsigned char buf[16];
5821 if (Bytes.readBytes(buf, 16, 0) != 16)
5822 return error("Invalid bitcode signature");
5823
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005824 if (!isBitcode(buf, buf + 16))
5825 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00005826
5827 if (isBitcodeWrapper(buf, buf + 4)) {
5828 const unsigned char *bitcodeStart = buf;
5829 const unsigned char *bitcodeEnd = buf + 16;
5830 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5831 Bytes.dropLeadingBytes(bitcodeStart - buf);
5832 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5833 }
5834 return std::error_code();
5835}
5836
Rafael Espindola48da4f42013-11-04 16:16:24 +00005837namespace {
Rafael Espindola25188c92014-06-12 01:45:43 +00005838class BitcodeErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +00005839 const char *name() const LLVM_NOEXCEPT override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00005840 return "llvm.bitcode";
5841 }
Craig Topper73156022014-03-02 09:09:27 +00005842 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00005843 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005844 switch (E) {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00005845 case BitcodeError::InvalidBitcodeSignature:
Rafael Espindola48da4f42013-11-04 16:16:24 +00005846 return "Invalid bitcode signature";
Rafael Espindolad0b23be2015-01-10 00:07:30 +00005847 case BitcodeError::CorruptedBitcode:
5848 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00005849 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00005850 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00005851 }
5852};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00005853} // end anonymous namespace
Rafael Espindola48da4f42013-11-04 16:16:24 +00005854
Chris Bieneman770163e2014-09-19 20:29:02 +00005855static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5856
Rafael Espindolac3f2e732014-07-29 20:22:46 +00005857const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00005858 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005859}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00005860
Chris Lattner6694f602007-04-29 07:54:31 +00005861//===----------------------------------------------------------------------===//
5862// External interface
5863//===----------------------------------------------------------------------===//
5864
Rafael Espindola456baad2015-06-17 01:15:47 +00005865static ErrorOr<std::unique_ptr<Module>>
5866getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
5867 BitcodeReader *R, LLVMContext &Context,
5868 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
5869 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5870 M->setMaterializer(R);
5871
5872 auto cleanupOnError = [&](std::error_code EC) {
5873 R->releaseBuffer(); // Never take ownership on error.
5874 return EC;
5875 };
5876
5877 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5878 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
5879 ShouldLazyLoadMetadata))
5880 return cleanupOnError(EC);
5881
5882 if (MaterializeAll) {
5883 // Read in the entire module, and destroy the BitcodeReader.
Rafael Espindolac4a03482015-12-18 20:13:39 +00005884 if (std::error_code EC = M->materializeAll())
Rafael Espindola456baad2015-06-17 01:15:47 +00005885 return cleanupOnError(EC);
5886 } else {
5887 // Resolve forward references from blockaddresses.
5888 if (std::error_code EC = R->materializeForwardReferencedFunctions())
5889 return cleanupOnError(EC);
5890 }
5891 return std::move(M);
5892}
5893
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005894/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00005895///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005896/// This isn't always used in a lazy context. In particular, it's also used by
5897/// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
5898/// in forward-referenced functions from block address references.
5899///
Rafael Espindola728074b2015-06-17 00:40:56 +00005900/// \param[in] MaterializeAll Set to \c true if we should materialize
5901/// everything.
Rafael Espindoladcd1dca2015-06-16 22:27:55 +00005902static ErrorOr<std::unique_ptr<Module>>
Rafael Espindola68812152014-09-03 17:31:46 +00005903getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindola728074b2015-06-17 00:40:56 +00005904 LLVMContext &Context, bool MaterializeAll,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00005905 bool ShouldLazyLoadMetadata = false) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005906 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005907
Rafael Espindola456baad2015-06-17 01:15:47 +00005908 ErrorOr<std::unique_ptr<Module>> Ret =
5909 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
5910 MaterializeAll, ShouldLazyLoadMetadata);
5911 if (!Ret)
5912 return Ret;
Rafael Espindolab7993462012-01-02 07:49:53 +00005913
Rafael Espindolae2c1d772014-08-26 22:00:09 +00005914 Buffer.release(); // The BitcodeReader owns it now.
Rafael Espindola456baad2015-06-17 01:15:47 +00005915 return Ret;
Chris Lattner6694f602007-04-29 07:54:31 +00005916}
5917
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005918ErrorOr<std::unique_ptr<Module>>
5919llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
5920 LLVMContext &Context, bool ShouldLazyLoadMetadata) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00005921 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005922 ShouldLazyLoadMetadata);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005923}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005924
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005925ErrorOr<std::unique_ptr<Module>>
5926llvm::getStreamedBitcodeModule(StringRef Name,
5927 std::unique_ptr<DataStreamer> Streamer,
5928 LLVMContext &Context) {
Rafael Espindola7d727b52014-12-18 05:08:43 +00005929 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005930 BitcodeReader *R = new BitcodeReader(Context);
Rafael Espindola456baad2015-06-17 01:15:47 +00005931
5932 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
5933 false);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005934}
5935
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005936ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
5937 LLVMContext &Context) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00005938 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005939 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
Chad Rosierca2567b2011-12-07 21:44:12 +00005940 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5941 // written. We must defer until the Module has been fully materialized.
Chris Lattner6694f602007-04-29 07:54:31 +00005942}
Bill Wendling0198ce02010-10-06 01:22:42 +00005943
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005944std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
5945 LLVMContext &Context) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00005946 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005947 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00005948 ErrorOr<std::string> Triple = R->parseTriple();
Rafael Espindolad346cc82014-07-04 13:52:01 +00005949 if (Triple.getError())
5950 return "";
5951 return Triple.get();
Bill Wendling0198ce02010-10-06 01:22:42 +00005952}
Teresa Johnson403a7872015-10-04 14:33:43 +00005953
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005954std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
5955 LLVMContext &Context) {
Mehdi Amini3383ccc2015-11-09 02:46:41 +00005956 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005957 BitcodeReader R(Buf.release(), Context);
Mehdi Amini3383ccc2015-11-09 02:46:41 +00005958 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
5959 if (ProducerString.getError())
5960 return "";
5961 return ProducerString.get();
5962}
5963
Teresa Johnson403a7872015-10-04 14:33:43 +00005964// Parse the specified bitcode buffer, returning the function info index.
5965// If IsLazy is false, parse the entire function summary into
5966// the index. Otherwise skip the function summary section, and only create
5967// an index object with a map from function name to function summary offset.
5968// The index is used to perform lazy function summary reading later.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005969ErrorOr<std::unique_ptr<FunctionInfoIndex>>
Mehdi Amini354f5202015-11-19 05:52:29 +00005970llvm::getFunctionInfoIndex(MemoryBufferRef Buffer,
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005971 DiagnosticHandlerFunction DiagnosticHandler,
Mehdi Amini9abe1082015-12-03 02:37:23 +00005972 bool IsLazy) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005973 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Mehdi Amini354f5202015-11-19 05:52:29 +00005974 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, IsLazy);
Teresa Johnson403a7872015-10-04 14:33:43 +00005975
Mehdi Amini9abe1082015-12-03 02:37:23 +00005976 auto Index = llvm::make_unique<FunctionInfoIndex>();
Teresa Johnson403a7872015-10-04 14:33:43 +00005977
5978 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005979 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00005980 return EC;
5981 };
5982
5983 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
5984 return cleanupOnError(EC);
5985
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005986 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
Teresa Johnson403a7872015-10-04 14:33:43 +00005987 return std::move(Index);
5988}
5989
5990// Check if the given bitcode buffer contains a function summary block.
Mehdi Amini354f5202015-11-19 05:52:29 +00005991bool llvm::hasFunctionSummary(MemoryBufferRef Buffer,
Teresa Johnson403a7872015-10-04 14:33:43 +00005992 DiagnosticHandlerFunction DiagnosticHandler) {
5993 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Mehdi Amini354f5202015-11-19 05:52:29 +00005994 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, false, true);
Teresa Johnson403a7872015-10-04 14:33:43 +00005995
5996 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005997 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00005998 return false;
5999 };
6000
6001 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
6002 return cleanupOnError(EC);
6003
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006004 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
Teresa Johnson403a7872015-10-04 14:33:43 +00006005 return R.foundFuncSummary();
6006}
6007
6008// This method supports lazy reading of function summary data from the combined
6009// index during ThinLTO function importing. When reading the combined index
6010// file, getFunctionInfoIndex is first invoked with IsLazy=true.
6011// Then this method is called for each function considered for importing,
6012// to parse the summary information for the given function name into
6013// the index.
Mehdi Amini354f5202015-11-19 05:52:29 +00006014std::error_code llvm::readFunctionSummary(
6015 MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler,
6016 StringRef FunctionName, std::unique_ptr<FunctionInfoIndex> Index) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006017 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Mehdi Amini354f5202015-11-19 05:52:29 +00006018 FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler);
Teresa Johnson403a7872015-10-04 14:33:43 +00006019
6020 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006021 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00006022 return EC;
6023 };
6024
6025 // Lookup the given function name in the FunctionMap, which may
6026 // contain a list of function infos in the case of a COMDAT. Walk through
6027 // and parse each function summary info at the function summary offset
6028 // recorded when parsing the value symbol table.
6029 for (const auto &FI : Index->getFunctionInfoList(FunctionName)) {
6030 size_t FunctionSummaryOffset = FI->bitcodeIndex();
6031 if (std::error_code EC =
6032 R.parseFunctionSummary(nullptr, Index.get(), FunctionSummaryOffset))
6033 return cleanupOnError(EC);
6034 }
6035
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006036 Buf.release(); // The FunctionIndexBitcodeReader owns it now.
Teresa Johnson403a7872015-10-04 14:33:43 +00006037 return std::error_code();
6038}