blob: 39f2d6ae333b87c24fe83ac413e7eb1476b4aab9 [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
Benjamin Kramer0a446fd2015-03-01 21:28:53 +000010#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000011#include "llvm/ADT/SmallString.h"
12#include "llvm/ADT/SmallVector.h"
David Majnemer3087b222015-01-20 05:58:07 +000013#include "llvm/ADT/Triple.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000014#include "llvm/Bitcode/BitstreamReader.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000015#include "llvm/Bitcode/LLVMBitCodes.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000016#include "llvm/Bitcode/ReaderWriter.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"
Teresa Johnson26ab5772016-03-15 00:04:37 +000028#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/OperandTraits.h"
30#include "llvm/IR/Operator.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000031#include "llvm/IR/ValueHandle.h"
Teresa Johnson916495d2016-04-04 18:52:58 +000032#include "llvm/Support/CommandLine.h"
Derek Schuff8b2dcad2012-02-06 22:30:29 +000033#include "llvm/Support/DataStream.h"
Teresa Johnson916495d2016-04-04 18:52:58 +000034#include "llvm/Support/Debug.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000035#include "llvm/Support/ManagedStatic.h"
Chris Lattner08feb1e2007-04-24 04:04:35 +000036#include "llvm/Support/MathExtras.h"
Chris Lattner6694f602007-04-29 07:54:31 +000037#include "llvm/Support/MemoryBuffer.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000038#include "llvm/Support/raw_ostream.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000039#include <deque>
Eugene Zelenko6ac3f732016-01-26 18:48:36 +000040
Chris Lattner1314b992007-04-22 06:23:29 +000041using namespace llvm;
42
Teresa Johnson916495d2016-04-04 18:52:58 +000043static cl::opt<bool> PrintSummaryGUIDs(
44 "print-summary-global-ids", cl::init(false), cl::Hidden,
45 cl::desc(
46 "Print the global id for each value when reading the module summary"));
47
Benjamin Kramercced8be2015-03-17 20:40:24 +000048namespace {
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +000049enum {
50 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
51};
52
Benjamin Kramercced8be2015-03-17 20:40:24 +000053class BitcodeReaderValueList {
54 std::vector<WeakVH> ValuePtrs;
55
Rafael Espindolacbdcb502015-06-15 20:55:37 +000056 /// As we resolve forward-referenced constants, we add information about them
57 /// to this vector. This allows us to resolve them in bulk instead of
58 /// resolving each reference at a time. See the code in
Benjamin Kramercced8be2015-03-17 20:40:24 +000059 /// ResolveConstantForwardRefs for more information about this.
60 ///
61 /// The key of this vector is the placeholder constant, the value is the slot
62 /// number that holds the resolved value.
63 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
64 ResolveConstantsTy ResolveConstants;
65 LLVMContext &Context;
66public:
67 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
68 ~BitcodeReaderValueList() {
69 assert(ResolveConstants.empty() && "Constants not resolved?");
70 }
71
72 // vector compatibility methods
73 unsigned size() const { return ValuePtrs.size(); }
74 void resize(unsigned N) { ValuePtrs.resize(N); }
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +000075 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
Benjamin Kramercced8be2015-03-17 20:40:24 +000076
77 void clear() {
78 assert(ResolveConstants.empty() && "Constants not resolved?");
79 ValuePtrs.clear();
80 }
81
82 Value *operator[](unsigned i) const {
83 assert(i < ValuePtrs.size());
84 return ValuePtrs[i];
85 }
86
87 Value *back() const { return ValuePtrs.back(); }
Duncan P. N. Exon Smith7457ecb2016-03-30 04:21:52 +000088 void pop_back() { ValuePtrs.pop_back(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +000089 bool empty() const { return ValuePtrs.empty(); }
90 void shrinkTo(unsigned N) {
91 assert(N <= size() && "Invalid shrinkTo request!");
92 ValuePtrs.resize(N);
93 }
94
95 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
David Majnemer8a1c45d2015-12-12 05:38:55 +000096 Value *getValueFwdRef(unsigned Idx, Type *Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +000097
David Majnemer8a1c45d2015-12-12 05:38:55 +000098 void assignValue(Value *V, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +000099
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000100 /// Once all constants are read, this method bulk resolves any forward
101 /// references.
102 void resolveConstantForwardRefs();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000103};
104
Teresa Johnson61b406e2015-12-29 23:00:22 +0000105class BitcodeReaderMetadataList {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000106 unsigned NumFwdRefs;
107 bool AnyFwdRefs;
108 unsigned MinFwdRef;
109 unsigned MaxFwdRef;
Teresa Johnson61b406e2015-12-29 23:00:22 +0000110 std::vector<TrackingMDRef> MetadataPtrs;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000111
112 LLVMContext &Context;
113public:
Teresa Johnson61b406e2015-12-29 23:00:22 +0000114 BitcodeReaderMetadataList(LLVMContext &C)
Teresa Johnson34702952015-12-21 15:38:13 +0000115 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
Benjamin Kramercced8be2015-03-17 20:40:24 +0000116
117 // vector compatibility methods
Teresa Johnson61b406e2015-12-29 23:00:22 +0000118 unsigned size() const { return MetadataPtrs.size(); }
119 void resize(unsigned N) { MetadataPtrs.resize(N); }
120 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
121 void clear() { MetadataPtrs.clear(); }
122 Metadata *back() const { return MetadataPtrs.back(); }
123 void pop_back() { MetadataPtrs.pop_back(); }
124 bool empty() const { return MetadataPtrs.empty(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000125
126 Metadata *operator[](unsigned i) const {
Teresa Johnson61b406e2015-12-29 23:00:22 +0000127 assert(i < MetadataPtrs.size());
128 return MetadataPtrs[i];
Benjamin Kramercced8be2015-03-17 20:40:24 +0000129 }
130
131 void shrinkTo(unsigned N) {
132 assert(N <= size() && "Invalid shrinkTo request!");
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +0000133 assert(!AnyFwdRefs && "Unexpected forward refs");
Teresa Johnson61b406e2015-12-29 23:00:22 +0000134 MetadataPtrs.resize(N);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000135 }
136
Justin Bognerae341c62016-03-17 20:12:06 +0000137 Metadata *getMetadataFwdRef(unsigned Idx);
138 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000139 void assignValue(Metadata *MD, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000140 void tryToResolveCycles();
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +0000141 bool hasFwdRefs() const { return AnyFwdRefs; }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000142};
143
144class BitcodeReader : public GVMaterializer {
145 LLVMContext &Context;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000146 Module *TheModule = nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000147 std::unique_ptr<MemoryBuffer> Buffer;
148 std::unique_ptr<BitstreamReader> StreamFile;
149 BitstreamCursor Stream;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000150 // Next offset to start scanning for lazy parsing of function bodies.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000151 uint64_t NextUnreadBit = 0;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000152 // Last function offset found in the VST.
153 uint64_t LastFunctionBlockBit = 0;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000154 bool SeenValueSymbolTable = false;
Peter Collingbourne128a9762015-10-27 23:01:25 +0000155 uint64_t VSTOffset = 0;
Mehdi Amini5d303282015-10-26 18:37:00 +0000156 // Contains an arbitrary and optional string identifying the bitcode producer
157 std::string ProducerIdentification;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000158
159 std::vector<Type*> TypeList;
160 BitcodeReaderValueList ValueList;
Teresa Johnson61b406e2015-12-29 23:00:22 +0000161 BitcodeReaderMetadataList MetadataList;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000162 std::vector<Comdat *> ComdatList;
163 SmallVector<Instruction *, 64> InstructionList;
164
165 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
166 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
167 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
168 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
David Majnemer7fddecc2015-06-17 20:52:32 +0000169 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000170
171 SmallVector<Instruction*, 64> InstsWithTBAATag;
172
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +0000173 bool HasSeenOldLoopTags = false;
174
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000175 /// The set of attributes by index. Index zero in the file is for null, and
176 /// is thus not represented here. As such all indices are off by one.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000177 std::vector<AttributeSet> MAttributes;
178
Karl Schimpf36440082015-08-31 16:43:55 +0000179 /// The set of attribute groups.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000180 std::map<unsigned, AttributeSet> MAttributeGroups;
181
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000182 /// While parsing a function body, this is a list of the basic blocks for the
183 /// function.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000184 std::vector<BasicBlock*> FunctionBBs;
185
186 // When reading the module header, this list is populated with functions that
187 // have bodies later in the file.
188 std::vector<Function*> FunctionsWithBodies;
189
190 // When intrinsic functions are encountered which require upgrading they are
191 // stored here with their replacement function.
Rafael Espindola4e721212015-07-02 16:22:40 +0000192 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000193 UpgradedIntrinsicMap UpgradedIntrinsics;
194
195 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
196 DenseMap<unsigned, unsigned> MDKindMap;
197
198 // Several operations happen after the module header has been read, but
199 // before function bodies are processed. This keeps track of whether
200 // we've done this yet.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000201 bool SeenFirstFunctionBody = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000202
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000203 /// When function bodies are initially scanned, this map contains info about
204 /// where to find deferred function body in the stream.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000205 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
206
207 /// When Metadata block is initially scanned when parsing the module, we may
208 /// choose to defer parsing of the metadata. This vector contains info about
209 /// which Metadata blocks are deferred.
210 std::vector<uint64_t> DeferredMetadataInfo;
211
212 /// These are basic blocks forward-referenced by block addresses. They are
213 /// inserted lazily into functions when they're loaded. The basic block ID is
214 /// its index into the vector.
215 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
216 std::deque<Function *> BasicBlockFwdRefQueue;
217
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000218 /// Indicates that we are using a new encoding for instruction operands where
219 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
220 /// instruction number, for a more compact encoding. Some instruction
221 /// operands are not relative to the instruction ID: basic block numbers, and
222 /// types. Once the old style function blocks have been phased out, we would
Benjamin Kramercced8be2015-03-17 20:40:24 +0000223 /// not need this flag.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000224 bool UseRelativeIDs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000225
226 /// True if all functions will be materialized, negating the need to process
227 /// (e.g.) blockaddress forward references.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000228 bool WillMaterializeAllForwardRefs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000229
Benjamin Kramercced8be2015-03-17 20:40:24 +0000230 /// True if any Metadata block has been materialized.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000231 bool IsMetadataMaterialized = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000232
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000233 bool StripDebugInfo = false;
234
Peter Collingbourned4bff302015-11-05 22:03:56 +0000235 /// Functions that need to be matched with subprograms when upgrading old
236 /// metadata.
237 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
238
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000239 std::vector<std::string> BundleTags;
240
Benjamin Kramercced8be2015-03-17 20:40:24 +0000241public:
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000242 std::error_code error(BitcodeError E, const Twine &Message);
243 std::error_code error(BitcodeError E);
244 std::error_code error(const Twine &Message);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000245
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000246 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context);
247 BitcodeReader(LLVMContext &Context);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000248 ~BitcodeReader() override { freeState(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000249
250 std::error_code materializeForwardReferencedFunctions();
251
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000252 void freeState();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000253
254 void releaseBuffer();
255
Benjamin Kramercced8be2015-03-17 20:40:24 +0000256 std::error_code materialize(GlobalValue *GV) override;
Rafael Espindola79753a02015-12-18 21:18:57 +0000257 std::error_code materializeModule() override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000258 std::vector<StructType *> getIdentifiedStructTypes() const override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000259
Rafael Espindola6ace6852015-06-15 21:02:49 +0000260 /// \brief Main interface to parsing a bitcode buffer.
261 /// \returns true if an error occurred.
Rafael Espindola1aabf982015-06-16 23:29:49 +0000262 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
263 Module *M,
Benjamin Kramercced8be2015-03-17 20:40:24 +0000264 bool ShouldLazyLoadMetadata = false);
265
Rafael Espindola6ace6852015-06-15 21:02:49 +0000266 /// \brief Cheap mechanism to just extract module triple
267 /// \returns true if an error occurred.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000268 ErrorOr<std::string> parseTriple();
269
Mehdi Amini3383ccc2015-11-09 02:46:41 +0000270 /// Cheap mechanism to just extract the identification block out of bitcode.
271 ErrorOr<std::string> parseIdentificationBlock();
272
Benjamin Kramercced8be2015-03-17 20:40:24 +0000273 static uint64_t decodeSignRotatedValue(uint64_t V);
274
275 /// Materialize any deferred Metadata block.
276 std::error_code materializeMetadata() override;
277
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000278 void setStripDebugInfo() override;
279
Benjamin Kramercced8be2015-03-17 20:40:24 +0000280private:
Mehdi Amini5d303282015-10-26 18:37:00 +0000281 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
282 // ProducerIdentification data member, and do some basic enforcement on the
283 // "epoch" encoded in the bitcode.
284 std::error_code parseBitcodeVersion();
285
Benjamin Kramercced8be2015-03-17 20:40:24 +0000286 std::vector<StructType *> IdentifiedStructTypes;
287 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
288 StructType *createIdentifiedStructType(LLVMContext &Context);
289
290 Type *getTypeByID(unsigned ID);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000291 Value *getFnValueByID(unsigned ID, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000292 if (Ty && Ty->isMetadataTy())
293 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
David Majnemer8a1c45d2015-12-12 05:38:55 +0000294 return ValueList.getValueFwdRef(ID, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000295 }
296 Metadata *getFnMetadataByID(unsigned ID) {
Justin Bognerae341c62016-03-17 20:12:06 +0000297 return MetadataList.getMetadataFwdRef(ID);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000298 }
299 BasicBlock *getBasicBlock(unsigned ID) const {
300 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
301 return FunctionBBs[ID];
302 }
303 AttributeSet getAttributes(unsigned i) const {
304 if (i-1 < MAttributes.size())
305 return MAttributes[i-1];
306 return AttributeSet();
307 }
308
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000309 /// Read a value/type pair out of the specified record from slot 'Slot'.
310 /// Increment Slot past the number of slots used in the record. Return true on
311 /// failure.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000312 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
313 unsigned InstNum, Value *&ResVal) {
314 if (Slot == Record.size()) return true;
315 unsigned ValNo = (unsigned)Record[Slot++];
316 // Adjust the ValNo, if it was encoded relative to the InstNum.
317 if (UseRelativeIDs)
318 ValNo = InstNum - ValNo;
319 if (ValNo < InstNum) {
320 // If this is not a forward reference, just return the value we already
321 // have.
322 ResVal = getFnValueByID(ValNo, nullptr);
323 return ResVal == nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000324 }
David Blaikiedbe6e0f2015-04-17 06:40:14 +0000325 if (Slot == Record.size())
326 return true;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000327
328 unsigned TypeNo = (unsigned)Record[Slot++];
329 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
330 return ResVal == nullptr;
331 }
332
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000333 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
334 /// past the number of slots used by the value in the record. Return true if
335 /// there is an error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000336 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000337 unsigned InstNum, Type *Ty, Value *&ResVal) {
338 if (getValue(Record, Slot, InstNum, Ty, ResVal))
Benjamin Kramercced8be2015-03-17 20:40:24 +0000339 return true;
340 // All values currently take a single record slot.
341 ++Slot;
342 return false;
343 }
344
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000345 /// Like popValue, but does not increment the Slot number.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000346 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000347 unsigned InstNum, Type *Ty, Value *&ResVal) {
348 ResVal = getValue(Record, Slot, InstNum, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000349 return ResVal == nullptr;
350 }
351
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000352 /// Version of getValue that returns ResVal directly, or 0 if there is an
353 /// error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000354 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000355 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000356 if (Slot == Record.size()) return nullptr;
357 unsigned ValNo = (unsigned)Record[Slot];
358 // Adjust the ValNo, if it was encoded relative to the InstNum.
359 if (UseRelativeIDs)
360 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000361 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000362 }
363
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000364 /// Like getValue, but decodes signed VBRs.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000365 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000366 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000367 if (Slot == Record.size()) return nullptr;
368 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
369 // Adjust the ValNo, if it was encoded relative to the InstNum.
370 if (UseRelativeIDs)
371 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000372 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000373 }
374
375 /// Converts alignment exponent (i.e. power of two (or zero)) to the
376 /// corresponding alignment to use. If alignment is too large, returns
377 /// a corresponding error code.
378 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000379 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
Teresa Johnson1493ad92015-10-10 14:18:36 +0000380 std::error_code parseModule(uint64_t ResumeBit,
381 bool ShouldLazyLoadMetadata = false);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000382 std::error_code parseAttributeBlock();
383 std::error_code parseAttributeGroupBlock();
384 std::error_code parseTypeTable();
385 std::error_code parseTypeTableBody();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000386 std::error_code parseOperandBundleTags();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000387
Teresa Johnsonff642b92015-09-17 20:12:00 +0000388 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
389 unsigned NameIndex, Triple &TT);
Peter Collingbourne128a9762015-10-27 23:01:25 +0000390 std::error_code parseValueSymbolTable(uint64_t Offset = 0);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000391 std::error_code parseConstants();
Teresa Johnson1493ad92015-10-10 14:18:36 +0000392 std::error_code rememberAndSkipFunctionBodies();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000393 std::error_code rememberAndSkipFunctionBody();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000394 /// Save the positions of the Metadata blocks and skip parsing the blocks.
395 std::error_code rememberAndSkipMetadata();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000396 std::error_code parseFunctionBody(Function *F);
397 std::error_code globalCleanup();
398 std::error_code resolveGlobalAndAliasInits();
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +0000399 std::error_code parseMetadata(bool ModuleLevel = false);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +0000400 std::error_code parseMetadataStrings(ArrayRef<uint64_t> Record,
401 StringRef Blob,
402 unsigned &NextMetadataNo);
Teresa Johnson12545072015-11-15 02:00:09 +0000403 std::error_code parseMetadataKinds();
404 std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000405 std::error_code parseMetadataAttachment(Function &F);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000406 ErrorOr<std::string> parseModuleTriple();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000407 std::error_code parseUseLists();
Rafael Espindola1aabf982015-06-16 23:29:49 +0000408 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000409 std::error_code initStreamFromBuffer();
Rafael Espindola1aabf982015-06-16 23:29:49 +0000410 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000411 std::error_code findFunctionInStream(
Benjamin Kramercced8be2015-03-17 20:40:24 +0000412 Function *F,
413 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
414};
Teresa Johnson403a7872015-10-04 14:33:43 +0000415
416/// Class to manage reading and parsing function summary index bitcode
417/// files/sections.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000418class ModuleSummaryIndexBitcodeReader {
Teresa Johnson403a7872015-10-04 14:33:43 +0000419 DiagnosticHandlerFunction DiagnosticHandler;
420
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000421 /// Eventually points to the module index built during parsing.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000422 ModuleSummaryIndex *TheIndex = nullptr;
Teresa Johnson403a7872015-10-04 14:33:43 +0000423
424 std::unique_ptr<MemoryBuffer> Buffer;
425 std::unique_ptr<BitstreamReader> StreamFile;
426 BitstreamCursor Stream;
427
428 /// \brief Used to indicate whether we are doing lazy parsing of summary data.
429 ///
430 /// If false, the summary section is fully parsed into the index during
431 /// the initial parse. Otherwise, if true, the caller is expected to
Teresa Johnson26ab5772016-03-15 00:04:37 +0000432 /// invoke \a readGlobalValueSummary for each summary needed, and the summary
Teresa Johnson403a7872015-10-04 14:33:43 +0000433 /// section is thus parsed lazily.
434 bool IsLazy = false;
435
436 /// Used to indicate whether caller only wants to check for the presence
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000437 /// of the global value summary bitcode section. All blocks are skipped,
438 /// but the SeenGlobalValSummary boolean is set.
439 bool CheckGlobalValSummaryPresenceOnly = false;
Teresa Johnson403a7872015-10-04 14:33:43 +0000440
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000441 /// Indicates whether we have encountered a global value summary section
442 /// yet during parsing, used when checking if file contains global value
Teresa Johnson403a7872015-10-04 14:33:43 +0000443 /// summary section.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000444 bool SeenGlobalValSummary = false;
Teresa Johnson403a7872015-10-04 14:33:43 +0000445
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000446 /// Indicates whether we have already parsed the VST, used for error checking.
447 bool SeenValueSymbolTable = false;
448
449 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
450 /// Used to enable on-demand parsing of the VST.
451 uint64_t VSTOffset = 0;
452
453 // Map to save ValueId to GUID association that was recorded in the
454 // ValueSymbolTable. It is used after the VST is parsed to convert
455 // call graph edges read from the function summary from referencing
456 // callees by their ValueId to using the GUID instead, which is how
Teresa Johnson26ab5772016-03-15 00:04:37 +0000457 // they are recorded in the summary index being built.
Mehdi Aminiad5741b2016-04-02 05:07:53 +0000458 DenseMap<unsigned, GlobalValue::GUID> ValueIdToCallGraphGUIDMap;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000459
460 /// Map to save the association between summary offset in the VST to the
461 /// GlobalValueInfo object created when parsing it. Used to access the
462 /// info object when parsing the summary section.
463 DenseMap<uint64_t, GlobalValueInfo *> SummaryOffsetToInfoMap;
Teresa Johnson403a7872015-10-04 14:33:43 +0000464
465 /// Map populated during module path string table parsing, from the
466 /// module ID to a string reference owned by the index's module
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000467 /// path string table, used to correlate with combined index
Teresa Johnson403a7872015-10-04 14:33:43 +0000468 /// summary records.
469 DenseMap<uint64_t, StringRef> ModuleIdMap;
470
Teresa Johnsone1164de2016-02-10 21:55:02 +0000471 /// Original source file name recorded in a bitcode record.
472 std::string SourceFileName;
473
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000474public:
Teresa Johnson403a7872015-10-04 14:33:43 +0000475 std::error_code error(BitcodeError E, const Twine &Message);
476 std::error_code error(BitcodeError E);
477 std::error_code error(const Twine &Message);
478
Teresa Johnson26ab5772016-03-15 00:04:37 +0000479 ModuleSummaryIndexBitcodeReader(
480 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
481 bool IsLazy = false, bool CheckGlobalValSummaryPresenceOnly = false);
482 ModuleSummaryIndexBitcodeReader(
483 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy = false,
484 bool CheckGlobalValSummaryPresenceOnly = false);
485 ~ModuleSummaryIndexBitcodeReader() { freeState(); }
Teresa Johnson403a7872015-10-04 14:33:43 +0000486
487 void freeState();
488
489 void releaseBuffer();
490
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000491 /// Check if the parser has encountered a summary section.
492 bool foundGlobalValSummary() { return SeenGlobalValSummary; }
Teresa Johnson403a7872015-10-04 14:33:43 +0000493
494 /// \brief Main interface to parsing a bitcode buffer.
495 /// \returns true if an error occurred.
496 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000497 ModuleSummaryIndex *I);
Teresa Johnson403a7872015-10-04 14:33:43 +0000498
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000499 /// \brief Interface for parsing a summary lazily.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000500 std::error_code
501 parseGlobalValueSummary(std::unique_ptr<DataStreamer> Streamer,
502 ModuleSummaryIndex *I, size_t SummaryOffset);
Teresa Johnson403a7872015-10-04 14:33:43 +0000503
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000504private:
Teresa Johnson403a7872015-10-04 14:33:43 +0000505 std::error_code parseModule();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000506 std::error_code parseValueSymbolTable(
507 uint64_t Offset,
508 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
Teresa Johnson403a7872015-10-04 14:33:43 +0000509 std::error_code parseEntireSummary();
510 std::error_code parseModuleStringTable();
511 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
512 std::error_code initStreamFromBuffer();
513 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
Mehdi Aminiad5741b2016-04-02 05:07:53 +0000514 GlobalValue::GUID getGUIDFromValueId(unsigned ValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000515 GlobalValueInfo *getInfoFromSummaryOffset(uint64_t Offset);
Teresa Johnson403a7872015-10-04 14:33:43 +0000516};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000517} // end anonymous namespace
Benjamin Kramercced8be2015-03-17 20:40:24 +0000518
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000519BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
520 DiagnosticSeverity Severity,
521 const Twine &Msg)
522 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
523
524void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
525
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000526static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000527 std::error_code EC, const Twine &Message) {
528 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
529 DiagnosticHandler(DI);
530 return EC;
531}
532
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000533static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000534 std::error_code EC) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000535 return error(DiagnosticHandler, EC, EC.message());
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000536}
537
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000538static std::error_code error(LLVMContext &Context, std::error_code EC,
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000539 const Twine &Message) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000540 return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC,
541 Message);
542}
543
544static std::error_code error(LLVMContext &Context, std::error_code EC) {
545 return error(Context, EC, EC.message());
546}
547
548static std::error_code error(LLVMContext &Context, const Twine &Message) {
549 return error(Context, make_error_code(BitcodeError::CorruptedBitcode),
550 Message);
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000551}
552
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000553std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
Mehdi Amini5d303282015-10-26 18:37:00 +0000554 if (!ProducerIdentification.empty()) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000555 return ::error(Context, make_error_code(E),
Filipe Cabecinhasf3e167a2015-11-03 13:48:21 +0000556 Message + " (Producer: '" + ProducerIdentification +
557 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
Mehdi Amini5d303282015-10-26 18:37:00 +0000558 }
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000559 return ::error(Context, make_error_code(E), Message);
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000560}
561
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000562std::error_code BitcodeReader::error(const Twine &Message) {
Mehdi Amini5d303282015-10-26 18:37:00 +0000563 if (!ProducerIdentification.empty()) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000564 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
Filipe Cabecinhasf3e167a2015-11-03 13:48:21 +0000565 Message + " (Producer: '" + ProducerIdentification +
566 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
Mehdi Amini5d303282015-10-26 18:37:00 +0000567 }
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000568 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
569 Message);
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000570}
571
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000572std::error_code BitcodeReader::error(BitcodeError E) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000573 return ::error(Context, make_error_code(E));
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000574}
575
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000576BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context)
577 : Context(Context), Buffer(Buffer), ValueList(Context),
Teresa Johnson61b406e2015-12-29 23:00:22 +0000578 MetadataList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000579
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000580BitcodeReader::BitcodeReader(LLVMContext &Context)
581 : Context(Context), Buffer(nullptr), ValueList(Context),
Teresa Johnson61b406e2015-12-29 23:00:22 +0000582 MetadataList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000583
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000584std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
585 if (WillMaterializeAllForwardRefs)
586 return std::error_code();
587
588 // Prevent recursion.
589 WillMaterializeAllForwardRefs = true;
590
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000591 while (!BasicBlockFwdRefQueue.empty()) {
592 Function *F = BasicBlockFwdRefQueue.front();
593 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000594 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000595 if (!BasicBlockFwdRefs.count(F))
596 // Already materialized.
597 continue;
598
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000599 // Check for a function that isn't materializable to prevent an infinite
600 // loop. When parsing a blockaddress stored in a global variable, there
601 // isn't a trivial way to check if a function will have a body without a
602 // linear search through FunctionsWithBodies, so just check it here.
603 if (!F->isMaterializable())
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000604 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000605
606 // Try to materialize F.
Rafael Espindola5a52e6d2014-10-24 22:50:48 +0000607 if (std::error_code EC = materialize(F))
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000608 return EC;
Rafael Espindolab7993462012-01-02 07:49:53 +0000609 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000610 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000611
612 // Reset state.
613 WillMaterializeAllForwardRefs = false;
614 return std::error_code();
Rafael Espindolab7993462012-01-02 07:49:53 +0000615}
616
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000617void BitcodeReader::freeState() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000618 Buffer = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000619 std::vector<Type*>().swap(TypeList);
Chris Lattner9eeada92007-05-18 04:02:46 +0000620 ValueList.clear();
Teresa Johnson61b406e2015-12-29 23:00:22 +0000621 MetadataList.clear();
David Majnemerdad0a642014-06-27 18:19:56 +0000622 std::vector<Comdat *>().swap(ComdatList);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000623
Bill Wendlinge94d8432012-12-07 23:16:57 +0000624 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattner9eeada92007-05-18 04:02:46 +0000625 std::vector<BasicBlock*>().swap(FunctionBBs);
626 std::vector<Function*>().swap(FunctionsWithBodies);
627 DeferredFunctionInfo.clear();
Manman Ren4a9b0eb2015-03-13 19:24:30 +0000628 DeferredMetadataInfo.clear();
Dan Gohman43aa8f02010-07-20 21:42:28 +0000629 MDKindMap.clear();
Benjamin Kramer736a4fc2012-09-21 14:34:31 +0000630
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +0000631 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000632 BasicBlockFwdRefQueue.clear();
Chris Lattner6694f602007-04-29 07:54:31 +0000633}
634
Chris Lattnerfee5a372007-05-04 03:30:17 +0000635//===----------------------------------------------------------------------===//
636// Helper functions to implement forward reference resolution, etc.
637//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +0000638
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000639/// Convert a string from a record into an std::string, return true on failure.
640template <typename StrTy>
641static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattnerccaa4482007-04-23 21:26:05 +0000642 StrTy &Result) {
Chris Lattnere14cb882007-05-04 19:11:41 +0000643 if (Idx > Record.size())
Chris Lattner1314b992007-04-22 06:23:29 +0000644 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000645
Chris Lattnere14cb882007-05-04 19:11:41 +0000646 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
647 Result += (char)Record[i];
Chris Lattner1314b992007-04-22 06:23:29 +0000648 return false;
649}
650
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000651static bool hasImplicitComdat(size_t Val) {
652 switch (Val) {
653 default:
654 return false;
655 case 1: // Old WeakAnyLinkage
656 case 4: // Old LinkOnceAnyLinkage
657 case 10: // Old WeakODRLinkage
658 case 11: // Old LinkOnceODRLinkage
659 return true;
660 }
661}
662
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000663static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000664 switch (Val) {
665 default: // Map unknown/new linkages to external
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000666 case 0:
667 return GlobalValue::ExternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000668 case 2:
669 return GlobalValue::AppendingLinkage;
670 case 3:
671 return GlobalValue::InternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000672 case 5:
673 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
674 case 6:
675 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
676 case 7:
677 return GlobalValue::ExternalWeakLinkage;
678 case 8:
679 return GlobalValue::CommonLinkage;
680 case 9:
681 return GlobalValue::PrivateLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000682 case 12:
683 return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000684 case 13:
685 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
686 case 14:
687 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Rafael Espindolabec6af62015-01-08 15:39:50 +0000688 case 15:
689 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000690 case 1: // Old value with implicit comdat.
691 case 16:
692 return GlobalValue::WeakAnyLinkage;
693 case 10: // Old value with implicit comdat.
694 case 17:
695 return GlobalValue::WeakODRLinkage;
696 case 4: // Old value with implicit comdat.
697 case 18:
698 return GlobalValue::LinkOnceAnyLinkage;
699 case 11: // Old value with implicit comdat.
700 case 19:
701 return GlobalValue::LinkOnceODRLinkage;
Chris Lattner1314b992007-04-22 06:23:29 +0000702 }
703}
704
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000705static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000706 switch (Val) {
707 default: // Map unknown visibilities to default.
708 case 0: return GlobalValue::DefaultVisibility;
709 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000710 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000711 }
712}
713
Nico Rieck7157bb72014-01-14 15:22:47 +0000714static GlobalValue::DLLStorageClassTypes
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000715getDecodedDLLStorageClass(unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000716 switch (Val) {
717 default: // Map unknown values to default.
718 case 0: return GlobalValue::DefaultStorageClass;
719 case 1: return GlobalValue::DLLImportStorageClass;
720 case 2: return GlobalValue::DLLExportStorageClass;
721 }
722}
723
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000724static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000725 switch (Val) {
726 case 0: return GlobalVariable::NotThreadLocal;
727 default: // Map unknown non-zero value to general dynamic.
728 case 1: return GlobalVariable::GeneralDynamicTLSModel;
729 case 2: return GlobalVariable::LocalDynamicTLSModel;
730 case 3: return GlobalVariable::InitialExecTLSModel;
731 case 4: return GlobalVariable::LocalExecTLSModel;
732 }
733}
734
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000735static int getDecodedCastOpcode(unsigned Val) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000736 switch (Val) {
737 default: return -1;
738 case bitc::CAST_TRUNC : return Instruction::Trunc;
739 case bitc::CAST_ZEXT : return Instruction::ZExt;
740 case bitc::CAST_SEXT : return Instruction::SExt;
741 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
742 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
743 case bitc::CAST_UITOFP : return Instruction::UIToFP;
744 case bitc::CAST_SITOFP : return Instruction::SIToFP;
745 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
746 case bitc::CAST_FPEXT : return Instruction::FPExt;
747 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
748 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
749 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000750 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000751 }
752}
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000753
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000754static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000755 bool IsFP = Ty->isFPOrFPVectorTy();
756 // BinOps are only valid for int/fp or vector of int/fp types
757 if (!IsFP && !Ty->isIntOrIntVectorTy())
758 return -1;
759
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000760 switch (Val) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000761 default:
762 return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000763 case bitc::BINOP_ADD:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000764 return IsFP ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000765 case bitc::BINOP_SUB:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000766 return IsFP ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000767 case bitc::BINOP_MUL:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000768 return IsFP ? Instruction::FMul : Instruction::Mul;
769 case bitc::BINOP_UDIV:
770 return IsFP ? -1 : Instruction::UDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000771 case bitc::BINOP_SDIV:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000772 return IsFP ? Instruction::FDiv : Instruction::SDiv;
773 case bitc::BINOP_UREM:
774 return IsFP ? -1 : Instruction::URem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000775 case bitc::BINOP_SREM:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000776 return IsFP ? Instruction::FRem : Instruction::SRem;
777 case bitc::BINOP_SHL:
778 return IsFP ? -1 : Instruction::Shl;
779 case bitc::BINOP_LSHR:
780 return IsFP ? -1 : Instruction::LShr;
781 case bitc::BINOP_ASHR:
782 return IsFP ? -1 : Instruction::AShr;
783 case bitc::BINOP_AND:
784 return IsFP ? -1 : Instruction::And;
785 case bitc::BINOP_OR:
786 return IsFP ? -1 : Instruction::Or;
787 case bitc::BINOP_XOR:
788 return IsFP ? -1 : Instruction::Xor;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000789 }
790}
791
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000792static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000793 switch (Val) {
794 default: return AtomicRMWInst::BAD_BINOP;
795 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
796 case bitc::RMW_ADD: return AtomicRMWInst::Add;
797 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
798 case bitc::RMW_AND: return AtomicRMWInst::And;
799 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
800 case bitc::RMW_OR: return AtomicRMWInst::Or;
801 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
802 case bitc::RMW_MAX: return AtomicRMWInst::Max;
803 case bitc::RMW_MIN: return AtomicRMWInst::Min;
804 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
805 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
806 }
807}
808
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000809static AtomicOrdering getDecodedOrdering(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000810 switch (Val) {
811 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
812 case bitc::ORDERING_UNORDERED: return Unordered;
813 case bitc::ORDERING_MONOTONIC: return Monotonic;
814 case bitc::ORDERING_ACQUIRE: return Acquire;
815 case bitc::ORDERING_RELEASE: return Release;
816 case bitc::ORDERING_ACQREL: return AcquireRelease;
817 default: // Map unknown orderings to sequentially-consistent.
818 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
819 }
820}
821
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000822static SynchronizationScope getDecodedSynchScope(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000823 switch (Val) {
824 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
825 default: // Map unknown scopes to cross-thread.
826 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
827 }
828}
829
David Majnemerdad0a642014-06-27 18:19:56 +0000830static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
831 switch (Val) {
832 default: // Map unknown selection kinds to any.
833 case bitc::COMDAT_SELECTION_KIND_ANY:
834 return Comdat::Any;
835 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
836 return Comdat::ExactMatch;
837 case bitc::COMDAT_SELECTION_KIND_LARGEST:
838 return Comdat::Largest;
839 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
840 return Comdat::NoDuplicates;
841 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
842 return Comdat::SameSize;
843 }
844}
845
James Molloy88eb5352015-07-10 12:52:00 +0000846static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
847 FastMathFlags FMF;
848 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
849 FMF.setUnsafeAlgebra();
850 if (0 != (Val & FastMathFlags::NoNaNs))
851 FMF.setNoNaNs();
852 if (0 != (Val & FastMathFlags::NoInfs))
853 FMF.setNoInfs();
854 if (0 != (Val & FastMathFlags::NoSignedZeros))
855 FMF.setNoSignedZeros();
856 if (0 != (Val & FastMathFlags::AllowReciprocal))
857 FMF.setAllowReciprocal();
858 return FMF;
859}
860
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000861static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000862 switch (Val) {
863 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
864 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
865 }
866}
867
Gabor Greiff6caff662008-05-10 08:32:32 +0000868namespace llvm {
Chris Lattner1663cca2007-04-24 05:48:56 +0000869namespace {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000870/// \brief A class for maintaining the slot number definition
871/// as a placeholder for the actual definition for forward constants defs.
872class ConstantPlaceHolder : public ConstantExpr {
873 void operator=(const ConstantPlaceHolder &) = delete;
874
875public:
876 // allocate space for exactly one operand
877 void *operator new(size_t s) { return User::operator new(s, 1); }
878 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
Gabor Greiff6caff662008-05-10 08:32:32 +0000879 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000880 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
881 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000882
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000883 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
884 static bool classof(const Value *V) {
885 return isa<ConstantExpr>(V) &&
886 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
887 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000888
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000889 /// Provide fast operand accessors
890 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
891};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000892} // end anonymous namespace
Chris Lattner1663cca2007-04-24 05:48:56 +0000893
Chris Lattner2d8cd802009-03-31 22:55:09 +0000894// FIXME: can we inherit this from ConstantExpr?
Gabor Greiff6caff662008-05-10 08:32:32 +0000895template <>
Jay Foadc8adf5f2011-01-11 15:07:38 +0000896struct OperandTraits<ConstantPlaceHolder> :
897 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greiff6caff662008-05-10 08:32:32 +0000898};
Richard Trieue3d126c2014-11-21 02:42:08 +0000899DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000900} // end namespace llvm
Gabor Greiff6caff662008-05-10 08:32:32 +0000901
David Majnemer8a1c45d2015-12-12 05:38:55 +0000902void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000903 if (Idx == size()) {
904 push_back(V);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000905 return;
Chris Lattner2d8cd802009-03-31 22:55:09 +0000906 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000907
Chris Lattner2d8cd802009-03-31 22:55:09 +0000908 if (Idx >= size())
909 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000910
Chris Lattner2d8cd802009-03-31 22:55:09 +0000911 WeakVH &OldV = ValuePtrs[Idx];
Craig Topper2617dcc2014-04-15 06:32:26 +0000912 if (!OldV) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000913 OldV = V;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000914 return;
Chris Lattner2d8cd802009-03-31 22:55:09 +0000915 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000916
Chris Lattner2d8cd802009-03-31 22:55:09 +0000917 // Handle constants and non-constants (e.g. instrs) differently for
918 // efficiency.
919 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
920 ResolveConstants.push_back(std::make_pair(PHC, Idx));
921 OldV = V;
922 } else {
923 // If there was a forward reference to this value, replace it.
924 Value *PrevVal = OldV;
925 OldV->replaceAllUsesWith(V);
926 delete PrevVal;
Gabor Greiff6caff662008-05-10 08:32:32 +0000927 }
928}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000929
Chris Lattner1663cca2007-04-24 05:48:56 +0000930Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattner229907c2011-07-18 04:54:35 +0000931 Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000932 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000933 resize(Idx + 1);
Chris Lattner1663cca2007-04-24 05:48:56 +0000934
Chris Lattner2d8cd802009-03-31 22:55:09 +0000935 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhas6a92a3f2015-05-27 01:05:40 +0000936 if (Ty != V->getType())
937 report_fatal_error("Type mismatch in constant table!");
Chris Lattner83930552007-05-01 07:01:57 +0000938 return cast<Constant>(V);
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000939 }
Chris Lattner1663cca2007-04-24 05:48:56 +0000940
941 // Create and return a placeholder, which will later be RAUW'd.
Owen Andersone9f98042009-07-07 20:18:58 +0000942 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000943 ValuePtrs[Idx] = C;
Chris Lattner1663cca2007-04-24 05:48:56 +0000944 return C;
945}
946
David Majnemer8a1c45d2015-12-12 05:38:55 +0000947Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Filipe Cabecinhasbad07792015-04-30 00:52:42 +0000948 // Bail out for a clearly invalid value. This would make us call resize(0)
949 if (Idx == UINT_MAX)
950 return nullptr;
951
Chris Lattner2d8cd802009-03-31 22:55:09 +0000952 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000953 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000954
Chris Lattner2d8cd802009-03-31 22:55:09 +0000955 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhasb435d0f2015-04-28 20:18:47 +0000956 // If the types don't match, it's invalid.
957 if (Ty && Ty != V->getType())
958 return nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000959 return V;
Chris Lattner83930552007-05-01 07:01:57 +0000960 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000961
Chris Lattner1fc27f02007-05-02 05:16:49 +0000962 // No type specified, must be invalid reference.
Craig Topper2617dcc2014-04-15 06:32:26 +0000963 if (!Ty) return nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000964
Chris Lattner83930552007-05-01 07:01:57 +0000965 // Create and return a placeholder, which will later be RAUW'd.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000966 Value *V = new Argument(Ty);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000967 ValuePtrs[Idx] = V;
Chris Lattner83930552007-05-01 07:01:57 +0000968 return V;
969}
970
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000971/// Once all constants are read, this method bulk resolves any forward
972/// references. The idea behind this is that we sometimes get constants (such
973/// as large arrays) which reference *many* forward ref constants. Replacing
974/// each of these causes a lot of thrashing when building/reuniquing the
975/// constant. Instead of doing this, we look at all the uses and rewrite all
976/// the place holders at once for any constant that uses a placeholder.
977void BitcodeReaderValueList::resolveConstantForwardRefs() {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000978 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattner74429932008-08-21 02:34:16 +0000979 // binary search.
980 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000981
Chris Lattner74429932008-08-21 02:34:16 +0000982 SmallVector<Constant*, 64> NewOps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000983
Chris Lattner74429932008-08-21 02:34:16 +0000984 while (!ResolveConstants.empty()) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000985 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattner74429932008-08-21 02:34:16 +0000986 Constant *Placeholder = ResolveConstants.back().first;
987 ResolveConstants.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000988
Chris Lattner74429932008-08-21 02:34:16 +0000989 // Loop over all users of the placeholder, updating them to reference the
990 // new value. If they reference more than one placeholder, update them all
991 // at once.
992 while (!Placeholder->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000993 auto UI = Placeholder->user_begin();
Gabor Greif2c0ab482010-07-09 16:01:21 +0000994 User *U = *UI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000995
Chris Lattner74429932008-08-21 02:34:16 +0000996 // If the using object isn't uniqued, just update the operands. This
997 // handles instructions and initializers for global variables.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000998 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattner479c5d92008-08-21 17:31:45 +0000999 UI.getUse().set(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +00001000 continue;
1001 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001002
Chris Lattner74429932008-08-21 02:34:16 +00001003 // Otherwise, we have a constant that uses the placeholder. Replace that
1004 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greif2c0ab482010-07-09 16:01:21 +00001005 Constant *UserC = cast<Constant>(U);
Chris Lattner74429932008-08-21 02:34:16 +00001006 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
1007 I != E; ++I) {
1008 Value *NewOp;
1009 if (!isa<ConstantPlaceHolder>(*I)) {
1010 // Not a placeholder reference.
1011 NewOp = *I;
1012 } else if (*I == Placeholder) {
1013 // Common case is that it just references this one placeholder.
1014 NewOp = RealVal;
1015 } else {
1016 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001017 ResolveConstantsTy::iterator It =
1018 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattner74429932008-08-21 02:34:16 +00001019 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1020 0));
1021 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner2d8cd802009-03-31 22:55:09 +00001022 NewOp = operator[](It->second);
Chris Lattner74429932008-08-21 02:34:16 +00001023 }
1024
1025 NewOps.push_back(cast<Constant>(NewOp));
1026 }
1027
1028 // Make the new constant.
1029 Constant *NewC;
1030 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad83be3612011-06-22 09:24:39 +00001031 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001032 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnercc19efa2011-06-20 04:01:31 +00001033 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001034 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner69229312011-02-15 00:14:00 +00001035 NewC = ConstantVector::get(NewOps);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001036 } else {
1037 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foad5c984e562011-04-13 13:46:01 +00001038 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001039 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001040
Chris Lattner74429932008-08-21 02:34:16 +00001041 UserC->replaceAllUsesWith(NewC);
1042 UserC->destroyConstant();
1043 NewOps.clear();
1044 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001045
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001046 // Update all ValueHandles, they should be the only users at this point.
1047 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +00001048 delete Placeholder;
1049 }
1050}
1051
Teresa Johnson61b406e2015-12-29 23:00:22 +00001052void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +00001053 if (Idx == size()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001054 push_back(MD);
Devang Patel05eb6172009-08-04 06:00:18 +00001055 return;
1056 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001057
Devang Patel05eb6172009-08-04 06:00:18 +00001058 if (Idx >= size())
1059 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001060
Teresa Johnson61b406e2015-12-29 23:00:22 +00001061 TrackingMDRef &OldMD = MetadataPtrs[Idx];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001062 if (!OldMD) {
1063 OldMD.reset(MD);
Devang Patel05eb6172009-08-04 06:00:18 +00001064 return;
1065 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001066
Devang Patel05eb6172009-08-04 06:00:18 +00001067 // If there was a forward reference to this value, replace it.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +00001068 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001069 PrevMD->replaceAllUsesWith(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001070 --NumFwdRefs;
Devang Patel05eb6172009-08-04 06:00:18 +00001071}
1072
Justin Bognerae341c62016-03-17 20:12:06 +00001073Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +00001074 if (Idx >= size())
1075 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001076
Teresa Johnson61b406e2015-12-29 23:00:22 +00001077 if (Metadata *MD = MetadataPtrs[Idx])
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001078 return MD;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001079
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001080 // Track forward refs to be resolved later.
1081 if (AnyFwdRefs) {
1082 MinFwdRef = std::min(MinFwdRef, Idx);
1083 MaxFwdRef = std::max(MaxFwdRef, Idx);
1084 } else {
1085 AnyFwdRefs = true;
1086 MinFwdRef = MaxFwdRef = Idx;
1087 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001088 ++NumFwdRefs;
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001089
1090 // Create and return a placeholder, which will later be RAUW'd.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +00001091 Metadata *MD = MDNode::getTemporary(Context, None).release();
Teresa Johnson61b406e2015-12-29 23:00:22 +00001092 MetadataPtrs[Idx].reset(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001093 return MD;
1094}
1095
Justin Bognerae341c62016-03-17 20:12:06 +00001096MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
1097 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
1098}
1099
Teresa Johnson61b406e2015-12-29 23:00:22 +00001100void BitcodeReaderMetadataList::tryToResolveCycles() {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001101 if (!AnyFwdRefs)
1102 // Nothing to do.
1103 return;
1104
1105 if (NumFwdRefs)
1106 // Still forward references... can't resolve cycles.
1107 return;
1108
1109 // Resolve any cycles.
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001110 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
Teresa Johnson61b406e2015-12-29 23:00:22 +00001111 auto &MD = MetadataPtrs[I];
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +00001112 auto *N = dyn_cast_or_null<MDNode>(MD);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +00001113 if (!N)
1114 continue;
1115
1116 assert(!N->isTemporary() && "Unexpected forward reference");
1117 N->resolveCycles();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001118 }
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001119
1120 // Make sure we return early again until there's another forward ref.
1121 AnyFwdRefs = false;
Devang Patel05eb6172009-08-04 06:00:18 +00001122}
Chris Lattner1314b992007-04-22 06:23:29 +00001123
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001124Type *BitcodeReader::getTypeByID(unsigned ID) {
1125 // The type table size is always specified correctly.
1126 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +00001127 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +00001128
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001129 if (Type *Ty = TypeList[ID])
1130 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001131
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001132 // If we have a forward reference, the only possible case is when it is to a
1133 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001134 return TypeList[ID] = createIdentifiedStructType(Context);
1135}
1136
1137StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1138 StringRef Name) {
1139 auto *Ret = StructType::create(Context, Name);
1140 IdentifiedStructTypes.push_back(Ret);
1141 return Ret;
1142}
1143
1144StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1145 auto *Ret = StructType::create(Context);
1146 IdentifiedStructTypes.push_back(Ret);
1147 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +00001148}
1149
Chris Lattnerfee5a372007-05-04 03:30:17 +00001150//===----------------------------------------------------------------------===//
1151// Functions for parsing blocks from the bitcode file
1152//===----------------------------------------------------------------------===//
1153
Bill Wendling56aeccc2013-02-04 23:32:23 +00001154
1155/// \brief This fills an AttrBuilder object with the LLVM attributes that have
1156/// been decoded from the given integer. This function must stay in sync with
1157/// 'encodeLLVMAttributesForBitcode'.
1158static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1159 uint64_t EncodedAttrs) {
1160 // FIXME: Remove in 4.0.
1161
1162 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1163 // the bits above 31 down by 11 bits.
1164 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1165 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1166 "Alignment must be a power of two.");
1167
1168 if (Alignment)
1169 B.addAlignmentAttr(Alignment);
Kostya Serebryanyd688bab2013-02-11 08:13:54 +00001170 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
Bill Wendling56aeccc2013-02-04 23:32:23 +00001171 (EncodedAttrs & 0xffff));
1172}
1173
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001174std::error_code BitcodeReader::parseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001175 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001176 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001177
Devang Patela05633e2008-09-26 22:53:05 +00001178 if (!MAttributes.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001179 return error("Invalid multiple blocks");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001180
Chris Lattnerfee5a372007-05-04 03:30:17 +00001181 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001182
Bill Wendling71173cb2013-01-27 00:36:48 +00001183 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001184
Chris Lattnerfee5a372007-05-04 03:30:17 +00001185 // Read all the records.
1186 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001187 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001188
Chris Lattner27d38752013-01-20 02:13:19 +00001189 switch (Entry.Kind) {
1190 case BitstreamEntry::SubBlock: // Handled for us already.
1191 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001192 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001193 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001194 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001195 case BitstreamEntry::Record:
1196 // The interesting case.
1197 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001198 }
Joe Abbey97b7a172013-02-06 22:14:06 +00001199
Chris Lattnerfee5a372007-05-04 03:30:17 +00001200 // Read a record.
1201 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001202 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +00001203 default: // Default behavior: ignore.
1204 break;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001205 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1206 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +00001207 if (Record.size() & 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001208 return error("Invalid record");
Chris Lattnerfee5a372007-05-04 03:30:17 +00001209
Chris Lattnerfee5a372007-05-04 03:30:17 +00001210 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +00001211 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001212 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling60011b82013-01-29 01:43:29 +00001213 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +00001214 }
Devang Patela05633e2008-09-26 22:53:05 +00001215
Bill Wendlinge94d8432012-12-07 23:16:57 +00001216 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +00001217 Attrs.clear();
1218 break;
1219 }
Bill Wendling0dc08912013-02-12 08:13:50 +00001220 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1221 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1222 Attrs.push_back(MAttributeGroups[Record[i]]);
1223
1224 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1225 Attrs.clear();
1226 break;
1227 }
Duncan Sands04eb67e2007-11-20 14:09:29 +00001228 }
Chris Lattnerfee5a372007-05-04 03:30:17 +00001229 }
1230}
1231
Reid Klecknere9f36af2013-11-12 01:31:00 +00001232// Returns Attribute::None on unrecognized codes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001233static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
Reid Klecknere9f36af2013-11-12 01:31:00 +00001234 switch (Code) {
1235 default:
1236 return Attribute::None;
1237 case bitc::ATTR_KIND_ALIGNMENT:
1238 return Attribute::Alignment;
1239 case bitc::ATTR_KIND_ALWAYS_INLINE:
1240 return Attribute::AlwaysInline;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001241 case bitc::ATTR_KIND_ARGMEMONLY:
1242 return Attribute::ArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001243 case bitc::ATTR_KIND_BUILTIN:
1244 return Attribute::Builtin;
1245 case bitc::ATTR_KIND_BY_VAL:
1246 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +00001247 case bitc::ATTR_KIND_IN_ALLOCA:
1248 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001249 case bitc::ATTR_KIND_COLD:
1250 return Attribute::Cold;
Owen Anderson85fa7d52015-05-26 23:48:40 +00001251 case bitc::ATTR_KIND_CONVERGENT:
1252 return Attribute::Convergent;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001253 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1254 return Attribute::InaccessibleMemOnly;
1255 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1256 return Attribute::InaccessibleMemOrArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001257 case bitc::ATTR_KIND_INLINE_HINT:
1258 return Attribute::InlineHint;
1259 case bitc::ATTR_KIND_IN_REG:
1260 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +00001261 case bitc::ATTR_KIND_JUMP_TABLE:
1262 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001263 case bitc::ATTR_KIND_MIN_SIZE:
1264 return Attribute::MinSize;
1265 case bitc::ATTR_KIND_NAKED:
1266 return Attribute::Naked;
1267 case bitc::ATTR_KIND_NEST:
1268 return Attribute::Nest;
1269 case bitc::ATTR_KIND_NO_ALIAS:
1270 return Attribute::NoAlias;
1271 case bitc::ATTR_KIND_NO_BUILTIN:
1272 return Attribute::NoBuiltin;
1273 case bitc::ATTR_KIND_NO_CAPTURE:
1274 return Attribute::NoCapture;
1275 case bitc::ATTR_KIND_NO_DUPLICATE:
1276 return Attribute::NoDuplicate;
1277 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1278 return Attribute::NoImplicitFloat;
1279 case bitc::ATTR_KIND_NO_INLINE:
1280 return Attribute::NoInline;
James Molloye6f87ca2015-11-06 10:32:53 +00001281 case bitc::ATTR_KIND_NO_RECURSE:
1282 return Attribute::NoRecurse;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001283 case bitc::ATTR_KIND_NON_LAZY_BIND:
1284 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001285 case bitc::ATTR_KIND_NON_NULL:
1286 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001287 case bitc::ATTR_KIND_DEREFERENCEABLE:
1288 return Attribute::Dereferenceable;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001289 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1290 return Attribute::DereferenceableOrNull;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001291 case bitc::ATTR_KIND_NO_RED_ZONE:
1292 return Attribute::NoRedZone;
1293 case bitc::ATTR_KIND_NO_RETURN:
1294 return Attribute::NoReturn;
1295 case bitc::ATTR_KIND_NO_UNWIND:
1296 return Attribute::NoUnwind;
1297 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1298 return Attribute::OptimizeForSize;
1299 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1300 return Attribute::OptimizeNone;
1301 case bitc::ATTR_KIND_READ_NONE:
1302 return Attribute::ReadNone;
1303 case bitc::ATTR_KIND_READ_ONLY:
1304 return Attribute::ReadOnly;
1305 case bitc::ATTR_KIND_RETURNED:
1306 return Attribute::Returned;
1307 case bitc::ATTR_KIND_RETURNS_TWICE:
1308 return Attribute::ReturnsTwice;
1309 case bitc::ATTR_KIND_S_EXT:
1310 return Attribute::SExt;
1311 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1312 return Attribute::StackAlignment;
1313 case bitc::ATTR_KIND_STACK_PROTECT:
1314 return Attribute::StackProtect;
1315 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1316 return Attribute::StackProtectReq;
1317 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1318 return Attribute::StackProtectStrong;
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001319 case bitc::ATTR_KIND_SAFESTACK:
1320 return Attribute::SafeStack;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001321 case bitc::ATTR_KIND_STRUCT_RET:
1322 return Attribute::StructRet;
1323 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1324 return Attribute::SanitizeAddress;
1325 case bitc::ATTR_KIND_SANITIZE_THREAD:
1326 return Attribute::SanitizeThread;
1327 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1328 return Attribute::SanitizeMemory;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001329 case bitc::ATTR_KIND_SWIFT_ERROR:
1330 return Attribute::SwiftError;
Manman Renf46262e2016-03-29 17:37:21 +00001331 case bitc::ATTR_KIND_SWIFT_SELF:
1332 return Attribute::SwiftSelf;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001333 case bitc::ATTR_KIND_UW_TABLE:
1334 return Attribute::UWTable;
1335 case bitc::ATTR_KIND_Z_EXT:
1336 return Attribute::ZExt;
1337 }
1338}
1339
JF Bastien30bf96b2015-02-22 19:32:03 +00001340std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1341 unsigned &Alignment) {
1342 // Note: Alignment in bitcode files is incremented by 1, so that zero
1343 // can be used for default alignment.
1344 if (Exponent > Value::MaxAlignmentExponent + 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001345 return error("Invalid alignment value");
JF Bastien30bf96b2015-02-22 19:32:03 +00001346 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1347 return std::error_code();
1348}
1349
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001350std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001351 Attribute::AttrKind *Kind) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001352 *Kind = getAttrFromCode(Code);
Reid Klecknere9f36af2013-11-12 01:31:00 +00001353 if (*Kind == Attribute::None)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001354 return error(BitcodeError::CorruptedBitcode,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001355 "Unknown attribute kind (" + Twine(Code) + ")");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001356 return std::error_code();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001357}
1358
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001359std::error_code BitcodeReader::parseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +00001360 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001361 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001362
1363 if (!MAttributeGroups.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001364 return error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +00001365
1366 SmallVector<uint64_t, 64> Record;
1367
1368 // Read all the records.
1369 while (1) {
1370 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1371
1372 switch (Entry.Kind) {
1373 case BitstreamEntry::SubBlock: // Handled for us already.
1374 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001375 return error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +00001376 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001377 return std::error_code();
Bill Wendlingba629332013-02-10 23:24:25 +00001378 case BitstreamEntry::Record:
1379 // The interesting case.
1380 break;
1381 }
1382
1383 // Read a record.
1384 Record.clear();
1385 switch (Stream.readRecord(Entry.ID, Record)) {
1386 default: // Default behavior: ignore.
1387 break;
1388 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1389 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001390 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001391
Bill Wendlinge46707e2013-02-11 22:32:29 +00001392 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +00001393 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1394
1395 AttrBuilder B;
1396 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1397 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001398 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001399 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001400 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001401
1402 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +00001403 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001404 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001405 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001406 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001407 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001408 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001409 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001410 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001411 else if (Kind == Attribute::Dereferenceable)
1412 B.addDereferenceableAttr(Record[++i]);
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001413 else if (Kind == Attribute::DereferenceableOrNull)
1414 B.addDereferenceableOrNullAttr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +00001415 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +00001416 assert((Record[i] == 3 || Record[i] == 4) &&
1417 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +00001418 bool HasValue = (Record[i++] == 4);
1419 SmallString<64> KindStr;
1420 SmallString<64> ValStr;
1421
1422 while (Record[i] != 0 && i != e)
1423 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001424 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001425
1426 if (HasValue) {
1427 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +00001428 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +00001429 while (Record[i] != 0 && i != e)
1430 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001431 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001432 }
1433
1434 B.addAttribute(KindStr.str(), ValStr.str());
1435 }
1436 }
1437
Bill Wendlinge46707e2013-02-11 22:32:29 +00001438 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +00001439 break;
1440 }
1441 }
1442 }
1443}
1444
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001445std::error_code BitcodeReader::parseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001446 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001447 return error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +00001448
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001449 return parseTypeTableBody();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001450}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001451
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001452std::error_code BitcodeReader::parseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +00001453 if (!TypeList.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001454 return error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +00001455
1456 SmallVector<uint64_t, 64> Record;
1457 unsigned NumRecords = 0;
1458
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001459 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +00001460
Chris Lattner1314b992007-04-22 06:23:29 +00001461 // Read all the records for this type table.
1462 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001463 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001464
Chris Lattner27d38752013-01-20 02:13:19 +00001465 switch (Entry.Kind) {
1466 case BitstreamEntry::SubBlock: // Handled for us already.
1467 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001468 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001469 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +00001470 if (NumRecords != TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001471 return error("Malformed block");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001472 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001473 case BitstreamEntry::Record:
1474 // The interesting case.
1475 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001476 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001477
Chris Lattner1314b992007-04-22 06:23:29 +00001478 // Read a record.
1479 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001480 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001481 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001482 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001483 return error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +00001484 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1485 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1486 // type list. This allows us to reserve space.
1487 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001488 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001489 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001490 continue;
Chris Lattner1314b992007-04-22 06:23:29 +00001491 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +00001492 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001493 break;
Dan Gohman518cda42011-12-17 00:04:22 +00001494 case bitc::TYPE_CODE_HALF: // HALF
1495 ResultTy = Type::getHalfTy(Context);
1496 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001497 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +00001498 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001499 break;
1500 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +00001501 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001502 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001503 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +00001504 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001505 break;
1506 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001507 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001508 break;
1509 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001510 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001511 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001512 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +00001513 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001514 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001515 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +00001516 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001517 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +00001518 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1519 ResultTy = Type::getX86_MMXTy(Context);
1520 break;
David Majnemerb611e3f2015-08-14 05:09:07 +00001521 case bitc::TYPE_CODE_TOKEN: // TOKEN
1522 ResultTy = Type::getTokenTy(Context);
1523 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001524 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
Chris Lattner1314b992007-04-22 06:23:29 +00001525 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001526 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001527
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001528 uint64_t NumBits = Record[0];
1529 if (NumBits < IntegerType::MIN_INT_BITS ||
1530 NumBits > IntegerType::MAX_INT_BITS)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001531 return error("Bitwidth for integer type out of range");
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001532 ResultTy = IntegerType::get(Context, NumBits);
Chris Lattner1314b992007-04-22 06:23:29 +00001533 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001534 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001535 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001536 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +00001537 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001538 return error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001539 unsigned AddressSpace = 0;
1540 if (Record.size() == 2)
1541 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001542 ResultTy = getTypeByID(Record[0]);
Filipe Cabecinhasd8a1bcd2015-04-29 02:27:28 +00001543 if (!ResultTy ||
1544 !PointerType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001545 return error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001546 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +00001547 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001548 }
Nuno Lopes561dae02012-05-23 15:19:39 +00001549 case bitc::TYPE_CODE_FUNCTION_OLD: {
1550 // FIXME: attrid is dead, remove it in LLVM 4.0
1551 // FUNCTION: [vararg, attrid, retty, paramty x N]
1552 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001553 return error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +00001554 SmallVector<Type*, 8> ArgTys;
1555 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1556 if (Type *T = getTypeByID(Record[i]))
1557 ArgTys.push_back(T);
1558 else
1559 break;
1560 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001561
Nuno Lopes561dae02012-05-23 15:19:39 +00001562 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001563 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001564 return error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +00001565
1566 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1567 break;
1568 }
Chad Rosier95898722011-11-03 00:14:01 +00001569 case bitc::TYPE_CODE_FUNCTION: {
1570 // FUNCTION: [vararg, retty, paramty x N]
1571 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001572 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001573 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +00001574 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001575 if (Type *T = getTypeByID(Record[i])) {
1576 if (!FunctionType::isValidArgumentType(T))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001577 return error("Invalid function argument type");
Chad Rosier95898722011-11-03 00:14:01 +00001578 ArgTys.push_back(T);
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001579 }
Chad Rosier95898722011-11-03 00:14:01 +00001580 else
1581 break;
1582 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001583
Chad Rosier95898722011-11-03 00:14:01 +00001584 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001585 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001586 return error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +00001587
1588 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1589 break;
1590 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001591 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +00001592 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001593 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001594 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001595 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1596 if (Type *T = getTypeByID(Record[i]))
1597 EltTys.push_back(T);
1598 else
1599 break;
1600 }
1601 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001602 return error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001603 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001604 break;
1605 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001606 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001607 if (convertToString(Record, 0, TypeName))
1608 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001609 continue;
1610
1611 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1612 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001613 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001614
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001615 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001616 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001617
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001618 // Check to see if this was forward referenced, if so fill in the temp.
1619 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1620 if (Res) {
1621 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001622 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001623 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001624 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001625 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001626
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001627 SmallVector<Type*, 8> EltTys;
1628 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1629 if (Type *T = getTypeByID(Record[i]))
1630 EltTys.push_back(T);
1631 else
1632 break;
1633 }
1634 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001635 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001636 Res->setBody(EltTys, Record[0]);
1637 ResultTy = Res;
1638 break;
1639 }
1640 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1641 if (Record.size() != 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001642 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001643
1644 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001645 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001646
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001647 // Check to see if this was forward referenced, if so fill in the temp.
1648 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1649 if (Res) {
1650 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001651 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001652 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001653 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001654 TypeName.clear();
1655 ResultTy = Res;
1656 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001657 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001658 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1659 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001660 return error("Invalid record");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001661 ResultTy = getTypeByID(Record[1]);
1662 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001663 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001664 ResultTy = ArrayType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001665 break;
1666 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1667 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001668 return error("Invalid record");
Filipe Cabecinhas8e421902015-06-03 00:05:30 +00001669 if (Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001670 return error("Invalid vector length");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001671 ResultTy = getTypeByID(Record[1]);
1672 if (!ResultTy || !StructType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001673 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001674 ResultTy = VectorType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001675 break;
1676 }
1677
1678 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001679 return error("Invalid TYPE table");
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001680 if (TypeList[NumRecords])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001681 return error(
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001682 "Invalid TYPE table: Only named structs can be forward referenced");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001683 assert(ResultTy && "Didn't read a type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001684 TypeList[NumRecords++] = ResultTy;
1685 }
1686}
1687
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001688std::error_code BitcodeReader::parseOperandBundleTags() {
1689 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1690 return error("Invalid record");
1691
1692 if (!BundleTags.empty())
1693 return error("Invalid multiple blocks");
1694
1695 SmallVector<uint64_t, 64> Record;
1696
1697 while (1) {
1698 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1699
1700 switch (Entry.Kind) {
1701 case BitstreamEntry::SubBlock: // Handled for us already.
1702 case BitstreamEntry::Error:
1703 return error("Malformed block");
1704 case BitstreamEntry::EndBlock:
1705 return std::error_code();
1706 case BitstreamEntry::Record:
1707 // The interesting case.
1708 break;
1709 }
1710
1711 // Tags are implicitly mapped to integers by their order.
1712
1713 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1714 return error("Invalid record");
1715
1716 // OPERAND_BUNDLE_TAG: [strchr x N]
1717 BundleTags.emplace_back();
1718 if (convertToString(Record, 0, BundleTags.back()))
1719 return error("Invalid record");
1720 Record.clear();
1721 }
1722}
1723
Teresa Johnsonff642b92015-09-17 20:12:00 +00001724/// Associate a value with its name from the given index in the provided record.
1725ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1726 unsigned NameIndex, Triple &TT) {
1727 SmallString<128> ValueName;
1728 if (convertToString(Record, NameIndex, ValueName))
1729 return error("Invalid record");
1730 unsigned ValueID = Record[0];
1731 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1732 return error("Invalid record");
1733 Value *V = ValueList[ValueID];
1734
Filipe Cabecinhasa2b0ac42015-11-04 14:53:36 +00001735 StringRef NameStr(ValueName.data(), ValueName.size());
1736 if (NameStr.find_first_of(0) != StringRef::npos)
1737 return error("Invalid value name");
1738 V->setName(NameStr);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001739 auto *GO = dyn_cast<GlobalObject>(V);
1740 if (GO) {
1741 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1742 if (TT.isOSBinFormatMachO())
1743 GO->setComdat(nullptr);
1744 else
1745 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1746 }
1747 }
1748 return V;
1749}
1750
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001751/// Helper to note and return the current location, and jump to the given
1752/// offset.
1753static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1754 BitstreamCursor &Stream) {
1755 // Save the current parsing location so we can jump back at the end
1756 // of the VST read.
1757 uint64_t CurrentBit = Stream.GetCurrentBitNo();
1758 Stream.JumpToBit(Offset * 32);
1759#ifndef NDEBUG
1760 // Do some checking if we are in debug mode.
1761 BitstreamEntry Entry = Stream.advance();
1762 assert(Entry.Kind == BitstreamEntry::SubBlock);
1763 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1764#else
1765 // In NDEBUG mode ignore the output so we don't get an unused variable
1766 // warning.
1767 Stream.advance();
1768#endif
1769 return CurrentBit;
1770}
1771
Teresa Johnsonff642b92015-09-17 20:12:00 +00001772/// Parse the value symbol table at either the current parsing location or
1773/// at the given bit offset if provided.
Peter Collingbourne128a9762015-10-27 23:01:25 +00001774std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001775 uint64_t CurrentBit;
1776 // Pass in the Offset to distinguish between calling for the module-level
1777 // VST (where we want to jump to the VST offset) and the function-level
1778 // VST (where we don't).
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001779 if (Offset > 0)
1780 CurrentBit = jumpToValueSymbolTable(Offset, Stream);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001781
1782 // Compute the delta between the bitcode indices in the VST (the word offset
1783 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1784 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1785 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1786 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1787 // just before entering the VST subblock because: 1) the EnterSubBlock
1788 // changes the AbbrevID width; 2) the VST block is nested within the same
1789 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1790 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1791 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1792 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1793 unsigned FuncBitcodeOffsetDelta =
1794 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1795
Chris Lattner982ec1e2007-05-05 00:17:00 +00001796 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001797 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001798
1799 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001800
David Majnemer3087b222015-01-20 05:58:07 +00001801 Triple TT(TheModule->getTargetTriple());
1802
Chris Lattnerccaa4482007-04-23 21:26:05 +00001803 // Read all the records for this value table.
1804 SmallString<128> ValueName;
1805 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001806 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001807
Chris Lattner27d38752013-01-20 02:13:19 +00001808 switch (Entry.Kind) {
1809 case BitstreamEntry::SubBlock: // Handled for us already.
1810 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001811 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001812 case BitstreamEntry::EndBlock:
Teresa Johnsonff642b92015-09-17 20:12:00 +00001813 if (Offset > 0)
1814 Stream.JumpToBit(CurrentBit);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001815 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001816 case BitstreamEntry::Record:
1817 // The interesting case.
1818 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001819 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001820
Chris Lattnerccaa4482007-04-23 21:26:05 +00001821 // Read a record.
1822 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001823 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001824 default: // Default behavior: unknown type.
1825 break;
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001826 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
Teresa Johnsonff642b92015-09-17 20:12:00 +00001827 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1828 if (std::error_code EC = ValOrErr.getError())
1829 return EC;
1830 ValOrErr.get();
1831 break;
1832 }
1833 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001834 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonff642b92015-09-17 20:12:00 +00001835 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1836 if (std::error_code EC = ValOrErr.getError())
1837 return EC;
1838 Value *V = ValOrErr.get();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001839
Teresa Johnsonff642b92015-09-17 20:12:00 +00001840 auto *GO = dyn_cast<GlobalObject>(V);
1841 if (!GO) {
1842 // If this is an alias, need to get the actual Function object
1843 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1844 auto *GA = dyn_cast<GlobalAlias>(V);
1845 if (GA)
1846 GO = GA->getBaseObject();
1847 assert(GO);
Rafael Espindola12ca34f2015-01-19 15:16:06 +00001848 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001849
1850 uint64_t FuncWordOffset = Record[1];
1851 Function *F = dyn_cast<Function>(GO);
1852 assert(F);
1853 uint64_t FuncBitOffset = FuncWordOffset * 32;
1854 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
Teresa Johnson1493ad92015-10-10 14:18:36 +00001855 // Set the LastFunctionBlockBit to point to the last function block.
Teresa Johnsonff642b92015-09-17 20:12:00 +00001856 // Later when parsing is resumed after function materialization,
1857 // we can simply skip that last function block.
Teresa Johnson1493ad92015-10-10 14:18:36 +00001858 if (FuncBitOffset > LastFunctionBlockBit)
1859 LastFunctionBlockBit = FuncBitOffset;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001860 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00001861 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00001862 case bitc::VST_CODE_BBENTRY: {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001863 if (convertToString(Record, 1, ValueName))
1864 return error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00001865 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001866 if (!BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001867 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001868
Daniel Dunbard786b512009-07-26 00:34:27 +00001869 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00001870 ValueName.clear();
1871 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001872 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00001873 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001874 }
1875}
1876
Teresa Johnson12545072015-11-15 02:00:09 +00001877/// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1878std::error_code
1879BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
1880 if (Record.size() < 2)
1881 return error("Invalid record");
1882
1883 unsigned Kind = Record[0];
1884 SmallString<8> Name(Record.begin() + 1, Record.end());
1885
1886 unsigned NewKind = TheModule->getMDKindID(Name.str());
1887 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1888 return error("Conflicting METADATA_KIND records");
1889 return std::error_code();
1890}
1891
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001892static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1893
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001894std::error_code BitcodeReader::parseMetadataStrings(ArrayRef<uint64_t> Record,
1895 StringRef Blob,
1896 unsigned &NextMetadataNo) {
1897 // All the MDStrings in the block are emitted together in a single
1898 // record. The strings are concatenated and stored in a blob along with
1899 // their sizes.
1900 if (Record.size() != 2)
1901 return error("Invalid record: metadata strings layout");
1902
1903 unsigned NumStrings = Record[0];
1904 unsigned StringsOffset = Record[1];
1905 if (!NumStrings)
1906 return error("Invalid record: metadata strings with no strings");
Duncan P. N. Exon Smithbb7ce3b2016-03-29 05:25:17 +00001907 if (StringsOffset > Blob.size())
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001908 return error("Invalid record: metadata strings corrupt offset");
1909
1910 StringRef Lengths = Blob.slice(0, StringsOffset);
1911 SimpleBitstreamCursor R(*StreamFile);
1912 R.jumpToPointer(Lengths.begin());
1913
1914 // Ensure that Blob doesn't get invalidated, even if this is reading from
1915 // a StreamingMemoryObject with corrupt data.
1916 R.setArtificialByteLimit(R.getCurrentByteNo() + StringsOffset);
1917
1918 StringRef Strings = Blob.drop_front(StringsOffset);
1919 do {
1920 if (R.AtEndOfStream())
1921 return error("Invalid record: metadata strings bad length");
1922
1923 unsigned Size = R.ReadVBR(6);
1924 if (Strings.size() < Size)
1925 return error("Invalid record: metadata strings truncated chars");
1926
1927 MetadataList.assignValue(MDString::get(Context, Strings.slice(0, Size)),
1928 NextMetadataNo++);
1929 Strings = Strings.drop_front(Size);
1930 } while (--NumStrings);
1931
1932 return std::error_code();
1933}
1934
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00001935/// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
1936/// module level metadata.
1937std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00001938 IsMetadataMaterialized = true;
Teresa Johnson61b406e2015-12-29 23:00:22 +00001939 unsigned NextMetadataNo = MetadataList.size();
Devang Patel7428d8a2009-07-22 17:43:22 +00001940
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00001941 if (!ModuleLevel && MetadataList.hasFwdRefs())
1942 return error("Invalid metadata: fwd refs into function blocks");
1943
Devang Patel7428d8a2009-07-22 17:43:22 +00001944 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001945 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001946
Devang Patel7428d8a2009-07-22 17:43:22 +00001947 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001948
Teresa Johnson61b406e2015-12-29 23:00:22 +00001949 auto getMD = [&](unsigned ID) -> Metadata * {
Justin Bognerae341c62016-03-17 20:12:06 +00001950 return MetadataList.getMetadataFwdRef(ID);
Teresa Johnson61b406e2015-12-29 23:00:22 +00001951 };
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001952 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1953 if (ID)
1954 return getMD(ID - 1);
1955 return nullptr;
1956 };
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001957 auto getMDString = [&](unsigned ID) -> MDString *{
1958 // This requires that the ID is not really a forward reference. In
1959 // particular, the MDString must already have been resolved.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001960 return cast_or_null<MDString>(getMDOrNull(ID));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001961 };
1962
1963#define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1964 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1965
Devang Patel7428d8a2009-07-22 17:43:22 +00001966 // Read all the records.
1967 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001968 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001969
Chris Lattner27d38752013-01-20 02:13:19 +00001970 switch (Entry.Kind) {
1971 case BitstreamEntry::SubBlock: // Handled for us already.
1972 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001973 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001974 case BitstreamEntry::EndBlock:
Teresa Johnson61b406e2015-12-29 23:00:22 +00001975 MetadataList.tryToResolveCycles();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001976 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001977 case BitstreamEntry::Record:
1978 // The interesting case.
1979 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00001980 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001981
Devang Patel7428d8a2009-07-22 17:43:22 +00001982 // Read a record.
1983 Record.clear();
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001984 StringRef Blob;
1985 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001986 bool IsDistinct = false;
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00001987 switch (Code) {
Devang Patel7428d8a2009-07-22 17:43:22 +00001988 default: // Default behavior: ignore.
1989 break;
Devang Patel27c87ff2009-07-29 22:34:41 +00001990 case bitc::METADATA_NAME: {
Chris Lattner8d140532013-01-20 02:54:05 +00001991 // Read name of the named metadata.
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001992 SmallString<8> Name(Record.begin(), Record.end());
Devang Patel27c87ff2009-07-29 22:34:41 +00001993 Record.clear();
1994 Code = Stream.ReadCode();
1995
Chris Lattner27d38752013-01-20 02:13:19 +00001996 unsigned NextBitCode = Stream.readRecord(Code, Record);
Filipe Cabecinhas14e68672015-05-30 00:17:20 +00001997 if (NextBitCode != bitc::METADATA_NAMED_NODE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001998 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
Devang Patel27c87ff2009-07-29 22:34:41 +00001999
2000 // Read named metadata elements.
2001 unsigned Size = Record.size();
Dan Gohman2637cc12010-07-21 23:38:33 +00002002 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patel27c87ff2009-07-29 22:34:41 +00002003 for (unsigned i = 0; i != Size; ++i) {
Justin Bognerae341c62016-03-17 20:12:06 +00002004 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002005 if (!MD)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002006 return error("Invalid record");
Dan Gohman2637cc12010-07-21 23:38:33 +00002007 NMD->addOperand(MD);
Devang Patel27c87ff2009-07-29 22:34:41 +00002008 }
Devang Patel27c87ff2009-07-29 22:34:41 +00002009 break;
2010 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00002011 case bitc::METADATA_OLD_FN_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00002012 // FIXME: Remove in 4.0.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002013 // This is a LocalAsMetadata record, the only type of function-local
2014 // metadata.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002015 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002016 return error("Invalid record");
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002017
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002018 // If this isn't a LocalAsMetadata record, we're dropping it. This used
2019 // to be legal, but there's no upgrade path.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002020 auto dropRecord = [&] {
Teresa Johnson61b406e2015-12-29 23:00:22 +00002021 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002022 };
2023 if (Record.size() != 2) {
2024 dropRecord();
2025 break;
2026 }
2027
2028 Type *Ty = getTypeByID(Record[0]);
2029 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
2030 dropRecord();
2031 break;
2032 }
2033
Teresa Johnson61b406e2015-12-29 23:00:22 +00002034 MetadataList.assignValue(
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002035 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002036 NextMetadataNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002037 break;
2038 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00002039 case bitc::METADATA_OLD_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00002040 // FIXME: Remove in 4.0.
Dan Gohman1e0213a2010-07-13 19:33:27 +00002041 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002042 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002043
Devang Patele059ba6e2009-07-23 01:07:34 +00002044 unsigned Size = Record.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002045 SmallVector<Metadata *, 8> Elts;
Devang Patele059ba6e2009-07-23 01:07:34 +00002046 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00002047 Type *Ty = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002048 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002049 return error("Invalid record");
Chris Lattnerfdd87902009-10-05 05:54:46 +00002050 if (Ty->isMetadataTy())
Justin Bognerae341c62016-03-17 20:12:06 +00002051 Elts.push_back(MetadataList.getMetadataFwdRef(Record[i + 1]));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002052 else if (!Ty->isVoidTy()) {
2053 auto *MD =
2054 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2055 assert(isa<ConstantAsMetadata>(MD) &&
2056 "Expected non-function-local metadata");
2057 Elts.push_back(MD);
2058 } else
Craig Topper2617dcc2014-04-15 06:32:26 +00002059 Elts.push_back(nullptr);
Devang Patele059ba6e2009-07-23 01:07:34 +00002060 }
Teresa Johnson61b406e2015-12-29 23:00:22 +00002061 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++);
Devang Patele059ba6e2009-07-23 01:07:34 +00002062 break;
2063 }
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002064 case bitc::METADATA_VALUE: {
2065 if (Record.size() != 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002066 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002067
2068 Type *Ty = getTypeByID(Record[0]);
2069 if (Ty->isMetadataTy() || Ty->isVoidTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002070 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002071
Teresa Johnson61b406e2015-12-29 23:00:22 +00002072 MetadataList.assignValue(
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002073 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002074 NextMetadataNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002075 break;
2076 }
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00002077 case bitc::METADATA_DISTINCT_NODE:
2078 IsDistinct = true;
2079 // fallthrough...
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002080 case bitc::METADATA_NODE: {
2081 SmallVector<Metadata *, 8> Elts;
2082 Elts.reserve(Record.size());
2083 for (unsigned ID : Record)
Justin Bognerae341c62016-03-17 20:12:06 +00002084 Elts.push_back(ID ? MetadataList.getMetadataFwdRef(ID - 1) : nullptr);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002085 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2086 : MDNode::get(Context, Elts),
2087 NextMetadataNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002088 break;
2089 }
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002090 case bitc::METADATA_LOCATION: {
2091 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002092 return error("Invalid record");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002093
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002094 unsigned Line = Record[1];
2095 unsigned Column = Record[2];
Justin Bognerae341c62016-03-17 20:12:06 +00002096 MDNode *Scope = MetadataList.getMDNodeFwdRefOrNull(Record[3]);
2097 if (!Scope)
2098 return error("Invalid record");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002099 Metadata *InlinedAt =
Justin Bognerae341c62016-03-17 20:12:06 +00002100 Record[4] ? MetadataList.getMetadataFwdRef(Record[4] - 1) : nullptr;
Teresa Johnson61b406e2015-12-29 23:00:22 +00002101 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002102 GET_OR_DISTINCT(DILocation, Record[0],
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00002103 (Context, Line, Column, Scope, InlinedAt)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002104 NextMetadataNo++);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002105 break;
2106 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002107 case bitc::METADATA_GENERIC_DEBUG: {
2108 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002109 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002110
2111 unsigned Tag = Record[1];
2112 unsigned Version = Record[2];
2113
2114 if (Tag >= 1u << 16 || Version != 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002115 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002116
2117 auto *Header = getMDString(Record[3]);
2118 SmallVector<Metadata *, 8> DwarfOps;
2119 for (unsigned I = 4, E = Record.size(); I != E; ++I)
Justin Bognerae341c62016-03-17 20:12:06 +00002120 DwarfOps.push_back(Record[I]
2121 ? MetadataList.getMetadataFwdRef(Record[I] - 1)
2122 : nullptr);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002123 MetadataList.assignValue(
2124 GET_OR_DISTINCT(GenericDINode, Record[0],
2125 (Context, Tag, Header, DwarfOps)),
2126 NextMetadataNo++);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002127 break;
2128 }
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002129 case bitc::METADATA_SUBRANGE: {
2130 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002131 return error("Invalid record");
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002132
Teresa Johnson61b406e2015-12-29 23:00:22 +00002133 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002134 GET_OR_DISTINCT(DISubrange, Record[0],
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002135 (Context, Record[1], unrotateSign(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002136 NextMetadataNo++);
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002137 break;
2138 }
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002139 case bitc::METADATA_ENUMERATOR: {
2140 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002141 return error("Invalid record");
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002142
Teresa Johnson61b406e2015-12-29 23:00:22 +00002143 MetadataList.assignValue(
2144 GET_OR_DISTINCT(
2145 DIEnumerator, Record[0],
2146 (Context, unrotateSign(Record[1]), getMDString(Record[2]))),
2147 NextMetadataNo++);
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002148 break;
2149 }
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002150 case bitc::METADATA_BASIC_TYPE: {
2151 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002152 return error("Invalid record");
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002153
Teresa Johnson61b406e2015-12-29 23:00:22 +00002154 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002155 GET_OR_DISTINCT(DIBasicType, Record[0],
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002156 (Context, Record[1], getMDString(Record[2]),
2157 Record[3], Record[4], Record[5])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002158 NextMetadataNo++);
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002159 break;
2160 }
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002161 case bitc::METADATA_DERIVED_TYPE: {
2162 if (Record.size() != 12)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002163 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002164
Teresa Johnson61b406e2015-12-29 23:00:22 +00002165 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002166 GET_OR_DISTINCT(DIDerivedType, Record[0],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002167 (Context, Record[1], getMDString(Record[2]),
2168 getMDOrNull(Record[3]), Record[4],
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00002169 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2170 Record[7], Record[8], Record[9], Record[10],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002171 getMDOrNull(Record[11]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002172 NextMetadataNo++);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002173 break;
2174 }
2175 case bitc::METADATA_COMPOSITE_TYPE: {
2176 if (Record.size() != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002177 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002178
Teresa Johnson61b406e2015-12-29 23:00:22 +00002179 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002180 GET_OR_DISTINCT(DICompositeType, Record[0],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002181 (Context, Record[1], getMDString(Record[2]),
2182 getMDOrNull(Record[3]), Record[4],
2183 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2184 Record[7], Record[8], Record[9], Record[10],
2185 getMDOrNull(Record[11]), Record[12],
2186 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2187 getMDString(Record[15]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002188 NextMetadataNo++);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002189 break;
2190 }
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002191 case bitc::METADATA_SUBROUTINE_TYPE: {
2192 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002193 return error("Invalid record");
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002194
Teresa Johnson61b406e2015-12-29 23:00:22 +00002195 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002196 GET_OR_DISTINCT(DISubroutineType, Record[0],
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002197 (Context, Record[1], getMDOrNull(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002198 NextMetadataNo++);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002199 break;
2200 }
Adrian Prantlab1243f2015-06-29 23:03:47 +00002201
2202 case bitc::METADATA_MODULE: {
2203 if (Record.size() != 6)
2204 return error("Invalid record");
2205
Teresa Johnson61b406e2015-12-29 23:00:22 +00002206 MetadataList.assignValue(
Adrian Prantlab1243f2015-06-29 23:03:47 +00002207 GET_OR_DISTINCT(DIModule, Record[0],
2208 (Context, getMDOrNull(Record[1]),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002209 getMDString(Record[2]), getMDString(Record[3]),
2210 getMDString(Record[4]), getMDString(Record[5]))),
2211 NextMetadataNo++);
Adrian Prantlab1243f2015-06-29 23:03:47 +00002212 break;
2213 }
2214
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002215 case bitc::METADATA_FILE: {
2216 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002217 return error("Invalid record");
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002218
Teresa Johnson61b406e2015-12-29 23:00:22 +00002219 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002220 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002221 getMDString(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002222 NextMetadataNo++);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002223 break;
2224 }
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002225 case bitc::METADATA_COMPILE_UNIT: {
Amjad Abouda9bcf162015-12-10 12:56:35 +00002226 if (Record.size() < 14 || Record.size() > 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002227 return error("Invalid record");
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002228
Amjad Abouda9bcf162015-12-10 12:56:35 +00002229 // Ignore Record[0], which indicates whether this compile unit is
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00002230 // distinct. It's always distinct.
Teresa Johnson61b406e2015-12-29 23:00:22 +00002231 MetadataList.assignValue(
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00002232 DICompileUnit::getDistinct(
2233 Context, Record[1], getMDOrNull(Record[2]),
2234 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2235 Record[6], getMDString(Record[7]), Record[8],
2236 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2237 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
Amjad Abouda9bcf162015-12-10 12:56:35 +00002238 getMDOrNull(Record[13]),
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00002239 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
Amjad Abouda9bcf162015-12-10 12:56:35 +00002240 Record.size() <= 14 ? 0 : Record[14]),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002241 NextMetadataNo++);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002242 break;
2243 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002244 case bitc::METADATA_SUBPROGRAM: {
Peter Collingbourned4bff302015-11-05 22:03:56 +00002245 if (Record.size() != 18 && Record.size() != 19)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002246 return error("Invalid record");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002247
Peter Collingbourned4bff302015-11-05 22:03:56 +00002248 bool HasFn = Record.size() == 19;
2249 DISubprogram *SP = GET_OR_DISTINCT(
2250 DISubprogram,
2251 Record[0] || Record[8], // All definitions should be distinct.
2252 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2253 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2254 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2255 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2256 Record[14], getMDOrNull(Record[15 + HasFn]),
2257 getMDOrNull(Record[16 + HasFn]), getMDOrNull(Record[17 + HasFn])));
Teresa Johnson61b406e2015-12-29 23:00:22 +00002258 MetadataList.assignValue(SP, NextMetadataNo++);
Peter Collingbourned4bff302015-11-05 22:03:56 +00002259
2260 // Upgrade sp->function mapping to function->sp mapping.
2261 if (HasFn && Record[15]) {
2262 if (auto *CMD = dyn_cast<ConstantAsMetadata>(getMDOrNull(Record[15])))
2263 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2264 if (F->isMaterializable())
2265 // Defer until materialized; unmaterialized functions may not have
2266 // metadata.
2267 FunctionsWithSPs[F] = SP;
2268 else if (!F->empty())
2269 F->setSubprogram(SP);
2270 }
2271 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002272 break;
2273 }
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002274 case bitc::METADATA_LEXICAL_BLOCK: {
2275 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002276 return error("Invalid record");
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002277
Teresa Johnson61b406e2015-12-29 23:00:22 +00002278 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002279 GET_OR_DISTINCT(DILexicalBlock, Record[0],
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002280 (Context, getMDOrNull(Record[1]),
2281 getMDOrNull(Record[2]), Record[3], Record[4])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002282 NextMetadataNo++);
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002283 break;
2284 }
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002285 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2286 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002287 return error("Invalid record");
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002288
Teresa Johnson61b406e2015-12-29 23:00:22 +00002289 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002290 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002291 (Context, getMDOrNull(Record[1]),
2292 getMDOrNull(Record[2]), Record[3])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002293 NextMetadataNo++);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002294 break;
2295 }
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002296 case bitc::METADATA_NAMESPACE: {
2297 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002298 return error("Invalid record");
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002299
Teresa Johnson61b406e2015-12-29 23:00:22 +00002300 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002301 GET_OR_DISTINCT(DINamespace, Record[0],
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002302 (Context, getMDOrNull(Record[1]),
2303 getMDOrNull(Record[2]), getMDString(Record[3]),
2304 Record[4])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002305 NextMetadataNo++);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002306 break;
2307 }
Amjad Abouda9bcf162015-12-10 12:56:35 +00002308 case bitc::METADATA_MACRO: {
2309 if (Record.size() != 5)
2310 return error("Invalid record");
2311
Teresa Johnson61b406e2015-12-29 23:00:22 +00002312 MetadataList.assignValue(
Amjad Abouda9bcf162015-12-10 12:56:35 +00002313 GET_OR_DISTINCT(DIMacro, Record[0],
2314 (Context, Record[1], Record[2],
2315 getMDString(Record[3]), getMDString(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002316 NextMetadataNo++);
Amjad Abouda9bcf162015-12-10 12:56:35 +00002317 break;
2318 }
2319 case bitc::METADATA_MACRO_FILE: {
2320 if (Record.size() != 5)
2321 return error("Invalid record");
2322
Teresa Johnson61b406e2015-12-29 23:00:22 +00002323 MetadataList.assignValue(
Amjad Abouda9bcf162015-12-10 12:56:35 +00002324 GET_OR_DISTINCT(DIMacroFile, Record[0],
2325 (Context, Record[1], Record[2],
2326 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002327 NextMetadataNo++);
Amjad Abouda9bcf162015-12-10 12:56:35 +00002328 break;
2329 }
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002330 case bitc::METADATA_TEMPLATE_TYPE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002331 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002332 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002333
Teresa Johnson61b406e2015-12-29 23:00:22 +00002334 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2335 Record[0],
2336 (Context, getMDString(Record[1]),
2337 getMDOrNull(Record[2]))),
2338 NextMetadataNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002339 break;
2340 }
2341 case bitc::METADATA_TEMPLATE_VALUE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002342 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002343 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002344
Teresa Johnson61b406e2015-12-29 23:00:22 +00002345 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002346 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002347 (Context, Record[1], getMDString(Record[2]),
2348 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002349 NextMetadataNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002350 break;
2351 }
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002352 case bitc::METADATA_GLOBAL_VAR: {
2353 if (Record.size() != 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002354 return error("Invalid record");
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002355
Teresa Johnson61b406e2015-12-29 23:00:22 +00002356 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002357 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002358 (Context, getMDOrNull(Record[1]),
2359 getMDString(Record[2]), getMDString(Record[3]),
2360 getMDOrNull(Record[4]), Record[5],
2361 getMDOrNull(Record[6]), Record[7], Record[8],
2362 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002363 NextMetadataNo++);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002364 break;
2365 }
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002366 case bitc::METADATA_LOCAL_VAR: {
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00002367 // 10th field is for the obseleted 'inlinedAt:' field.
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002368 if (Record.size() < 8 || Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002369 return error("Invalid record");
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002370
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002371 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2372 // DW_TAG_arg_variable.
2373 bool HasTag = Record.size() > 8;
Teresa Johnson61b406e2015-12-29 23:00:22 +00002374 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002375 GET_OR_DISTINCT(DILocalVariable, Record[0],
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002376 (Context, getMDOrNull(Record[1 + HasTag]),
2377 getMDString(Record[2 + HasTag]),
2378 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2379 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2380 Record[7 + HasTag])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002381 NextMetadataNo++);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002382 break;
2383 }
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002384 case bitc::METADATA_EXPRESSION: {
2385 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002386 return error("Invalid record");
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002387
Teresa Johnson61b406e2015-12-29 23:00:22 +00002388 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002389 GET_OR_DISTINCT(DIExpression, Record[0],
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002390 (Context, makeArrayRef(Record).slice(1))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002391 NextMetadataNo++);
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002392 break;
2393 }
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002394 case bitc::METADATA_OBJC_PROPERTY: {
2395 if (Record.size() != 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002396 return error("Invalid record");
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002397
Teresa Johnson61b406e2015-12-29 23:00:22 +00002398 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002399 GET_OR_DISTINCT(DIObjCProperty, Record[0],
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002400 (Context, getMDString(Record[1]),
2401 getMDOrNull(Record[2]), Record[3],
2402 getMDString(Record[4]), getMDString(Record[5]),
2403 Record[6], getMDOrNull(Record[7]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002404 NextMetadataNo++);
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002405 break;
2406 }
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002407 case bitc::METADATA_IMPORTED_ENTITY: {
2408 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002409 return error("Invalid record");
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002410
Teresa Johnson61b406e2015-12-29 23:00:22 +00002411 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002412 GET_OR_DISTINCT(DIImportedEntity, Record[0],
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002413 (Context, Record[1], getMDOrNull(Record[2]),
2414 getMDOrNull(Record[3]), Record[4],
2415 getMDString(Record[5]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002416 NextMetadataNo++);
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002417 break;
2418 }
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002419 case bitc::METADATA_STRING_OLD: {
Eli Bendersky5d5e18d2014-06-25 15:41:00 +00002420 std::string String(Record.begin(), Record.end());
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00002421
2422 // Test for upgrading !llvm.loop.
2423 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2424
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002425 Metadata *MD = MDString::get(Context, String);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002426 MetadataList.assignValue(MD, NextMetadataNo++);
Devang Patel7428d8a2009-07-22 17:43:22 +00002427 break;
2428 }
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002429 case bitc::METADATA_STRINGS:
2430 if (std::error_code EC =
2431 parseMetadataStrings(Record, Blob, NextMetadataNo))
2432 return EC;
2433 break;
Devang Patelaf206b82009-09-18 19:26:43 +00002434 case bitc::METADATA_KIND: {
Teresa Johnson12545072015-11-15 02:00:09 +00002435 // Support older bitcode files that had METADATA_KIND records in a
2436 // block with METADATA_BLOCK_ID.
2437 if (std::error_code EC = parseMetadataKindRecord(Record))
2438 return EC;
Devang Patelaf206b82009-09-18 19:26:43 +00002439 break;
2440 }
Devang Patel7428d8a2009-07-22 17:43:22 +00002441 }
2442 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002443#undef GET_OR_DISTINCT
Devang Patel7428d8a2009-07-22 17:43:22 +00002444}
2445
Teresa Johnson12545072015-11-15 02:00:09 +00002446/// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2447std::error_code BitcodeReader::parseMetadataKinds() {
2448 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2449 return error("Invalid record");
2450
2451 SmallVector<uint64_t, 64> Record;
2452
2453 // Read all the records.
2454 while (1) {
2455 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2456
2457 switch (Entry.Kind) {
2458 case BitstreamEntry::SubBlock: // Handled for us already.
2459 case BitstreamEntry::Error:
2460 return error("Malformed block");
2461 case BitstreamEntry::EndBlock:
2462 return std::error_code();
2463 case BitstreamEntry::Record:
2464 // The interesting case.
2465 break;
2466 }
2467
2468 // Read a record.
2469 Record.clear();
2470 unsigned Code = Stream.readRecord(Entry.ID, Record);
2471 switch (Code) {
2472 default: // Default behavior: ignore.
2473 break;
2474 case bitc::METADATA_KIND: {
2475 if (std::error_code EC = parseMetadataKindRecord(Record))
2476 return EC;
2477 break;
2478 }
2479 }
2480 }
2481}
2482
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002483/// Decode a signed value stored with the sign bit in the LSB for dense VBR
2484/// encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002485uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00002486 if ((V & 1) == 0)
2487 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002488 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00002489 return -(V >> 1);
2490 // There is no such thing as -0 with integers. "-0" really means MININT.
2491 return 1ULL << 63;
2492}
2493
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002494/// Resolve all of the initializers for global values and aliases that we can.
2495std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00002496 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2497 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002498 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002499 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
David Majnemer7fddecc2015-06-17 20:52:32 +00002500 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002501
Chris Lattner44c17072007-04-26 02:46:40 +00002502 GlobalInitWorklist.swap(GlobalInits);
2503 AliasInitWorklist.swap(AliasInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002504 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002505 FunctionPrologueWorklist.swap(FunctionPrologues);
David Majnemer7fddecc2015-06-17 20:52:32 +00002506 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
Chris Lattner44c17072007-04-26 02:46:40 +00002507
2508 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00002509 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002510 if (ValID >= ValueList.size()) {
2511 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00002512 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002513 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002514 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00002515 GlobalInitWorklist.back().first->setInitializer(C);
2516 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002517 return error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00002518 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002519 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002520 }
2521
2522 while (!AliasInitWorklist.empty()) {
2523 unsigned ValID = AliasInitWorklist.back().second;
2524 if (ValID >= ValueList.size()) {
2525 AliasInits.push_back(AliasInitWorklist.back());
2526 } else {
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002527 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2528 if (!C)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002529 return error("Expected a constant");
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002530 GlobalAlias *Alias = AliasInitWorklist.back().first;
2531 if (C->getType() != Alias->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002532 return error("Alias and aliasee types don't match");
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002533 Alias->setAliasee(C);
Chris Lattner44c17072007-04-26 02:46:40 +00002534 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002535 AliasInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002536 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002537
2538 while (!FunctionPrefixWorklist.empty()) {
2539 unsigned ValID = FunctionPrefixWorklist.back().second;
2540 if (ValID >= ValueList.size()) {
2541 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2542 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002543 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002544 FunctionPrefixWorklist.back().first->setPrefixData(C);
2545 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002546 return error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002547 }
2548 FunctionPrefixWorklist.pop_back();
2549 }
2550
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002551 while (!FunctionPrologueWorklist.empty()) {
2552 unsigned ValID = FunctionPrologueWorklist.back().second;
2553 if (ValID >= ValueList.size()) {
2554 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2555 } else {
2556 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2557 FunctionPrologueWorklist.back().first->setPrologueData(C);
2558 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002559 return error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002560 }
2561 FunctionPrologueWorklist.pop_back();
2562 }
2563
David Majnemer7fddecc2015-06-17 20:52:32 +00002564 while (!FunctionPersonalityFnWorklist.empty()) {
2565 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2566 if (ValID >= ValueList.size()) {
2567 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2568 } else {
2569 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2570 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2571 else
2572 return error("Expected a constant");
2573 }
2574 FunctionPersonalityFnWorklist.pop_back();
2575 }
2576
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002577 return std::error_code();
Chris Lattner44c17072007-04-26 02:46:40 +00002578}
2579
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002580static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002581 SmallVector<uint64_t, 8> Words(Vals.size());
2582 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00002583 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002584
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002585 return APInt(TypeBits, Words);
2586}
2587
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002588std::error_code BitcodeReader::parseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002589 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002590 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002591
2592 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002593
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002594 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00002595 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00002596 unsigned NextCstNo = ValueList.size();
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002597 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002598 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002599
Chris Lattner27d38752013-01-20 02:13:19 +00002600 switch (Entry.Kind) {
2601 case BitstreamEntry::SubBlock: // Handled for us already.
2602 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002603 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002604 case BitstreamEntry::EndBlock:
2605 if (NextCstNo != ValueList.size())
George Burgess IV1030d682016-01-20 22:15:23 +00002606 return error("Invalid constant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00002607
Chris Lattner27d38752013-01-20 02:13:19 +00002608 // Once all the constants have been read, go through and resolve forward
2609 // references.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002610 ValueList.resolveConstantForwardRefs();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002611 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002612 case BitstreamEntry::Record:
2613 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00002614 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002615 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002616
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002617 // Read a record.
2618 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00002619 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002620 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002621 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002622 default: // Default behavior: unknown constant
2623 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00002624 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002625 break;
2626 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2627 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002628 return error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00002629 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002630 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002631 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00002632 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002633 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00002634 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002635 break;
2636 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002637 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002638 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002639 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00002640 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00002641 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002642 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002643 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002644
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002645 APInt VInt =
2646 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002647 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002648
Chris Lattner08feb1e2007-04-24 04:04:35 +00002649 break;
2650 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002651 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00002652 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002653 return error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00002654 if (CurTy->isHalfTy())
Tim Northover29178a32013-01-22 09:46:31 +00002655 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2656 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00002657 else if (CurTy->isFloatTy())
Tim Northover29178a32013-01-22 09:46:31 +00002658 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2659 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002660 else if (CurTy->isDoubleTy())
Tim Northover29178a32013-01-22 09:46:31 +00002661 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2662 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002663 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00002664 // Bits are not stored the same way as a normal i80 APInt, compensate.
2665 uint64_t Rearrange[2];
2666 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2667 Rearrange[1] = Record[0] >> 48;
Tim Northover29178a32013-01-22 09:46:31 +00002668 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2669 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002670 } else if (CurTy->isFP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002671 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2672 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002673 else if (CurTy->isPPC_FP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002674 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2675 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002676 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00002677 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002678 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00002679 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002680
Chris Lattnere14cb882007-05-04 19:11:41 +00002681 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2682 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002683 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002684
Chris Lattnere14cb882007-05-04 19:11:41 +00002685 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00002686 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002687
Chris Lattner229907c2011-07-18 04:54:35 +00002688 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00002689 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002690 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00002691 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00002692 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002693 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2694 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002695 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002696 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00002697 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002698 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2699 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002700 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002701 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00002702 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00002703 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002704 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00002705 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002706 break;
2707 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002708 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00002709 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2710 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002711 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002712
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002713 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002714 V = ConstantDataArray::getString(Context, Elts,
2715 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00002716 break;
2717 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002718 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2719 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002720 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002721
Chris Lattner372dd1e2012-01-30 00:51:16 +00002722 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
Chris Lattner372dd1e2012-01-30 00:51:16 +00002723 if (EltTy->isIntegerTy(8)) {
2724 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2725 if (isa<VectorType>(CurTy))
2726 V = ConstantDataVector::get(Context, Elts);
2727 else
2728 V = ConstantDataArray::get(Context, Elts);
2729 } else if (EltTy->isIntegerTy(16)) {
2730 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2731 if (isa<VectorType>(CurTy))
2732 V = ConstantDataVector::get(Context, Elts);
2733 else
2734 V = ConstantDataArray::get(Context, Elts);
2735 } else if (EltTy->isIntegerTy(32)) {
2736 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2737 if (isa<VectorType>(CurTy))
2738 V = ConstantDataVector::get(Context, Elts);
2739 else
2740 V = ConstantDataArray::get(Context, Elts);
2741 } else if (EltTy->isIntegerTy(64)) {
2742 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2743 if (isa<VectorType>(CurTy))
2744 V = ConstantDataVector::get(Context, Elts);
2745 else
2746 V = ConstantDataArray::get(Context, Elts);
Justin Bognera43eacb2016-01-06 22:31:32 +00002747 } else if (EltTy->isHalfTy()) {
2748 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2749 if (isa<VectorType>(CurTy))
2750 V = ConstantDataVector::getFP(Context, Elts);
2751 else
2752 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002753 } else if (EltTy->isFloatTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00002754 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002755 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00002756 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002757 else
Justin Bognera43eacb2016-01-06 22:31:32 +00002758 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002759 } else if (EltTy->isDoubleTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00002760 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002761 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00002762 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002763 else
Justin Bognera43eacb2016-01-06 22:31:32 +00002764 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002765 } else {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002766 return error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00002767 }
2768 break;
2769 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002770 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002771 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002772 return error("Invalid record");
2773 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002774 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002775 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00002776 } else {
2777 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2778 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00002779 unsigned Flags = 0;
2780 if (Record.size() >= 4) {
2781 if (Opc == Instruction::Add ||
2782 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002783 Opc == Instruction::Mul ||
2784 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00002785 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2786 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2787 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2788 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002789 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002790 Opc == Instruction::UDiv ||
2791 Opc == Instruction::LShr ||
2792 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00002793 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00002794 Flags |= SDivOperator::IsExact;
2795 }
2796 }
2797 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00002798 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002799 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002800 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002801 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002802 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002803 return error("Invalid record");
2804 int Opc = getDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00002805 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002806 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00002807 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002808 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002809 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002810 return error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00002811 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002812 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2813 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002814 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002815 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002816 }
Dan Gohman1639c392009-07-27 21:53:46 +00002817 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002818 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
David Blaikieb9263572015-03-13 21:03:36 +00002819 unsigned OpNum = 0;
2820 Type *PointeeType = nullptr;
2821 if (Record.size() % 2)
2822 PointeeType = getTypeByID(Record[OpNum++]);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002823 SmallVector<Constant*, 16> Elts;
David Blaikieb9263572015-03-13 21:03:36 +00002824 while (OpNum != Record.size()) {
2825 Type *ElTy = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002826 if (!ElTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002827 return error("Invalid record");
David Blaikieb9263572015-03-13 21:03:36 +00002828 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002829 }
David Blaikieb9263572015-03-13 21:03:36 +00002830
David Blaikieb9263572015-03-13 21:03:36 +00002831 if (PointeeType &&
David Blaikie4a2e73b2015-04-02 18:55:32 +00002832 PointeeType !=
2833 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2834 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002835 return error("Explicit gep operator type does not match pointee type "
David Blaikie12cf5d702015-03-16 22:03:50 +00002836 "of pointer operand");
David Blaikie4a2e73b2015-04-02 18:55:32 +00002837
2838 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2839 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2840 BitCode ==
2841 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattner890683d2007-04-24 18:15:21 +00002842 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002843 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00002844 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002845 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002846 return error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00002847
2848 Type *SelectorTy = Type::getInt1Ty(Context);
2849
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00002850 // The selector might be an i1 or an <n x i1>
2851 // Get the type from the ValueList before getting a forward ref.
Joe Abbey1a6e7702013-09-12 22:02:31 +00002852 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00002853 if (Value *V = ValueList[Record[0]])
2854 if (SelectorTy != V->getType())
2855 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
Joe Abbey1a6e7702013-09-12 22:02:31 +00002856
2857 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2858 SelectorTy),
2859 ValueList.getConstantFwdRef(Record[1],CurTy),
2860 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002861 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00002862 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002863 case bitc::CST_CODE_CE_EXTRACTELT
2864 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002865 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002866 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002867 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002868 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002869 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002870 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002871 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002872 Constant *Op1 = nullptr;
2873 if (Record.size() == 4) {
2874 Type *IdxTy = getTypeByID(Record[2]);
2875 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002876 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002877 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2878 } else // TODO: Remove with llvm 4.0
2879 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2880 if (!Op1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002881 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002882 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002883 break;
2884 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002885 case bitc::CST_CODE_CE_INSERTELT
2886 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002887 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002888 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002889 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002890 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2891 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2892 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002893 Constant *Op2 = nullptr;
2894 if (Record.size() == 4) {
2895 Type *IdxTy = getTypeByID(Record[2]);
2896 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002897 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002898 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2899 } else // TODO: Remove with llvm 4.0
2900 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2901 if (!Op2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002902 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002903 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002904 break;
2905 }
2906 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002907 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002908 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002909 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002910 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2911 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002912 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002913 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002914 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002915 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002916 break;
2917 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00002918 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002919 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2920 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00002921 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002922 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002923 return error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002924 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2925 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002926 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002927 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00002928 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002929 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00002930 break;
2931 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002932 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002933 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002934 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002935 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002936 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002937 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002938 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2939 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2940
Duncan Sands9dff9be2010-02-15 16:12:20 +00002941 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002942 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00002943 else
Owen Anderson487375e2009-07-29 18:55:55 +00002944 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002945 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00002946 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002947 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00002948 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002949 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002950 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002951 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002952 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00002953 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002954 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002955 unsigned AsmStrSize = Record[1];
2956 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002957 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002958 unsigned ConstStrSize = Record[2+AsmStrSize];
2959 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002960 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002961
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002962 for (unsigned i = 0; i != AsmStrSize; ++i)
2963 AsmStr += (char)Record[2+i];
2964 for (unsigned i = 0; i != ConstStrSize; ++i)
2965 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00002966 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002967 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002968 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002969 break;
2970 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002971 // This version adds support for the asm dialect keywords (e.g.,
2972 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002973 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002974 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002975 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002976 std::string AsmStr, ConstrStr;
2977 bool HasSideEffects = Record[0] & 1;
2978 bool IsAlignStack = (Record[0] >> 1) & 1;
2979 unsigned AsmDialect = Record[0] >> 2;
2980 unsigned AsmStrSize = Record[1];
2981 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002982 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002983 unsigned ConstStrSize = Record[2+AsmStrSize];
2984 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002985 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002986
2987 for (unsigned i = 0; i != AsmStrSize; ++i)
2988 AsmStr += (char)Record[2+i];
2989 for (unsigned i = 0; i != ConstStrSize; ++i)
2990 ConstrStr += (char)Record[3+AsmStrSize+i];
2991 PointerType *PTy = cast<PointerType>(CurTy);
2992 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2993 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00002994 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002995 break;
2996 }
Chris Lattner5956dc82009-10-28 05:53:48 +00002997 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00002998 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002999 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003000 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003001 if (!FnTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003002 return error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00003003 Function *Fn =
3004 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00003005 if (!Fn)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003006 return error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003007
3008 // If the function is already parsed we can insert the block address right
3009 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003010 BasicBlock *BB;
3011 unsigned BBID = Record[2];
3012 if (!BBID)
3013 // Invalid reference to entry block.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003014 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003015 if (!Fn->empty()) {
3016 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003017 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003018 if (BBI == BBE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003019 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003020 ++BBI;
3021 }
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00003022 BB = &*BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003023 } else {
3024 // Otherwise insert a placeholder and remember it so it can be inserted
3025 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00003026 auto &FwdBBs = BasicBlockFwdRefs[Fn];
3027 if (FwdBBs.empty())
3028 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003029 if (FwdBBs.size() < BBID + 1)
3030 FwdBBs.resize(BBID + 1);
3031 if (!FwdBBs[BBID])
3032 FwdBBs[BBID] = BasicBlock::Create(Context);
3033 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003034 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003035 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00003036 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003037 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003038 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003039
David Majnemer8a1c45d2015-12-12 05:38:55 +00003040 ValueList.assignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00003041 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003042 }
3043}
Chris Lattner1314b992007-04-22 06:23:29 +00003044
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003045std::error_code BitcodeReader::parseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00003046 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003047 return error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00003048
Chad Rosierca2567b2011-12-07 21:44:12 +00003049 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003050 SmallVector<uint64_t, 64> Record;
Chad Rosierca2567b2011-12-07 21:44:12 +00003051 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00003052 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003053
Chris Lattner27d38752013-01-20 02:13:19 +00003054 switch (Entry.Kind) {
3055 case BitstreamEntry::SubBlock: // Handled for us already.
3056 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003057 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003058 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003059 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003060 case BitstreamEntry::Record:
3061 // The interesting case.
3062 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003063 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003064
Chad Rosierca2567b2011-12-07 21:44:12 +00003065 // Read a use list record.
3066 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003067 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00003068 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00003069 default: // Default behavior: unknown type.
3070 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003071 case bitc::USELIST_CODE_BB:
3072 IsBB = true;
3073 // fallthrough
3074 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00003075 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003076 if (RecordLength < 3)
3077 // Records should have at least an ID and two indexes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003078 return error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003079 unsigned ID = Record.back();
3080 Record.pop_back();
3081
3082 Value *V;
3083 if (IsBB) {
3084 assert(ID < FunctionBBs.size() && "Basic block not found");
3085 V = FunctionBBs[ID];
3086 } else
3087 V = ValueList[ID];
3088 unsigned NumUses = 0;
3089 SmallDenseMap<const Use *, unsigned, 16> Order;
Rafael Espindola257a3532016-01-15 19:00:20 +00003090 for (const Use &U : V->materialized_uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00003091 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003092 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00003093 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003094 }
3095 if (Order.size() != Record.size() || NumUses > Record.size())
3096 // Mismatches can happen if the functions are being materialized lazily
3097 // (out-of-order), or a value has been upgraded.
3098 break;
3099
3100 V->sortUseList([&](const Use &L, const Use &R) {
3101 return Order.lookup(&L) < Order.lookup(&R);
3102 });
Chad Rosierca2567b2011-12-07 21:44:12 +00003103 break;
3104 }
3105 }
3106 }
3107}
3108
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003109/// When we see the block for metadata, remember where it is and then skip it.
3110/// This lets us lazily deserialize the metadata.
3111std::error_code BitcodeReader::rememberAndSkipMetadata() {
3112 // Save the current stream state.
3113 uint64_t CurBit = Stream.GetCurrentBitNo();
3114 DeferredMetadataInfo.push_back(CurBit);
3115
3116 // Skip over the block for now.
3117 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003118 return error("Invalid record");
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003119 return std::error_code();
3120}
3121
3122std::error_code BitcodeReader::materializeMetadata() {
3123 for (uint64_t BitPos : DeferredMetadataInfo) {
3124 // Move the bit stream to the saved position.
3125 Stream.JumpToBit(BitPos);
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003126 if (std::error_code EC = parseMetadata(true))
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003127 return EC;
3128 }
3129 DeferredMetadataInfo.clear();
3130 return std::error_code();
3131}
3132
Rafael Espindola468b8682015-04-01 14:44:59 +00003133void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00003134
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003135/// When we see the block for a function body, remember where it is and then
3136/// skip it. This lets us lazily deserialize the functions.
3137std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003138 // Get the function we are talking about.
3139 if (FunctionsWithBodies.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003140 return error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003141
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003142 Function *Fn = FunctionsWithBodies.back();
3143 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003144
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003145 // Save the current stream state.
3146 uint64_t CurBit = Stream.GetCurrentBitNo();
Teresa Johnson1493ad92015-10-10 14:18:36 +00003147 assert(
3148 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3149 "Mismatch between VST and scanned function offsets");
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003150 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003151
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003152 // Skip over the function block for now.
3153 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003154 return error("Invalid record");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003155 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003156}
3157
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003158std::error_code BitcodeReader::globalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003159 // Patch the initializers for globals and aliases up.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003160 resolveGlobalAndAliasInits();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003161 if (!GlobalInits.empty() || !AliasInits.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003162 return error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003163
3164 // Look for intrinsic functions which need to be upgraded at some point
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003165 for (Function &F : *TheModule) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003166 Function *NewFn;
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003167 if (UpgradeIntrinsicFunction(&F, NewFn))
Rafael Espindola4e721212015-07-02 16:22:40 +00003168 UpgradedIntrinsics[&F] = NewFn;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003169 }
3170
3171 // Look for global variables which need to be renamed.
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003172 for (GlobalVariable &GV : TheModule->globals())
3173 UpgradeGlobalVariable(&GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00003174
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003175 // Force deallocation of memory for these vectors to favor the client that
3176 // want lazy deserialization.
3177 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3178 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003179 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003180}
3181
Teresa Johnson1493ad92015-10-10 14:18:36 +00003182/// Support for lazy parsing of function bodies. This is required if we
3183/// either have an old bitcode file without a VST forward declaration record,
3184/// or if we have an anonymous function being materialized, since anonymous
3185/// functions do not have a name and are therefore not in the VST.
3186std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3187 Stream.JumpToBit(NextUnreadBit);
3188
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003189 if (Stream.AtEndOfStream())
3190 return error("Could not find function in stream");
Teresa Johnson1493ad92015-10-10 14:18:36 +00003191
Filipe Cabecinhas7aae2f22015-11-03 13:48:26 +00003192 if (!SeenFirstFunctionBody)
3193 return error("Trying to materialize functions before seeing function blocks");
3194
Teresa Johnson1493ad92015-10-10 14:18:36 +00003195 // An old bitcode file with the symbol table at the end would have
3196 // finished the parse greedily.
3197 assert(SeenValueSymbolTable);
3198
3199 SmallVector<uint64_t, 64> Record;
3200
3201 while (1) {
3202 BitstreamEntry Entry = Stream.advance();
3203 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003204 default:
3205 return error("Expect SubBlock");
3206 case BitstreamEntry::SubBlock:
3207 switch (Entry.ID) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003208 default:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003209 return error("Expect function block");
3210 case bitc::FUNCTION_BLOCK_ID:
3211 if (std::error_code EC = rememberAndSkipFunctionBody())
3212 return EC;
3213 NextUnreadBit = Stream.GetCurrentBitNo();
3214 return std::error_code();
3215 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00003216 }
3217 }
3218}
3219
Mehdi Amini5d303282015-10-26 18:37:00 +00003220std::error_code BitcodeReader::parseBitcodeVersion() {
3221 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3222 return error("Invalid record");
3223
3224 // Read all the records.
3225 SmallVector<uint64_t, 64> Record;
3226 while (1) {
3227 BitstreamEntry Entry = Stream.advance();
3228
3229 switch (Entry.Kind) {
3230 default:
3231 case BitstreamEntry::Error:
3232 return error("Malformed block");
3233 case BitstreamEntry::EndBlock:
3234 return std::error_code();
3235 case BitstreamEntry::Record:
3236 // The interesting case.
3237 break;
3238 }
3239
3240 // Read a record.
3241 Record.clear();
3242 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3243 switch (BitCode) {
3244 default: // Default behavior: reject
3245 return error("Invalid value");
3246 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3247 // N]
3248 convertToString(Record, 0, ProducerIdentification);
3249 break;
3250 }
3251 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3252 unsigned epoch = (unsigned)Record[0];
3253 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
Oleksiy Vyalov6c2403f2015-10-26 22:37:36 +00003254 return error(
3255 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3256 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
Mehdi Amini5d303282015-10-26 18:37:00 +00003257 }
3258 }
3259 }
3260 }
3261}
3262
Teresa Johnson1493ad92015-10-10 14:18:36 +00003263std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003264 bool ShouldLazyLoadMetadata) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003265 if (ResumeBit)
3266 Stream.JumpToBit(ResumeBit);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003267 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003268 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003269
Chris Lattner1314b992007-04-22 06:23:29 +00003270 SmallVector<uint64_t, 64> Record;
3271 std::vector<std::string> SectionTable;
Gordon Henriksend930f912008-08-17 18:44:35 +00003272 std::vector<std::string> GCTable;
Chris Lattner1314b992007-04-22 06:23:29 +00003273
3274 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00003275 while (1) {
3276 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003277
Chris Lattner27d38752013-01-20 02:13:19 +00003278 switch (Entry.Kind) {
3279 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003280 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003281 case BitstreamEntry::EndBlock:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003282 return globalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00003283
Chris Lattner27d38752013-01-20 02:13:19 +00003284 case BitstreamEntry::SubBlock:
3285 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00003286 default: // Skip unknown content.
3287 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003288 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003289 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003290 case bitc::BLOCKINFO_BLOCK_ID:
3291 if (Stream.ReadBlockInfoBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003292 return error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003293 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003294 case bitc::PARAMATTR_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003295 if (std::error_code EC = parseAttributeBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003296 return EC;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003297 break;
Bill Wendlingba629332013-02-10 23:24:25 +00003298 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003299 if (std::error_code EC = parseAttributeGroupBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003300 return EC;
Bill Wendlingba629332013-02-10 23:24:25 +00003301 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003302 case bitc::TYPE_BLOCK_ID_NEW:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003303 if (std::error_code EC = parseTypeTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003304 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00003305 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00003306 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnsonff642b92015-09-17 20:12:00 +00003307 if (!SeenValueSymbolTable) {
3308 // Either this is an old form VST without function index and an
3309 // associated VST forward declaration record (which would have caused
3310 // the VST to be jumped to and parsed before it was encountered
3311 // normally in the stream), or there were no function blocks to
3312 // trigger an earlier parsing of the VST.
3313 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3314 if (std::error_code EC = parseValueSymbolTable())
3315 return EC;
3316 SeenValueSymbolTable = true;
3317 } else {
3318 // We must have had a VST forward declaration record, which caused
3319 // the parser to jump to and parse the VST earlier.
3320 assert(VSTOffset > 0);
3321 if (Stream.SkipBlock())
3322 return error("Invalid record");
3323 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00003324 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003325 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003326 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003327 return EC;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003328 if (std::error_code EC = resolveGlobalAndAliasInits())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003329 return EC;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003330 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00003331 case bitc::METADATA_BLOCK_ID:
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003332 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3333 if (std::error_code EC = rememberAndSkipMetadata())
3334 return EC;
3335 break;
3336 }
3337 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003338 if (std::error_code EC = parseMetadata(true))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003339 return EC;
Devang Patel7428d8a2009-07-22 17:43:22 +00003340 break;
Teresa Johnson12545072015-11-15 02:00:09 +00003341 case bitc::METADATA_KIND_BLOCK_ID:
3342 if (std::error_code EC = parseMetadataKinds())
3343 return EC;
3344 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003345 case bitc::FUNCTION_BLOCK_ID:
3346 // If this is the first function body we've seen, reverse the
3347 // FunctionsWithBodies list.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003348 if (!SeenFirstFunctionBody) {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003349 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003350 if (std::error_code EC = globalCleanup())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003351 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003352 SeenFirstFunctionBody = true;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003353 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003354
Teresa Johnsonff642b92015-09-17 20:12:00 +00003355 if (VSTOffset > 0) {
3356 // If we have a VST forward declaration record, make sure we
3357 // parse the VST now if we haven't already. It is needed to
3358 // set up the DeferredFunctionInfo vector for lazy reading.
3359 if (!SeenValueSymbolTable) {
3360 if (std::error_code EC =
3361 BitcodeReader::parseValueSymbolTable(VSTOffset))
3362 return EC;
3363 SeenValueSymbolTable = true;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003364 // Fall through so that we record the NextUnreadBit below.
3365 // This is necessary in case we have an anonymous function that
3366 // is later materialized. Since it will not have a VST entry we
3367 // need to fall back to the lazy parse to find its offset.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003368 } else {
3369 // If we have a VST forward declaration record, but have already
3370 // parsed the VST (just above, when the first function body was
3371 // encountered here), then we are resuming the parse after
Teresa Johnson1493ad92015-10-10 14:18:36 +00003372 // materializing functions. The ResumeBit points to the
3373 // start of the last function block recorded in the
3374 // DeferredFunctionInfo map. Skip it.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003375 if (Stream.SkipBlock())
3376 return error("Invalid record");
3377 continue;
3378 }
3379 }
3380
3381 // Support older bitcode files that did not have the function
Teresa Johnson1493ad92015-10-10 14:18:36 +00003382 // index in the VST, nor a VST forward declaration record, as
3383 // well as anonymous functions that do not have VST entries.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003384 // Build the DeferredFunctionInfo vector on the fly.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003385 if (std::error_code EC = rememberAndSkipFunctionBody())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003386 return EC;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003387
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003388 // Suspend parsing when we reach the function bodies. Subsequent
3389 // materialization calls will resume it when necessary. If the bitcode
3390 // file is old, the symbol table will be at the end instead and will not
3391 // have been seen yet. In this case, just finish the parse now.
3392 if (SeenValueSymbolTable) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003393 NextUnreadBit = Stream.GetCurrentBitNo();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003394 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003395 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003396 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003397 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003398 if (std::error_code EC = parseUseLists())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003399 return EC;
Chad Rosierca2567b2011-12-07 21:44:12 +00003400 break;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003401 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3402 if (std::error_code EC = parseOperandBundleTags())
3403 return EC;
3404 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003405 }
3406 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003407
Chris Lattner27d38752013-01-20 02:13:19 +00003408 case BitstreamEntry::Record:
3409 // The interesting case.
3410 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003411 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003412
Chris Lattner1314b992007-04-22 06:23:29 +00003413 // Read a record.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003414 auto BitCode = Stream.readRecord(Entry.ID, Record);
3415 switch (BitCode) {
Chris Lattner1314b992007-04-22 06:23:29 +00003416 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungafaced02012-10-11 20:20:40 +00003417 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattner1314b992007-04-22 06:23:29 +00003418 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003419 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00003420 // Only version #0 and #1 are supported so far.
3421 unsigned module_version = Record[0];
3422 switch (module_version) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003423 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003424 return error("Invalid value");
Jan Wen Voungafaced02012-10-11 20:20:40 +00003425 case 0:
3426 UseRelativeIDs = false;
3427 break;
3428 case 1:
3429 UseRelativeIDs = true;
3430 break;
3431 }
Chris Lattner1314b992007-04-22 06:23:29 +00003432 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00003433 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003434 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003435 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003436 if (convertToString(Record, 0, S))
3437 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003438 TheModule->setTargetTriple(S);
3439 break;
3440 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003441 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003442 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003443 if (convertToString(Record, 0, S))
3444 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003445 TheModule->setDataLayout(S);
3446 break;
3447 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003448 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003449 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003450 if (convertToString(Record, 0, S))
3451 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003452 TheModule->setModuleInlineAsm(S);
3453 break;
3454 }
Bill Wendling706d3d62012-11-28 08:41:48 +00003455 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3456 // FIXME: Remove in 4.0.
3457 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003458 if (convertToString(Record, 0, S))
3459 return error("Invalid record");
Bill Wendling706d3d62012-11-28 08:41:48 +00003460 // Ignore value.
3461 break;
3462 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003463 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003464 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003465 if (convertToString(Record, 0, S))
3466 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003467 SectionTable.push_back(S);
3468 break;
3469 }
Gordon Henriksend930f912008-08-17 18:44:35 +00003470 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00003471 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003472 if (convertToString(Record, 0, S))
3473 return error("Invalid record");
Gordon Henriksend930f912008-08-17 18:44:35 +00003474 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00003475 break;
3476 }
David Majnemerdad0a642014-06-27 18:19:56 +00003477 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3478 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003479 return error("Invalid record");
David Majnemerdad0a642014-06-27 18:19:56 +00003480 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3481 unsigned ComdatNameSize = Record[1];
3482 std::string ComdatName;
3483 ComdatName.reserve(ComdatNameSize);
3484 for (unsigned i = 0; i != ComdatNameSize; ++i)
3485 ComdatName += (char)Record[2 + i];
3486 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3487 C->setSelectionKind(SK);
3488 ComdatList.push_back(C);
3489 break;
3490 }
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003491 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00003492 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00003493 // unnamed_addr, externally_initialized, dllstorageclass,
3494 // comdat]
Chris Lattner1314b992007-04-22 06:23:29 +00003495 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner4b00d922007-04-23 16:04:05 +00003496 if (Record.size() < 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003497 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003498 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003499 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003500 return error("Invalid record");
David Blaikie1a848da2015-04-27 19:58:56 +00003501 bool isConstant = Record[1] & 1;
3502 bool explicitType = Record[1] & 2;
3503 unsigned AddressSpace;
3504 if (explicitType) {
3505 AddressSpace = Record[1] >> 2;
3506 } else {
3507 if (!Ty->isPointerTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003508 return error("Invalid type for value");
David Blaikie1a848da2015-04-27 19:58:56 +00003509 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3510 Ty = cast<PointerType>(Ty)->getElementType();
3511 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003512
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003513 uint64_t RawLinkage = Record[3];
3514 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
JF Bastien30bf96b2015-02-22 19:32:03 +00003515 unsigned Alignment;
3516 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3517 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00003518 std::string Section;
3519 if (Record[5]) {
3520 if (Record[5]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003521 return error("Invalid ID");
Chris Lattner1314b992007-04-22 06:23:29 +00003522 Section = SectionTable[Record[5]-1];
3523 }
Chris Lattner4b00d922007-04-23 16:04:05 +00003524 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003525 // Local linkage must have default visibility.
3526 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3527 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003528 Visibility = getDecodedVisibility(Record[6]);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00003529
3530 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner53862f72007-05-06 19:27:46 +00003531 if (Record.size() > 7)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003532 TLM = getDecodedThreadLocalMode(Record[7]);
Chris Lattner1314b992007-04-22 06:23:29 +00003533
Rafael Espindola45e6c192011-01-08 16:42:36 +00003534 bool UnnamedAddr = false;
3535 if (Record.size() > 8)
3536 UnnamedAddr = Record[8];
3537
Michael Gottesman27e7ef32013-02-05 05:57:38 +00003538 bool ExternallyInitialized = false;
3539 if (Record.size() > 9)
3540 ExternallyInitialized = Record[9];
3541
Chris Lattner1314b992007-04-22 06:23:29 +00003542 GlobalVariable *NewGV =
Craig Topper2617dcc2014-04-15 06:32:26 +00003543 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
Michael Gottesman27e7ef32013-02-05 05:57:38 +00003544 TLM, AddressSpace, ExternallyInitialized);
Chris Lattner1314b992007-04-22 06:23:29 +00003545 NewGV->setAlignment(Alignment);
3546 if (!Section.empty())
3547 NewGV->setSection(Section);
3548 NewGV->setVisibility(Visibility);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003549 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003550
Nico Rieck7157bb72014-01-14 15:22:47 +00003551 if (Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003552 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003553 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003554 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00003555
Chris Lattnerccaa4482007-04-23 21:26:05 +00003556 ValueList.push_back(NewGV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003557
Chris Lattner47d131b2007-04-24 00:18:21 +00003558 // Remember which value to use for the global initializer.
3559 if (unsigned InitID = Record[2])
3560 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
David Majnemerdad0a642014-06-27 18:19:56 +00003561
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003562 if (Record.size() > 11) {
David Majnemerdad0a642014-06-27 18:19:56 +00003563 if (unsigned ComdatID = Record[11]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00003564 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003565 return error("Invalid global variable comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00003566 NewGV->setComdat(ComdatList[ComdatID - 1]);
3567 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003568 } else if (hasImplicitComdat(RawLinkage)) {
3569 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3570 }
Chris Lattner1314b992007-04-22 06:23:29 +00003571 break;
3572 }
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003573 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Nico Rieck7157bb72014-01-14 15:22:47 +00003574 // alignment, section, visibility, gc, unnamed_addr,
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003575 // prologuedata, dllstorageclass, comdat, prefixdata]
Chris Lattner1314b992007-04-22 06:23:29 +00003576 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003577 if (Record.size() < 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003578 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003579 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003580 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003581 return error("Invalid record");
David Blaikie561a1572015-04-17 16:28:26 +00003582 if (auto *PTy = dyn_cast<PointerType>(Ty))
3583 Ty = PTy->getElementType();
3584 auto *FTy = dyn_cast<FunctionType>(Ty);
Chris Lattner1314b992007-04-22 06:23:29 +00003585 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003586 return error("Invalid type for value");
Vedant Kumarad6d6e72015-10-27 21:17:06 +00003587 auto CC = static_cast<CallingConv::ID>(Record[1]);
3588 if (CC & ~CallingConv::MaxID)
3589 return error("Invalid calling convention ID");
Chris Lattner1314b992007-04-22 06:23:29 +00003590
Gabor Greife9ecc682008-04-06 20:25:17 +00003591 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3592 "", TheModule);
Chris Lattner1314b992007-04-22 06:23:29 +00003593
Vedant Kumarad6d6e72015-10-27 21:17:06 +00003594 Func->setCallingConv(CC);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003595 bool isProto = Record[2];
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003596 uint64_t RawLinkage = Record[3];
3597 Func->setLinkage(getDecodedLinkage(RawLinkage));
Devang Patel4c758ea2008-09-25 21:00:45 +00003598 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003599
JF Bastien30bf96b2015-02-22 19:32:03 +00003600 unsigned Alignment;
3601 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3602 return EC;
3603 Func->setAlignment(Alignment);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003604 if (Record[6]) {
3605 if (Record[6]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003606 return error("Invalid ID");
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003607 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattner1314b992007-04-22 06:23:29 +00003608 }
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003609 // Local linkage must have default visibility.
3610 if (!Func->hasLocalLinkage())
3611 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003612 Func->setVisibility(getDecodedVisibility(Record[7]));
Gordon Henriksen71183b62007-12-10 03:18:06 +00003613 if (Record.size() > 8 && Record[8]) {
Filipe Cabecinhasf8a16a92015-04-30 04:09:41 +00003614 if (Record[8]-1 >= GCTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003615 return error("Invalid ID");
Gordon Henriksend930f912008-08-17 18:44:35 +00003616 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen71183b62007-12-10 03:18:06 +00003617 }
Rafael Espindola45e6c192011-01-08 16:42:36 +00003618 bool UnnamedAddr = false;
3619 if (Record.size() > 9)
3620 UnnamedAddr = Record[9];
3621 Func->setUnnamedAddr(UnnamedAddr);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003622 if (Record.size() > 10 && Record[10] != 0)
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003623 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
Nico Rieck7157bb72014-01-14 15:22:47 +00003624
3625 if (Record.size() > 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003626 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003627 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003628 upgradeDLLImportExportLinkage(Func, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00003629
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003630 if (Record.size() > 12) {
David Majnemerdad0a642014-06-27 18:19:56 +00003631 if (unsigned ComdatID = Record[12]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00003632 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003633 return error("Invalid function comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00003634 Func->setComdat(ComdatList[ComdatID - 1]);
3635 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003636 } else if (hasImplicitComdat(RawLinkage)) {
3637 Func->setComdat(reinterpret_cast<Comdat *>(1));
3638 }
David Majnemerdad0a642014-06-27 18:19:56 +00003639
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003640 if (Record.size() > 13 && Record[13] != 0)
3641 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3642
David Majnemer7fddecc2015-06-17 20:52:32 +00003643 if (Record.size() > 14 && Record[14] != 0)
3644 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3645
Chris Lattnerccaa4482007-04-23 21:26:05 +00003646 ValueList.push_back(Func);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003647
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003648 // If this is a function with a body, remember the prototype we are
3649 // creating now, so that we can match up the body with them later.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003650 if (!isProto) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00003651 Func->setIsMaterializable(true);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003652 FunctionsWithBodies.push_back(Func);
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003653 DeferredFunctionInfo[Func] = 0;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003654 }
Chris Lattner1314b992007-04-22 06:23:29 +00003655 break;
3656 }
David Blaikie6a51dbd2015-09-17 22:18:59 +00003657 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3658 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3659 case bitc::MODULE_CODE_ALIAS:
3660 case bitc::MODULE_CODE_ALIAS_OLD: {
3661 bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
Aaron Ballman2d0f38c2015-09-18 13:31:42 +00003662 if (Record.size() < (3 + (unsigned)NewRecord))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003663 return error("Invalid record");
David Blaikie6a51dbd2015-09-17 22:18:59 +00003664 unsigned OpNum = 0;
3665 Type *Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003666 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003667 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003668
David Blaikie6a51dbd2015-09-17 22:18:59 +00003669 unsigned AddrSpace;
3670 if (!NewRecord) {
3671 auto *PTy = dyn_cast<PointerType>(Ty);
3672 if (!PTy)
3673 return error("Invalid type for value");
3674 Ty = PTy->getElementType();
3675 AddrSpace = PTy->getAddressSpace();
3676 } else {
3677 AddrSpace = Record[OpNum++];
3678 }
3679
3680 auto Val = Record[OpNum++];
3681 auto Linkage = Record[OpNum++];
3682 auto *NewGA = GlobalAlias::create(
3683 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00003684 // Old bitcode files didn't have visibility field.
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003685 // Local linkage must have default visibility.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003686 if (OpNum != Record.size()) {
3687 auto VisInd = OpNum++;
3688 if (!NewGA->hasLocalLinkage())
3689 // FIXME: Change to an error if non-default in 4.0.
3690 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3691 }
3692 if (OpNum != Record.size())
3693 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003694 else
David Blaikie6a51dbd2015-09-17 22:18:59 +00003695 upgradeDLLImportExportLinkage(NewGA, Linkage);
3696 if (OpNum != Record.size())
3697 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3698 if (OpNum != Record.size())
3699 NewGA->setUnnamedAddr(Record[OpNum++]);
Chris Lattner44c17072007-04-26 02:46:40 +00003700 ValueList.push_back(NewGA);
David Blaikie6a51dbd2015-09-17 22:18:59 +00003701 AliasInits.push_back(std::make_pair(NewGA, Val));
Chris Lattner44c17072007-04-26 02:46:40 +00003702 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003703 }
Chris Lattner831d4202007-04-26 03:27:58 +00003704 /// MODULE_CODE_PURGEVALS: [numvals]
3705 case bitc::MODULE_CODE_PURGEVALS:
3706 // Trim down the value list to the specified size.
3707 if (Record.size() < 1 || Record[0] > ValueList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003708 return error("Invalid record");
Chris Lattner831d4202007-04-26 03:27:58 +00003709 ValueList.shrinkTo(Record[0]);
3710 break;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003711 /// MODULE_CODE_VSTOFFSET: [offset]
3712 case bitc::MODULE_CODE_VSTOFFSET:
3713 if (Record.size() < 1)
3714 return error("Invalid record");
3715 VSTOffset = Record[0];
3716 break;
Teresa Johnsone1164de2016-02-10 21:55:02 +00003717 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3718 case bitc::MODULE_CODE_SOURCE_FILENAME:
3719 SmallString<128> ValueName;
3720 if (convertToString(Record, 0, ValueName))
3721 return error("Invalid record");
3722 TheModule->setSourceFileName(ValueName);
3723 break;
Chris Lattner831d4202007-04-26 03:27:58 +00003724 }
Chris Lattner1314b992007-04-22 06:23:29 +00003725 Record.clear();
3726 }
Chris Lattner1314b992007-04-22 06:23:29 +00003727}
3728
Teresa Johnson403a7872015-10-04 14:33:43 +00003729/// Helper to read the header common to all bitcode files.
3730static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3731 // Sniff for the signature.
3732 if (Stream.Read(8) != 'B' ||
3733 Stream.Read(8) != 'C' ||
3734 Stream.Read(4) != 0x0 ||
3735 Stream.Read(4) != 0xC ||
3736 Stream.Read(4) != 0xE ||
3737 Stream.Read(4) != 0xD)
3738 return false;
3739 return true;
3740}
3741
Rafael Espindola1aabf982015-06-16 23:29:49 +00003742std::error_code
3743BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3744 Module *M, bool ShouldLazyLoadMetadata) {
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003745 TheModule = M;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003746
Rafael Espindola1aabf982015-06-16 23:29:49 +00003747 if (std::error_code EC = initStream(std::move(Streamer)))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003748 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003749
Chris Lattner1314b992007-04-22 06:23:29 +00003750 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003751 if (!hasValidBitcodeHeader(Stream))
3752 return error("Invalid bitcode signature");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003753
Chris Lattner1314b992007-04-22 06:23:29 +00003754 // We expect a number of well-defined blocks, though we don't necessarily
3755 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00003756 while (1) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003757 if (Stream.AtEndOfStream()) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003758 // We didn't really read a proper Module.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003759 return error("Malformed IR file");
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003760 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003761
Chris Lattner27d38752013-01-20 02:13:19 +00003762 BitstreamEntry Entry =
3763 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbey97b7a172013-02-06 22:14:06 +00003764
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003765 if (Entry.Kind != BitstreamEntry::SubBlock)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003766 return error("Malformed block");
Joe Abbey97b7a172013-02-06 22:14:06 +00003767
Mehdi Amini5d303282015-10-26 18:37:00 +00003768 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3769 parseBitcodeVersion();
3770 continue;
3771 }
3772
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003773 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Teresa Johnson1493ad92015-10-10 14:18:36 +00003774 return parseModule(0, ShouldLazyLoadMetadata);
Joe Abbey97b7a172013-02-06 22:14:06 +00003775
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003776 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003777 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003778 }
Chris Lattner1314b992007-04-22 06:23:29 +00003779}
Chris Lattner6694f602007-04-29 07:54:31 +00003780
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003781ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
Bill Wendling0198ce02010-10-06 01:22:42 +00003782 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003783 return error("Invalid record");
Bill Wendling0198ce02010-10-06 01:22:42 +00003784
3785 SmallVector<uint64_t, 64> Record;
3786
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003787 std::string Triple;
Bill Wendling0198ce02010-10-06 01:22:42 +00003788 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00003789 while (1) {
3790 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003791
Chris Lattner27d38752013-01-20 02:13:19 +00003792 switch (Entry.Kind) {
3793 case BitstreamEntry::SubBlock: // Handled for us already.
3794 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003795 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003796 case BitstreamEntry::EndBlock:
Rafael Espindolae6107792014-07-04 20:05:56 +00003797 return Triple;
Chris Lattner27d38752013-01-20 02:13:19 +00003798 case BitstreamEntry::Record:
3799 // The interesting case.
3800 break;
Bill Wendling0198ce02010-10-06 01:22:42 +00003801 }
3802
3803 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00003804 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling0198ce02010-10-06 01:22:42 +00003805 default: break; // Default behavior, ignore unknown content.
Bill Wendling0198ce02010-10-06 01:22:42 +00003806 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003807 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003808 if (convertToString(Record, 0, S))
3809 return error("Invalid record");
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003810 Triple = S;
Bill Wendling0198ce02010-10-06 01:22:42 +00003811 break;
3812 }
3813 }
3814 Record.clear();
3815 }
Rafael Espindolae6107792014-07-04 20:05:56 +00003816 llvm_unreachable("Exit infinite loop");
Bill Wendling0198ce02010-10-06 01:22:42 +00003817}
3818
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003819ErrorOr<std::string> BitcodeReader::parseTriple() {
Rafael Espindola1aabf982015-06-16 23:29:49 +00003820 if (std::error_code EC = initStream(nullptr))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003821 return EC;
Bill Wendling0198ce02010-10-06 01:22:42 +00003822
3823 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003824 if (!hasValidBitcodeHeader(Stream))
3825 return error("Invalid bitcode signature");
Bill Wendling0198ce02010-10-06 01:22:42 +00003826
3827 // We expect a number of well-defined blocks, though we don't necessarily
3828 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00003829 while (1) {
3830 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003831
Chris Lattner27d38752013-01-20 02:13:19 +00003832 switch (Entry.Kind) {
3833 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003834 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003835 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003836 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00003837
Chris Lattner27d38752013-01-20 02:13:19 +00003838 case BitstreamEntry::SubBlock:
3839 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Rafael Espindolad346cc82014-07-04 13:52:01 +00003840 return parseModuleTriple();
Joe Abbey97b7a172013-02-06 22:14:06 +00003841
Chris Lattner27d38752013-01-20 02:13:19 +00003842 // Ignore other sub-blocks.
Rafael Espindola48da4f42013-11-04 16:16:24 +00003843 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003844 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003845 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003846
Chris Lattner27d38752013-01-20 02:13:19 +00003847 case BitstreamEntry::Record:
3848 Stream.skipRecord(Entry.ID);
3849 continue;
Bill Wendling0198ce02010-10-06 01:22:42 +00003850 }
3851 }
Bill Wendling0198ce02010-10-06 01:22:42 +00003852}
3853
Mehdi Amini3383ccc2015-11-09 02:46:41 +00003854ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
3855 if (std::error_code EC = initStream(nullptr))
3856 return EC;
3857
3858 // Sniff for the signature.
3859 if (!hasValidBitcodeHeader(Stream))
3860 return error("Invalid bitcode signature");
3861
3862 // We expect a number of well-defined blocks, though we don't necessarily
3863 // need to understand them all.
3864 while (1) {
3865 BitstreamEntry Entry = Stream.advance();
3866 switch (Entry.Kind) {
3867 case BitstreamEntry::Error:
3868 return error("Malformed block");
3869 case BitstreamEntry::EndBlock:
3870 return std::error_code();
3871
3872 case BitstreamEntry::SubBlock:
3873 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3874 if (std::error_code EC = parseBitcodeVersion())
3875 return EC;
3876 return ProducerIdentification;
3877 }
3878 // Ignore other sub-blocks.
3879 if (Stream.SkipBlock())
3880 return error("Malformed block");
3881 continue;
3882 case BitstreamEntry::Record:
3883 Stream.skipRecord(Entry.ID);
3884 continue;
3885 }
3886 }
3887}
3888
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003889/// Parse metadata attachments.
3890std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
Devang Patelaf206b82009-09-18 19:26:43 +00003891 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003892 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003893
Devang Patelaf206b82009-09-18 19:26:43 +00003894 SmallVector<uint64_t, 64> Record;
Chris Lattner27d38752013-01-20 02:13:19 +00003895 while (1) {
3896 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003897
Chris Lattner27d38752013-01-20 02:13:19 +00003898 switch (Entry.Kind) {
3899 case BitstreamEntry::SubBlock: // Handled for us already.
3900 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003901 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003902 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003903 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003904 case BitstreamEntry::Record:
3905 // The interesting case.
Devang Patelaf206b82009-09-18 19:26:43 +00003906 break;
3907 }
Chris Lattner27d38752013-01-20 02:13:19 +00003908
Devang Patelaf206b82009-09-18 19:26:43 +00003909 // Read a metadata attachment record.
3910 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00003911 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patelaf206b82009-09-18 19:26:43 +00003912 default: // Default behavior: ignore.
3913 break;
Chris Lattnerb8778552011-06-17 17:50:30 +00003914 case bitc::METADATA_ATTACHMENT: {
Devang Patelaf206b82009-09-18 19:26:43 +00003915 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003916 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003917 return error("Invalid record");
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003918 if (RecordLength % 2 == 0) {
3919 // A function attachment.
3920 for (unsigned I = 0; I != RecordLength; I += 2) {
3921 auto K = MDKindMap.find(Record[I]);
3922 if (K == MDKindMap.end())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003923 return error("Invalid ID");
Justin Bognerae341c62016-03-17 20:12:06 +00003924 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
3925 if (!MD)
3926 return error("Invalid metadata attachment");
3927 F.setMetadata(K->second, MD);
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003928 }
3929 continue;
3930 }
3931
3932 // An instruction attachment.
Devang Patelaf206b82009-09-18 19:26:43 +00003933 Instruction *Inst = InstructionList[Record[0]];
3934 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patelb1a44772009-09-28 21:14:55 +00003935 unsigned Kind = Record[i];
Dan Gohman43aa8f02010-07-20 21:42:28 +00003936 DenseMap<unsigned, unsigned>::iterator I =
3937 MDKindMap.find(Kind);
3938 if (I == MDKindMap.end())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003939 return error("Invalid ID");
Justin Bognerae341c62016-03-17 20:12:06 +00003940 Metadata *Node = MetadataList.getMetadataFwdRef(Record[i + 1]);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003941 if (isa<LocalAsMetadata>(Node))
Duncan P. N. Exon Smith35303fd2014-12-06 02:29:44 +00003942 // Drop the attachment. This used to be legal, but there's no
3943 // upgrade path.
3944 break;
Justin Bognerae341c62016-03-17 20:12:06 +00003945 MDNode *MD = dyn_cast_or_null<MDNode>(Node);
3946 if (!MD)
3947 return error("Invalid metadata attachment");
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00003948
3949 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
3950 MD = upgradeInstructionLoopAttachment(*MD);
3951
Justin Bognerae341c62016-03-17 20:12:06 +00003952 Inst->setMetadata(I->second, MD);
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00003953 if (I->second == LLVMContext::MD_tbaa) {
Manman Ren209b17c2013-09-28 00:22:27 +00003954 InstsWithTBAATag.push_back(Inst);
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00003955 continue;
3956 }
Devang Patelaf206b82009-09-18 19:26:43 +00003957 }
3958 break;
3959 }
3960 }
3961 }
Devang Patelaf206b82009-09-18 19:26:43 +00003962}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003963
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00003964static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3965 LLVMContext &Context = PtrType->getContext();
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003966 if (!isa<PointerType>(PtrType))
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00003967 return error(Context, "Load/Store operand is not a pointer type");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003968 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3969
3970 if (ValType && ValType != ElemType)
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00003971 return error(Context, "Explicit load/store type does not match pointee "
3972 "type of pointer operand");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003973 if (!PointerType::isLoadableOrStorableType(ElemType))
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00003974 return error(Context, "Cannot load/store from pointer");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003975 return std::error_code();
3976}
3977
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003978/// Lazily parse the specified function body block.
3979std::error_code BitcodeReader::parseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00003980 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003981 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003982
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00003983 // Unexpected unresolved metadata when parsing function.
3984 if (MetadataList.hasFwdRefs())
3985 return error("Invalid function metadata: incoming forward references");
3986
Nick Lewyckya72e1af2010-02-25 08:30:17 +00003987 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00003988 unsigned ModuleValueListSize = ValueList.size();
Teresa Johnson61b406e2015-12-29 23:00:22 +00003989 unsigned ModuleMetadataListSize = MetadataList.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003990
Chris Lattner85b7b402007-05-01 05:52:21 +00003991 // Add all the function arguments to the value table.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00003992 for (Argument &I : F->args())
3993 ValueList.push_back(&I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003994
Chris Lattner83930552007-05-01 07:01:57 +00003995 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00003996 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00003997 unsigned CurBBNo = 0;
3998
Chris Lattner07d09ed2010-04-03 02:17:50 +00003999 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004000 auto getLastInstruction = [&]() -> Instruction * {
4001 if (CurBB && !CurBB->empty())
4002 return &CurBB->back();
4003 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4004 !FunctionBBs[CurBBNo - 1]->empty())
4005 return &FunctionBBs[CurBBNo - 1]->back();
4006 return nullptr;
4007 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004008
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004009 std::vector<OperandBundleDef> OperandBundles;
4010
Chris Lattner85b7b402007-05-01 05:52:21 +00004011 // Read all the records.
4012 SmallVector<uint64_t, 64> Record;
4013 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00004014 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00004015
Chris Lattner27d38752013-01-20 02:13:19 +00004016 switch (Entry.Kind) {
4017 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004018 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004019 case BitstreamEntry::EndBlock:
4020 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00004021
Chris Lattner27d38752013-01-20 02:13:19 +00004022 case BitstreamEntry::SubBlock:
4023 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00004024 default: // Skip unknown content.
4025 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004026 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00004027 break;
4028 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004029 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004030 return EC;
Chris Lattner83930552007-05-01 07:01:57 +00004031 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00004032 break;
4033 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004034 if (std::error_code EC = parseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004035 return EC;
Chris Lattner85b7b402007-05-01 05:52:21 +00004036 break;
Devang Patelaf206b82009-09-18 19:26:43 +00004037 case bitc::METADATA_ATTACHMENT_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004038 if (std::error_code EC = parseMetadataAttachment(*F))
Rafael Espindola48da4f42013-11-04 16:16:24 +00004039 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004040 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00004041 case bitc::METADATA_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004042 if (std::error_code EC = parseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004043 return EC;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00004044 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004045 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004046 if (std::error_code EC = parseUseLists())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004047 return EC;
4048 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00004049 }
4050 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00004051
Chris Lattner27d38752013-01-20 02:13:19 +00004052 case BitstreamEntry::Record:
4053 // The interesting case.
4054 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00004055 }
Joe Abbey97b7a172013-02-06 22:14:06 +00004056
Chris Lattner85b7b402007-05-01 05:52:21 +00004057 // Read a record.
4058 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00004059 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00004060 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00004061 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00004062 default: // Default behavior: reject
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004063 return error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004064 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00004065 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004066 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00004067 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00004068 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004069
4070 // See if anything took the address of blocks in this function.
4071 auto BBFRI = BasicBlockFwdRefs.find(F);
4072 if (BBFRI == BasicBlockFwdRefs.end()) {
4073 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4074 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
4075 } else {
4076 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00004077 // Check for invalid basic block references.
4078 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004079 return error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00004080 assert(!BBRefs.empty() && "Unexpected empty array");
4081 assert(!BBRefs.front() && "Invalid reference to entry block");
4082 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4083 ++I)
4084 if (I < RE && BBRefs[I]) {
4085 BBRefs[I]->insertInto(F);
4086 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004087 } else {
4088 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4089 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004090
4091 // Erase from the table.
4092 BasicBlockFwdRefs.erase(BBFRI);
4093 }
4094
Chris Lattner83930552007-05-01 07:01:57 +00004095 CurBB = FunctionBBs[0];
4096 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004097 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004098
Chris Lattner07d09ed2010-04-03 02:17:50 +00004099 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4100 // This record indicates that the last instruction is at the same
4101 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004102 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004103
Craig Topper2617dcc2014-04-15 06:32:26 +00004104 if (!I)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004105 return error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00004106 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004107 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004108 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004109
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00004110 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004111 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00004112 if (!I || Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004113 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004114
Chris Lattner07d09ed2010-04-03 02:17:50 +00004115 unsigned Line = Record[0], Col = Record[1];
4116 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004117
Craig Topper2617dcc2014-04-15 06:32:26 +00004118 MDNode *Scope = nullptr, *IA = nullptr;
Justin Bognerae341c62016-03-17 20:12:06 +00004119 if (ScopeID) {
4120 Scope = MetadataList.getMDNodeFwdRefOrNull(ScopeID - 1);
4121 if (!Scope)
4122 return error("Invalid record");
4123 }
4124 if (IAID) {
4125 IA = MetadataList.getMDNodeFwdRefOrNull(IAID - 1);
4126 if (!IA)
4127 return error("Invalid record");
4128 }
Chris Lattner07d09ed2010-04-03 02:17:50 +00004129 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4130 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004131 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004132 continue;
4133 }
4134
Chris Lattnere9759c22007-05-06 00:21:25 +00004135 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4136 unsigned OpNum = 0;
4137 Value *LHS, *RHS;
4138 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004139 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00004140 OpNum+1 > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004141 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004142
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004143 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00004144 if (Opc == -1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004145 return error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004146 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00004147 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00004148 if (OpNum < Record.size()) {
4149 if (Opc == Instruction::Add ||
4150 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00004151 Opc == Instruction::Mul ||
4152 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00004153 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00004154 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00004155 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00004156 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00004157 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00004158 Opc == Instruction::UDiv ||
4159 Opc == Instruction::LShr ||
4160 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00004161 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00004162 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004163 } else if (isa<FPMathOperator>(I)) {
James Molloy88eb5352015-07-10 12:52:00 +00004164 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004165 if (FMF.any())
4166 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00004167 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004168
Dan Gohman1b849082009-09-07 23:54:19 +00004169 }
Chris Lattner85b7b402007-05-01 05:52:21 +00004170 break;
4171 }
Chris Lattnere9759c22007-05-06 00:21:25 +00004172 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4173 unsigned OpNum = 0;
4174 Value *Op;
4175 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4176 OpNum+2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004177 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004178
Chris Lattner229907c2011-07-18 04:54:35 +00004179 Type *ResTy = getTypeByID(Record[OpNum]);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004180 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004181 if (Opc == -1 || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004182 return error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00004183 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004184 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4185 if (Temp) {
4186 InstructionList.push_back(Temp);
4187 CurBB->getInstList().push_back(Temp);
4188 }
4189 } else {
Filipe Cabecinhasb70fd872015-10-06 12:37:54 +00004190 auto CastOp = (Instruction::CastOps)Opc;
4191 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4192 return error("Invalid cast");
4193 I = CastInst::Create(CastOp, Op, ResTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004194 }
Devang Patelaf206b82009-09-18 19:26:43 +00004195 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004196 break;
4197 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00004198 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4199 case bitc::FUNC_CODE_INST_GEP_OLD:
4200 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004201 unsigned OpNum = 0;
David Blaikieb5b5efd2015-02-25 01:08:52 +00004202
4203 Type *Ty;
4204 bool InBounds;
4205
4206 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4207 InBounds = Record[OpNum++];
4208 Ty = getTypeByID(Record[OpNum++]);
4209 } else {
4210 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4211 Ty = nullptr;
4212 }
4213
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004214 Value *BasePtr;
4215 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004216 return error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00004217
David Blaikie60310f22015-05-08 00:42:26 +00004218 if (!Ty)
4219 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4220 ->getElementType();
4221 else if (Ty !=
4222 cast<SequentialType>(BasePtr->getType()->getScalarType())
4223 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004224 return error(
David Blaikie675e8cb2015-03-16 21:35:48 +00004225 "Explicit gep type does not match pointee type of pointer operand");
4226
Chris Lattner5285b5e2007-05-02 05:46:45 +00004227 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004228 while (OpNum != Record.size()) {
4229 Value *Op;
4230 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004231 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004232 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004233 }
4234
David Blaikie096b1da2015-03-14 19:53:33 +00004235 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
David Blaikie675e8cb2015-03-16 21:35:48 +00004236
Devang Patelaf206b82009-09-18 19:26:43 +00004237 InstructionList.push_back(I);
David Blaikieb5b5efd2015-02-25 01:08:52 +00004238 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004239 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004240 break;
4241 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004242
Dan Gohman1ecaf452008-05-31 00:58:22 +00004243 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4244 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00004245 unsigned OpNum = 0;
4246 Value *Agg;
4247 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004248 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004249
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004250 unsigned RecSize = Record.size();
4251 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004252 return error("EXTRACTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004253
Dan Gohman1ecaf452008-05-31 00:58:22 +00004254 SmallVector<unsigned, 4> EXTRACTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004255 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004256 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004257 bool IsArray = CurTy->isArrayTy();
4258 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00004259 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004260
4261 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004262 return error("EXTRACTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004263 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004264 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004265 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004266 return error("EXTRACTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004267 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004268 return error("EXTRACTVAL: Invalid array index");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004269 EXTRACTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004270
4271 if (IsStruct)
4272 CurTy = CurTy->subtypes()[Index];
4273 else
4274 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00004275 }
4276
Jay Foad57aa6362011-07-13 10:26:04 +00004277 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00004278 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00004279 break;
4280 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004281
Dan Gohman1ecaf452008-05-31 00:58:22 +00004282 case bitc::FUNC_CODE_INST_INSERTVAL: {
4283 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00004284 unsigned OpNum = 0;
4285 Value *Agg;
4286 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004287 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004288 Value *Val;
4289 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004290 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004291
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004292 unsigned RecSize = Record.size();
4293 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004294 return error("INSERTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004295
Dan Gohman1ecaf452008-05-31 00:58:22 +00004296 SmallVector<unsigned, 4> INSERTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004297 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004298 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004299 bool IsArray = CurTy->isArrayTy();
4300 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00004301 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004302
4303 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004304 return error("INSERTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004305 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004306 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004307 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004308 return error("INSERTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004309 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004310 return error("INSERTVAL: Invalid array index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004311
Dan Gohman1ecaf452008-05-31 00:58:22 +00004312 INSERTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004313 if (IsStruct)
4314 CurTy = CurTy->subtypes()[Index];
4315 else
4316 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00004317 }
4318
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00004319 if (CurTy != Val->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004320 return error("Inserted value type doesn't match aggregate type");
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00004321
Jay Foad57aa6362011-07-13 10:26:04 +00004322 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00004323 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00004324 break;
4325 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004326
Chris Lattnere9759c22007-05-06 00:21:25 +00004327 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00004328 // obsolete form of select
4329 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00004330 unsigned OpNum = 0;
4331 Value *TrueVal, *FalseVal, *Cond;
4332 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004333 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4334 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004335 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004336
Dan Gohmanc5d28922008-09-16 01:01:33 +00004337 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00004338 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00004339 break;
4340 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004341
Dan Gohmanc5d28922008-09-16 01:01:33 +00004342 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4343 // new form of select
4344 // handles select i1 or select [N x i1]
4345 unsigned OpNum = 0;
4346 Value *TrueVal, *FalseVal, *Cond;
4347 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004348 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00004349 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004350 return error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00004351
4352 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00004353 if (VectorType* vector_type =
4354 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00004355 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004356 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004357 return error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00004358 } else {
4359 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004360 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004361 return error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004362 }
4363
Gabor Greife9ecc682008-04-06 20:25:17 +00004364 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00004365 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004366 break;
4367 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004368
Chris Lattner1fc27f02007-05-02 05:16:49 +00004369 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00004370 unsigned OpNum = 0;
4371 Value *Vec, *Idx;
4372 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00004373 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004374 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004375 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004376 return error("Invalid type for value");
Eric Christopherc9742252009-07-25 02:28:41 +00004377 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00004378 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004379 break;
4380 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004381
Chris Lattner1fc27f02007-05-02 05:16:49 +00004382 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00004383 unsigned OpNum = 0;
4384 Value *Vec, *Elt, *Idx;
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004385 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004386 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004387 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004388 return error("Invalid type for value");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004389 if (popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00004390 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00004391 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004392 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00004393 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00004394 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004395 break;
4396 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004397
Chris Lattnere9759c22007-05-06 00:21:25 +00004398 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4399 unsigned OpNum = 0;
4400 Value *Vec1, *Vec2, *Mask;
4401 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004402 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004403 return error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00004404
Mon P Wang25f01062008-11-10 04:46:22 +00004405 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004406 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004407 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004408 return error("Invalid type for value");
Chris Lattner1fc27f02007-05-02 05:16:49 +00004409 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00004410 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004411 break;
4412 }
Mon P Wang25f01062008-11-10 04:46:22 +00004413
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004414 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4415 // Old form of ICmp/FCmp returning bool
4416 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4417 // both legal on vectors but had different behaviour.
4418 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4419 // FCmp/ICmp returning bool or vector of bool
4420
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004421 unsigned OpNum = 0;
4422 Value *LHS, *RHS;
4423 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
James Molloy88eb5352015-07-10 12:52:00 +00004424 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4425 return error("Invalid record");
4426
4427 unsigned PredVal = Record[OpNum];
4428 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4429 FastMathFlags FMF;
4430 if (IsFP && Record.size() > OpNum+1)
4431 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4432
4433 if (OpNum+1 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004434 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004435
Duncan Sands9dff9be2010-02-15 16:12:20 +00004436 if (LHS->getType()->isFPOrFPVectorTy())
James Molloy88eb5352015-07-10 12:52:00 +00004437 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004438 else
James Molloy88eb5352015-07-10 12:52:00 +00004439 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4440
4441 if (FMF.any())
4442 I->setFastMathFlags(FMF);
Devang Patelaf206b82009-09-18 19:26:43 +00004443 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00004444 break;
4445 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004446
Chris Lattnere53603e2007-05-02 04:27:25 +00004447 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00004448 {
4449 unsigned Size = Record.size();
4450 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00004451 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004452 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00004453 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004454 }
Devang Patelbbfd8742008-02-26 01:29:32 +00004455
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004456 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004457 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00004458 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004459 return error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00004460 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004461 return error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004462
Chris Lattnerf1c87102011-06-17 18:09:11 +00004463 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004464 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004465 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00004466 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004467 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00004468 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004469 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004470 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004471 if (!TrueDest)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004472 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004473
Devang Patelaf206b82009-09-18 19:26:43 +00004474 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00004475 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004476 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00004477 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004478 else {
4479 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004480 Value *Cond = getValue(Record, 2, NextValueNo,
4481 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00004482 if (!FalseDest || !Cond)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004483 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00004484 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004485 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004486 }
4487 break;
4488 }
David Majnemerb01aa9f2015-08-23 19:22:31 +00004489 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004490 if (Record.size() != 1 && Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00004491 return error("Invalid record");
4492 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004493 Value *CleanupPad =
4494 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004495 if (!CleanupPad)
David Majnemer654e1302015-07-31 17:58:14 +00004496 return error("Invalid record");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004497 BasicBlock *UnwindDest = nullptr;
4498 if (Record.size() == 2) {
David Majnemer654e1302015-07-31 17:58:14 +00004499 UnwindDest = getBasicBlock(Record[Idx++]);
4500 if (!UnwindDest)
4501 return error("Invalid record");
4502 }
4503
David Majnemer8a1c45d2015-12-12 05:38:55 +00004504 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
David Majnemer654e1302015-07-31 17:58:14 +00004505 InstructionList.push_back(I);
4506 break;
4507 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004508 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4509 if (Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00004510 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004511 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004512 Value *CatchPad =
4513 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004514 if (!CatchPad)
4515 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004516 BasicBlock *BB = getBasicBlock(Record[Idx++]);
David Majnemer654e1302015-07-31 17:58:14 +00004517 if (!BB)
4518 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004519
David Majnemer8a1c45d2015-12-12 05:38:55 +00004520 I = CatchReturnInst::Create(CatchPad, BB);
David Majnemer654e1302015-07-31 17:58:14 +00004521 InstructionList.push_back(I);
4522 break;
4523 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004524 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4525 // We must have, at minimum, the outer scope and the number of arguments.
4526 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00004527 return error("Invalid record");
4528
David Majnemer654e1302015-07-31 17:58:14 +00004529 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004530
4531 Value *ParentPad =
4532 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4533
4534 unsigned NumHandlers = Record[Idx++];
4535
4536 SmallVector<BasicBlock *, 2> Handlers;
4537 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4538 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4539 if (!BB)
David Majnemer654e1302015-07-31 17:58:14 +00004540 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004541 Handlers.push_back(BB);
4542 }
4543
4544 BasicBlock *UnwindDest = nullptr;
4545 if (Idx + 1 == Record.size()) {
David Majnemer654e1302015-07-31 17:58:14 +00004546 UnwindDest = getBasicBlock(Record[Idx++]);
4547 if (!UnwindDest)
4548 return error("Invalid record");
4549 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004550
4551 if (Record.size() != Idx)
4552 return error("Invalid record");
4553
4554 auto *CatchSwitch =
4555 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4556 for (BasicBlock *Handler : Handlers)
4557 CatchSwitch->addHandler(Handler);
4558 I = CatchSwitch;
4559 InstructionList.push_back(I);
4560 break;
4561 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004562 case bitc::FUNC_CODE_INST_CATCHPAD:
4563 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4564 // We must have, at minimum, the outer scope and the number of arguments.
4565 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00004566 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004567
David Majnemer654e1302015-07-31 17:58:14 +00004568 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004569
4570 Value *ParentPad =
4571 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4572
David Majnemer654e1302015-07-31 17:58:14 +00004573 unsigned NumArgOperands = Record[Idx++];
David Majnemer8a1c45d2015-12-12 05:38:55 +00004574
David Majnemer654e1302015-07-31 17:58:14 +00004575 SmallVector<Value *, 2> Args;
4576 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4577 Value *Val;
4578 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4579 return error("Invalid record");
4580 Args.push_back(Val);
4581 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004582
David Majnemer654e1302015-07-31 17:58:14 +00004583 if (Record.size() != Idx)
4584 return error("Invalid record");
4585
David Majnemer8a1c45d2015-12-12 05:38:55 +00004586 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4587 I = CleanupPadInst::Create(ParentPad, Args);
4588 else
4589 I = CatchPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00004590 InstructionList.push_back(I);
4591 break;
4592 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00004593 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004594 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004595 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00004596 // "New" SwitchInst format with case ranges. The changes to write this
4597 // format were reverted but we still recognize bitcode that uses it.
4598 // Hopefully someday we will have support for case ranges and can use
4599 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004600
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004601 Type *OpTy = getTypeByID(Record[1]);
4602 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4603
Jan Wen Voungafaced02012-10-11 20:20:40 +00004604 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004605 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004606 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004607 return error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004608
4609 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004610
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004611 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4612 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004613
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004614 unsigned CurIdx = 5;
4615 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00004616 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004617 unsigned NumItems = Record[CurIdx++];
4618 for (unsigned ci = 0; ci != NumItems; ++ci) {
4619 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004620
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004621 APInt Low;
4622 unsigned ActiveWords = 1;
4623 if (ValueBitWidth > 64)
4624 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004625 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
Benjamin Kramer9704ed02012-05-28 14:10:31 +00004626 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004627 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00004628
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004629 if (!isSingleNumber) {
4630 ActiveWords = 1;
4631 if (ValueBitWidth > 64)
4632 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004633 APInt High = readWideAPInt(
4634 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004635 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00004636
4637 // FIXME: It is not clear whether values in the range should be
4638 // compared as signed or unsigned values. The partially
4639 // implemented changes that used this format in the past used
4640 // unsigned comparisons.
4641 for ( ; Low.ule(High); ++Low)
4642 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004643 } else
Bob Wilsone4077362013-09-09 19:14:35 +00004644 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004645 }
4646 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00004647 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4648 cve = CaseVals.end(); cvi != cve; ++cvi)
4649 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004650 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004651 I = SI;
4652 break;
4653 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004654
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004655 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004656
Chris Lattner5285b5e2007-05-02 05:46:45 +00004657 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004658 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004659 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004660 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004661 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004662 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004663 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004664 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00004665 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00004666 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004667 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004668 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00004669 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4670 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004671 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00004672 delete SI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004673 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004674 }
4675 SI->addCase(CaseVal, DestBB);
4676 }
4677 I = SI;
4678 break;
4679 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004680 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00004681 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004682 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004683 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004684 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00004685 if (!OpTy || !Address)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004686 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004687 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004688 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00004689 InstructionList.push_back(IBI);
4690 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4691 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4692 IBI->addDestination(DestBB);
4693 } else {
4694 delete IBI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004695 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004696 }
4697 }
4698 I = IBI;
4699 break;
4700 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004701
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004702 case bitc::FUNC_CODE_INST_INVOKE: {
4703 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00004704 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004705 return error("Invalid record");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004706 unsigned OpNum = 0;
4707 AttributeSet PAL = getAttributes(Record[OpNum++]);
4708 unsigned CCInfo = Record[OpNum++];
4709 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4710 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004711
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004712 FunctionType *FTy = nullptr;
4713 if (CCInfo >> 13 & 1 &&
4714 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004715 return error("Explicit invoke type is not a function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004716
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004717 Value *Callee;
4718 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004719 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004720
Chris Lattner229907c2011-07-18 04:54:35 +00004721 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004722 if (!CalleeTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004723 return error("Callee is not a pointer");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004724 if (!FTy) {
4725 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4726 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004727 return error("Callee is not of pointer to function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004728 } else if (CalleeTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004729 return error("Explicit invoke type does not match pointee type of "
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004730 "callee operand");
4731 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004732 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004733
Chris Lattner5285b5e2007-05-02 05:46:45 +00004734 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004735 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004736 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4737 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004738 if (!Ops.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004739 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004740 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004741
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004742 if (!FTy->isVarArg()) {
4743 if (Record.size() != OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004744 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004745 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004746 // Read type/value pairs for varargs params.
4747 while (OpNum != Record.size()) {
4748 Value *Op;
4749 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004750 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004751 Ops.push_back(Op);
4752 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004753 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004754
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004755 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4756 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00004757 InstructionList.push_back(I);
Vedant Kumarad6d6e72015-10-27 21:17:06 +00004758 cast<InvokeInst>(I)->setCallingConv(
4759 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00004760 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004761 break;
4762 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00004763 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4764 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004765 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004766 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004767 return error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00004768 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00004769 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004770 break;
4771 }
Chris Lattnere53603e2007-05-02 04:27:25 +00004772 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00004773 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00004774 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004775 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00004776 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00004777 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004778 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004779 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004780 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004781 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004782
Jay Foad52131342011-03-30 11:28:46 +00004783 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00004784 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004785
Chris Lattnere14cb882007-05-04 19:11:41 +00004786 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004787 Value *V;
4788 // With the new function encoding, it is possible that operands have
4789 // negative IDs (for forward references). Use a signed VBR
4790 // representation to keep the encoding small.
4791 if (UseRelativeIDs)
4792 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4793 else
4794 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00004795 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004796 if (!V || !BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004797 return error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00004798 PN->addIncoming(V, BB);
4799 }
4800 I = PN;
4801 break;
4802 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004803
David Majnemer7fddecc2015-06-17 20:52:32 +00004804 case bitc::FUNC_CODE_INST_LANDINGPAD:
4805 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
Bill Wendlingfae14752011-08-12 20:24:12 +00004806 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4807 unsigned Idx = 0;
David Majnemer7fddecc2015-06-17 20:52:32 +00004808 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4809 if (Record.size() < 3)
4810 return error("Invalid record");
4811 } else {
4812 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4813 if (Record.size() < 4)
4814 return error("Invalid record");
4815 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004816 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004817 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004818 return error("Invalid record");
David Majnemer7fddecc2015-06-17 20:52:32 +00004819 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4820 Value *PersFn = nullptr;
4821 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4822 return error("Invalid record");
4823
4824 if (!F->hasPersonalityFn())
4825 F->setPersonalityFn(cast<Constant>(PersFn));
4826 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4827 return error("Personality function mismatch");
4828 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004829
4830 bool IsCleanup = !!Record[Idx++];
4831 unsigned NumClauses = Record[Idx++];
David Majnemer7fddecc2015-06-17 20:52:32 +00004832 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
Bill Wendlingfae14752011-08-12 20:24:12 +00004833 LP->setCleanup(IsCleanup);
4834 for (unsigned J = 0; J != NumClauses; ++J) {
4835 LandingPadInst::ClauseType CT =
4836 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4837 Value *Val;
4838
4839 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4840 delete LP;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004841 return error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00004842 }
4843
4844 assert((CT != LandingPadInst::Catch ||
4845 !isa<ArrayType>(Val->getType())) &&
4846 "Catch clause has a invalid type!");
4847 assert((CT != LandingPadInst::Filter ||
4848 isa<ArrayType>(Val->getType())) &&
4849 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004850 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00004851 }
4852
4853 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00004854 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00004855 break;
4856 }
4857
Chris Lattnerf1c87102011-06-17 18:09:11 +00004858 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4859 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004860 return error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00004861 uint64_t AlignRecord = Record[3];
4862 const uint64_t InAllocaMask = uint64_t(1) << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00004863 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00004864 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4865 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
4866 SwiftErrorMask;
JF Bastien30bf96b2015-02-22 19:32:03 +00004867 bool InAlloca = AlignRecord & InAllocaMask;
Manman Ren9bfd0d02016-04-01 21:41:15 +00004868 bool SwiftError = AlignRecord & SwiftErrorMask;
David Blaikiebdb49102015-04-28 16:51:01 +00004869 Type *Ty = getTypeByID(Record[0]);
4870 if ((AlignRecord & ExplicitTypeMask) == 0) {
4871 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4872 if (!PTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004873 return error("Old-style alloca with a non-pointer type");
David Blaikiebdb49102015-04-28 16:51:01 +00004874 Ty = PTy->getElementType();
4875 }
4876 Type *OpTy = getTypeByID(Record[1]);
4877 Value *Size = getFnValueByID(Record[2], OpTy);
JF Bastien30bf96b2015-02-22 19:32:03 +00004878 unsigned Align;
4879 if (std::error_code EC =
David Blaikiebdb49102015-04-28 16:51:01 +00004880 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
JF Bastien30bf96b2015-02-22 19:32:03 +00004881 return EC;
4882 }
Rafael Espindola48da4f42013-11-04 16:16:24 +00004883 if (!Ty || !Size)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004884 return error("Invalid record");
David Blaikiebdb49102015-04-28 16:51:01 +00004885 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00004886 AI->setUsedWithInAlloca(InAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00004887 AI->setSwiftError(SwiftError);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00004888 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00004889 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00004890 break;
4891 }
Chris Lattner9f600c52007-05-03 22:04:19 +00004892 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004893 unsigned OpNum = 0;
4894 Value *Op;
4895 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004896 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004897 return error("Invalid record");
David Blaikie85035652015-02-25 01:07:20 +00004898
4899 Type *Ty = nullptr;
4900 if (OpNum + 3 == Record.size())
4901 Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004902 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004903 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00004904 if (!Ty)
4905 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004906
JF Bastien30bf96b2015-02-22 19:32:03 +00004907 unsigned Align;
4908 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4909 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00004910 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
David Blaikie85035652015-02-25 01:07:20 +00004911
Devang Patelaf206b82009-09-18 19:26:43 +00004912 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00004913 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00004914 }
Eli Friedman59b66882011-08-09 23:02:53 +00004915 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4916 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4917 unsigned OpNum = 0;
4918 Value *Op;
4919 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004920 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004921 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004922
David Blaikie85035652015-02-25 01:07:20 +00004923 Type *Ty = nullptr;
4924 if (OpNum + 5 == Record.size())
4925 Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004926 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004927 return EC;
4928 if (!Ty)
4929 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004930
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004931 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman59b66882011-08-09 23:02:53 +00004932 if (Ordering == NotAtomic || Ordering == Release ||
4933 Ordering == AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004934 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004935 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004936 return error("Invalid record");
4937 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00004938
JF Bastien30bf96b2015-02-22 19:32:03 +00004939 unsigned Align;
4940 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4941 return EC;
4942 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
David Blaikie85035652015-02-25 01:07:20 +00004943
Eli Friedman59b66882011-08-09 23:02:53 +00004944 InstructionList.push_back(I);
4945 break;
4946 }
David Blaikie612ddbf2015-04-22 04:14:42 +00004947 case bitc::FUNC_CODE_INST_STORE:
4948 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004949 unsigned OpNum = 0;
4950 Value *Val, *Ptr;
4951 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie612ddbf2015-04-22 04:14:42 +00004952 (BitCode == bitc::FUNC_CODE_INST_STORE
4953 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4954 : popValue(Record, OpNum, NextValueNo,
4955 cast<PointerType>(Ptr->getType())->getElementType(),
4956 Val)) ||
4957 OpNum + 2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004958 return error("Invalid record");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004959
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004960 if (std::error_code EC =
4961 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004962 return EC;
JF Bastien30bf96b2015-02-22 19:32:03 +00004963 unsigned Align;
4964 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4965 return EC;
4966 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
Devang Patelaf206b82009-09-18 19:26:43 +00004967 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004968 break;
4969 }
David Blaikie50a06152015-04-22 04:14:46 +00004970 case bitc::FUNC_CODE_INST_STOREATOMIC:
4971 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
Eli Friedman59b66882011-08-09 23:02:53 +00004972 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4973 unsigned OpNum = 0;
4974 Value *Val, *Ptr;
4975 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie50a06152015-04-22 04:14:46 +00004976 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4977 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4978 : popValue(Record, OpNum, NextValueNo,
4979 cast<PointerType>(Ptr->getType())->getElementType(),
4980 Val)) ||
4981 OpNum + 4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004982 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004983
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004984 if (std::error_code EC =
4985 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004986 return EC;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004987 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman222b5a42011-09-19 19:41:28 +00004988 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman59b66882011-08-09 23:02:53 +00004989 Ordering == AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004990 return error("Invalid record");
4991 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00004992 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004993 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004994
JF Bastien30bf96b2015-02-22 19:32:03 +00004995 unsigned Align;
4996 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4997 return EC;
4998 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
Eli Friedman59b66882011-08-09 23:02:53 +00004999 InstructionList.push_back(I);
5000 break;
5001 }
David Blaikie2a661cd2015-04-28 04:30:29 +00005002 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005003 case bitc::FUNC_CODE_INST_CMPXCHG: {
Tim Northovere94a5182014-03-11 10:48:52 +00005004 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
Tim Northover420a2162014-06-13 14:24:07 +00005005 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005006 unsigned OpNum = 0;
5007 Value *Ptr, *Cmp, *New;
5008 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie2a661cd2015-04-28 04:30:29 +00005009 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
5010 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
5011 : popValue(Record, OpNum, NextValueNo,
5012 cast<PointerType>(Ptr->getType())->getElementType(),
5013 Cmp)) ||
5014 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
5015 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005016 return error("Invalid record");
5017 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
Tim Northovere94a5182014-03-11 10:48:52 +00005018 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005019 return error("Invalid record");
5020 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
Tim Northovere94a5182014-03-11 10:48:52 +00005021
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005022 if (std::error_code EC =
5023 typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005024 return EC;
Tim Northovere94a5182014-03-11 10:48:52 +00005025 AtomicOrdering FailureOrdering;
5026 if (Record.size() < 7)
5027 FailureOrdering =
5028 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
5029 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005030 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
Tim Northovere94a5182014-03-11 10:48:52 +00005031
5032 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
5033 SynchScope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005034 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00005035
5036 if (Record.size() < 8) {
5037 // Before weak cmpxchgs existed, the instruction simply returned the
5038 // value loaded from memory, so bitcode files from that era will be
5039 // expecting the first component of a modern cmpxchg.
5040 CurBB->getInstList().push_back(I);
5041 I = ExtractValueInst::Create(I, 0);
5042 } else {
5043 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
5044 }
5045
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005046 InstructionList.push_back(I);
5047 break;
5048 }
5049 case bitc::FUNC_CODE_INST_ATOMICRMW: {
5050 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
5051 unsigned OpNum = 0;
5052 Value *Ptr, *Val;
5053 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00005054 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005055 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
5056 OpNum+4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005057 return error("Invalid record");
5058 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005059 if (Operation < AtomicRMWInst::FIRST_BINOP ||
5060 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005061 return error("Invalid record");
5062 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman59b66882011-08-09 23:02:53 +00005063 if (Ordering == NotAtomic || Ordering == Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005064 return error("Invalid record");
5065 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005066 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
5067 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
5068 InstructionList.push_back(I);
5069 break;
5070 }
Eli Friedmanfee02c62011-07-25 23:16:38 +00005071 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
5072 if (2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005073 return error("Invalid record");
5074 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005075 if (Ordering == NotAtomic || Ordering == Unordered ||
5076 Ordering == Monotonic)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005077 return error("Invalid record");
5078 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005079 I = new FenceInst(Context, Ordering, SynchScope);
5080 InstructionList.push_back(I);
5081 break;
5082 }
Chris Lattnerc44070802011-06-17 18:17:37 +00005083 case bitc::FUNC_CODE_INST_CALL: {
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005084 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00005085 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005086 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005087
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005088 unsigned OpNum = 0;
5089 AttributeSet PAL = getAttributes(Record[OpNum++]);
5090 unsigned CCInfo = Record[OpNum++];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005091
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005092 FastMathFlags FMF;
5093 if ((CCInfo >> bitc::CALL_FMF) & 1) {
5094 FMF = getDecodedFastMathFlags(Record[OpNum++]);
5095 if (!FMF.any())
5096 return error("Fast math flags indicator set for call with no FMF");
5097 }
5098
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005099 FunctionType *FTy = nullptr;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005100 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005101 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005102 return error("Explicit call type is not a function type");
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005103
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005104 Value *Callee;
5105 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005106 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005107
Chris Lattner229907c2011-07-18 04:54:35 +00005108 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005109 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005110 return error("Callee is not a pointer type");
David Blaikie348de692015-04-23 21:36:23 +00005111 if (!FTy) {
5112 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5113 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005114 return error("Callee is not of pointer to function type");
David Blaikie348de692015-04-23 21:36:23 +00005115 } else if (OpTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005116 return error("Explicit call type does not match pointee type of "
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005117 "callee operand");
5118 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005119 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005120
Chris Lattner9f600c52007-05-03 22:04:19 +00005121 SmallVector<Value*, 16> Args;
5122 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005123 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005124 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00005125 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00005126 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00005127 Args.push_back(getValue(Record, OpNum, NextValueNo,
5128 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00005129 if (!Args.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005130 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005131 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005132
Chris Lattner9f600c52007-05-03 22:04:19 +00005133 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00005134 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005135 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005136 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005137 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005138 while (OpNum != Record.size()) {
5139 Value *Op;
5140 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005141 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005142 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00005143 }
5144 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005145
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005146 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5147 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00005148 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00005149 cast<CallInst>(I)->setCallingConv(
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005150 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
Reid Kleckner5772b772014-04-24 20:14:34 +00005151 CallInst::TailCallKind TCK = CallInst::TCK_None;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005152 if (CCInfo & 1 << bitc::CALL_TAIL)
Reid Kleckner5772b772014-04-24 20:14:34 +00005153 TCK = CallInst::TCK_Tail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005154 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
Reid Kleckner5772b772014-04-24 20:14:34 +00005155 TCK = CallInst::TCK_MustTail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005156 if (CCInfo & (1 << bitc::CALL_NOTAIL))
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005157 TCK = CallInst::TCK_NoTail;
Reid Kleckner5772b772014-04-24 20:14:34 +00005158 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00005159 cast<CallInst>(I)->setAttributes(PAL);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005160 if (FMF.any()) {
5161 if (!isa<FPMathOperator>(I))
5162 return error("Fast-math-flags specified for call without "
5163 "floating-point scalar or vector return type");
5164 I->setFastMathFlags(FMF);
5165 }
Chris Lattner9f600c52007-05-03 22:04:19 +00005166 break;
5167 }
5168 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5169 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005170 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00005171 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00005172 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00005173 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00005174 if (!OpTy || !Op || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005175 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005176 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00005177 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00005178 break;
5179 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005180
5181 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5182 // A call or an invoke can be optionally prefixed with some variable
5183 // number of operand bundle blocks. These blocks are read into
5184 // OperandBundles and consumed at the next call or invoke instruction.
5185
5186 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5187 return error("Invalid record");
5188
Sanjoy Dasf79d3442015-11-18 08:30:07 +00005189 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005190
5191 unsigned OpNum = 1;
5192 while (OpNum != Record.size()) {
5193 Value *Op;
5194 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5195 return error("Invalid record");
5196 Inputs.push_back(Op);
5197 }
5198
Sanjoy Dasf79d3442015-11-18 08:30:07 +00005199 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005200 continue;
5201 }
Chris Lattner83930552007-05-01 07:01:57 +00005202 }
5203
5204 // Add instruction to end of current BB. If there is no current BB, reject
5205 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00005206 if (!CurBB) {
Chris Lattner83930552007-05-01 07:01:57 +00005207 delete I;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005208 return error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00005209 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005210 if (!OperandBundles.empty()) {
5211 delete I;
5212 return error("Operand bundles found with no consumer");
5213 }
Chris Lattner83930552007-05-01 07:01:57 +00005214 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005215
Chris Lattner83930552007-05-01 07:01:57 +00005216 // If this was a terminator instruction, move to the next block.
5217 if (isa<TerminatorInst>(I)) {
5218 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00005219 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00005220 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005221
Chris Lattner83930552007-05-01 07:01:57 +00005222 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00005223 if (I && !I->getType()->isVoidTy())
David Majnemer8a1c45d2015-12-12 05:38:55 +00005224 ValueList.assignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00005225 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005226
Chris Lattner27d38752013-01-20 02:13:19 +00005227OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00005228
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005229 if (!OperandBundles.empty())
5230 return error("Operand bundles found with no consumer");
5231
Chris Lattner83930552007-05-01 07:01:57 +00005232 // Check the function list for unresolved values.
5233 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005234 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00005235 // We found at least one unresolved value. Nuke them all to avoid leaks.
5236 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00005237 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00005238 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00005239 delete A;
5240 }
5241 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005242 return error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00005243 }
Chris Lattner83930552007-05-01 07:01:57 +00005244 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005245
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00005246 // Unexpected unresolved metadata about to be dropped.
5247 if (MetadataList.hasFwdRefs())
5248 return error("Invalid function metadata: outgoing forward refs");
Dan Gohman9b9ff462010-08-25 20:23:38 +00005249
Chris Lattner85b7b402007-05-01 05:52:21 +00005250 // Trim the value list down to the size it was before we parsed this function.
5251 ValueList.shrinkTo(ModuleValueListSize);
Teresa Johnson61b406e2015-12-29 23:00:22 +00005252 MetadataList.shrinkTo(ModuleMetadataListSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00005253 std::vector<BasicBlock*>().swap(FunctionBBs);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005254 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00005255}
5256
Rafael Espindola7d712032013-11-05 17:16:08 +00005257/// Find the function body in the bitcode stream
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005258std::error_code BitcodeReader::findFunctionInStream(
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005259 Function *F,
5260 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005261 while (DeferredFunctionInfoIterator->second == 0) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00005262 // This is the fallback handling for the old format bitcode that
Teresa Johnson1493ad92015-10-10 14:18:36 +00005263 // didn't contain the function index in the VST, or when we have
5264 // an anonymous function which would not have a VST entry.
5265 // Assert that we have one of those two cases.
5266 assert(VSTOffset == 0 || !F->hasName());
5267 // Parse the next body in the stream and set its position in the
5268 // DeferredFunctionInfo map.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005269 if (std::error_code EC = rememberAndSkipFunctionBodies())
5270 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005271 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005272 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005273}
5274
Chris Lattner9eeada92007-05-18 04:02:46 +00005275//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005276// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00005277//===----------------------------------------------------------------------===//
5278
Rafael Espindolac3f9b5a2014-06-23 21:53:12 +00005279void BitcodeReader::releaseBuffer() { Buffer.release(); }
Chris Lattner9eeada92007-05-18 04:02:46 +00005280
Rafael Espindola5a52e6d2014-10-24 22:50:48 +00005281std::error_code BitcodeReader::materialize(GlobalValue *GV) {
Duncan P. N. Exon Smith68f56242016-03-25 01:29:50 +00005282 if (std::error_code EC = materializeMetadata())
5283 return EC;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00005284
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005285 Function *F = dyn_cast<Function>(GV);
5286 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005287 if (!F || !F->isMaterializable())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005288 return std::error_code();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005289
5290 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00005291 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005292 // If its position is recorded as 0, its body is somewhere in the stream
5293 // but we haven't seen it yet.
Rafael Espindola1c863ca2015-06-22 18:06:15 +00005294 if (DFII->second == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005295 if (std::error_code EC = findFunctionInStream(F, DFII))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005296 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005297
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005298 // Move the bit stream to the saved position of the deferred function body.
5299 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005300
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005301 if (std::error_code EC = parseFunctionBody(F))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005302 return EC;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00005303 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00005304
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00005305 if (StripDebugInfo)
5306 stripDebugInfo(*F);
5307
Chandler Carruth7132e002007-08-04 01:51:18 +00005308 // Upgrade any old intrinsic calls in the function.
Rafael Espindola86e33402015-07-02 15:55:09 +00005309 for (auto &I : UpgradedIntrinsics) {
Rafael Espindola257a3532016-01-15 19:00:20 +00005310 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5311 UI != UE;) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005312 User *U = *UI;
5313 ++UI;
5314 if (CallInst *CI = dyn_cast<CallInst>(U))
5315 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00005316 }
5317 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005318
Peter Collingbourned4bff302015-11-05 22:03:56 +00005319 // Finish fn->subprogram upgrade for materialized functions.
5320 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5321 F->setSubprogram(SP);
5322
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005323 // Bring in any functions that this function forward-referenced via
5324 // blockaddresses.
5325 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00005326}
5327
Rafael Espindola79753a02015-12-18 21:18:57 +00005328std::error_code BitcodeReader::materializeModule() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00005329 if (std::error_code EC = materializeMetadata())
5330 return EC;
5331
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005332 // Promise to materialize all forward references.
5333 WillMaterializeAllForwardRefs = true;
5334
Chris Lattner06310bf2009-06-16 05:15:21 +00005335 // Iterate over the module, deserializing any functions that are still on
5336 // disk.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00005337 for (Function &F : *TheModule) {
5338 if (std::error_code EC = materialize(&F))
Rafael Espindola246c4fb2014-11-01 16:46:18 +00005339 return EC;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005340 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00005341 // At this point, if there are any function bodies, parse the rest of
5342 // the bits in the module past the last function block we have recorded
5343 // through either lazy scanning or the VST.
5344 if (LastFunctionBlockBit || NextUnreadBit)
5345 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5346 : NextUnreadBit);
Derek Schuff92ef9752012-02-29 00:07:09 +00005347
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005348 // Check that all block address forward references got resolved (as we
5349 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00005350 if (!BasicBlockFwdRefs.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005351 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005352
Chris Bieneman671d0dd2016-03-16 23:17:54 +00005353 // Upgrading intrinsic calls before TBAA can cause TBAA metadata to be lost,
5354 // to prevent this instructions with TBAA tags should be upgraded first.
5355 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5356 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5357
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005358 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5359 // delete the old functions to clean up. We can't do this unless the entire
5360 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00005361 // with calls to the old function.
Rafael Espindola86e33402015-07-02 15:55:09 +00005362 for (auto &I : UpgradedIntrinsics) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005363 for (auto *U : I.first->users()) {
5364 if (CallInst *CI = dyn_cast<CallInst>(U))
5365 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00005366 }
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005367 if (!I.first->use_empty())
5368 I.first->replaceAllUsesWith(I.second);
5369 I.first->eraseFromParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00005370 }
Rafael Espindola4e721212015-07-02 16:22:40 +00005371 UpgradedIntrinsics.clear();
Devang Patel80ae3492009-08-28 23:24:31 +00005372
Rafael Espindola79753a02015-12-18 21:18:57 +00005373 UpgradeDebugInfo(*TheModule);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005374 return std::error_code();
Chris Lattner9eeada92007-05-18 04:02:46 +00005375}
5376
Rafael Espindola2fa1e432014-12-03 07:18:23 +00005377std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5378 return IdentifiedStructTypes;
5379}
5380
Rafael Espindola1aabf982015-06-16 23:29:49 +00005381std::error_code
5382BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
Rafael Espindola4223a1f2015-06-15 20:08:17 +00005383 if (Streamer)
Rafael Espindola1aabf982015-06-16 23:29:49 +00005384 return initLazyStream(std::move(Streamer));
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005385 return initStreamFromBuffer();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005386}
5387
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005388std::error_code BitcodeReader::initStreamFromBuffer() {
Roman Divacky4717a8d2012-09-06 15:42:13 +00005389 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005390 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5391
Rafael Espindola27435252014-07-29 21:01:24 +00005392 if (Buffer->getBufferSize() & 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005393 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005394
5395 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5396 // The magic number is 0x0B17C0DE stored in little endian.
5397 if (isBitcodeWrapper(BufPtr, BufEnd))
5398 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005399 return error("Invalid bitcode wrapper header");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005400
5401 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00005402 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005403
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005404 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005405}
5406
Rafael Espindola1aabf982015-06-16 23:29:49 +00005407std::error_code
5408BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005409 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5410 // see it.
Rafael Espindola1aabf982015-06-16 23:29:49 +00005411 auto OwnedBytes =
5412 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
Rafael Espindola7d727b52014-12-18 05:08:43 +00005413 StreamingMemoryObject &Bytes = *OwnedBytes;
Yaron Keren06d69302014-12-18 10:03:35 +00005414 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00005415 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005416
5417 unsigned char buf[16];
Rafael Espindola7d727b52014-12-18 05:08:43 +00005418 if (Bytes.readBytes(buf, 16, 0) != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005419 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005420
5421 if (!isBitcode(buf, buf + 16))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005422 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005423
5424 if (isBitcodeWrapper(buf, buf + 4)) {
5425 const unsigned char *bitcodeStart = buf;
5426 const unsigned char *bitcodeEnd = buf + 16;
5427 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
Rafael Espindola7d727b52014-12-18 05:08:43 +00005428 Bytes.dropLeadingBytes(bitcodeStart - buf);
5429 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005430 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005431 return std::error_code();
Rafael Espindola48da4f42013-11-04 16:16:24 +00005432}
5433
Teresa Johnson26ab5772016-03-15 00:04:37 +00005434std::error_code ModuleSummaryIndexBitcodeReader::error(BitcodeError E,
5435 const Twine &Message) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005436 return ::error(DiagnosticHandler, make_error_code(E), Message);
5437}
5438
Teresa Johnson26ab5772016-03-15 00:04:37 +00005439std::error_code ModuleSummaryIndexBitcodeReader::error(const Twine &Message) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005440 return ::error(DiagnosticHandler,
5441 make_error_code(BitcodeError::CorruptedBitcode), Message);
5442}
5443
Teresa Johnson26ab5772016-03-15 00:04:37 +00005444std::error_code ModuleSummaryIndexBitcodeReader::error(BitcodeError E) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005445 return ::error(DiagnosticHandler, make_error_code(E));
5446}
5447
Teresa Johnson26ab5772016-03-15 00:04:37 +00005448ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
Mehdi Amini354f5202015-11-19 05:52:29 +00005449 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005450 bool IsLazy, bool CheckGlobalValSummaryPresenceOnly)
Mehdi Amini354f5202015-11-19 05:52:29 +00005451 : DiagnosticHandler(DiagnosticHandler), Buffer(Buffer), IsLazy(IsLazy),
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005452 CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
Teresa Johnson403a7872015-10-04 14:33:43 +00005453
Teresa Johnson26ab5772016-03-15 00:04:37 +00005454ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
Mehdi Amini354f5202015-11-19 05:52:29 +00005455 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005456 bool CheckGlobalValSummaryPresenceOnly)
Mehdi Amini354f5202015-11-19 05:52:29 +00005457 : DiagnosticHandler(DiagnosticHandler), Buffer(nullptr), IsLazy(IsLazy),
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005458 CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
Teresa Johnson403a7872015-10-04 14:33:43 +00005459
Teresa Johnson26ab5772016-03-15 00:04:37 +00005460void ModuleSummaryIndexBitcodeReader::freeState() { Buffer = nullptr; }
Teresa Johnson403a7872015-10-04 14:33:43 +00005461
Teresa Johnson26ab5772016-03-15 00:04:37 +00005462void ModuleSummaryIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
Teresa Johnson403a7872015-10-04 14:33:43 +00005463
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005464GlobalValue::GUID
5465ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005466 auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId);
5467 assert(VGI != ValueIdToCallGraphGUIDMap.end());
5468 return VGI->second;
5469}
5470
5471GlobalValueInfo *
Teresa Johnson26ab5772016-03-15 00:04:37 +00005472ModuleSummaryIndexBitcodeReader::getInfoFromSummaryOffset(uint64_t Offset) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005473 auto I = SummaryOffsetToInfoMap.find(Offset);
5474 assert(I != SummaryOffsetToInfoMap.end());
5475 return I->second;
5476}
5477
5478// Specialized value symbol table parser used when reading module index
Teresa Johnson403a7872015-10-04 14:33:43 +00005479// blocks where we don't actually create global values.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005480// At the end of this routine the module index is populated with a map
5481// from global value name to GlobalValueInfo. The global value info contains
5482// the function block's bitcode offset (if applicable), or the offset into the
5483// summary section for the combined index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005484std::error_code ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005485 uint64_t Offset,
5486 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
5487 assert(Offset > 0 && "Expected non-zero VST offset");
5488 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
5489
Teresa Johnson403a7872015-10-04 14:33:43 +00005490 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5491 return error("Invalid record");
5492
5493 SmallVector<uint64_t, 64> Record;
5494
5495 // Read all the records for this value table.
5496 SmallString<128> ValueName;
5497 while (1) {
5498 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5499
5500 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005501 case BitstreamEntry::SubBlock: // Handled for us already.
5502 case BitstreamEntry::Error:
5503 return error("Malformed block");
5504 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005505 // Done parsing VST, jump back to wherever we came from.
5506 Stream.JumpToBit(CurrentBit);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005507 return std::error_code();
5508 case BitstreamEntry::Record:
5509 // The interesting case.
5510 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005511 }
5512
5513 // Read a record.
5514 Record.clear();
5515 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005516 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5517 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005518 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
5519 if (convertToString(Record, 1, ValueName))
5520 return error("Invalid record");
5521 unsigned ValueID = Record[0];
5522 std::unique_ptr<GlobalValueInfo> GlobalValInfo =
5523 llvm::make_unique<GlobalValueInfo>();
5524 assert(!SourceFileName.empty());
5525 auto VLI = ValueIdToLinkageMap.find(ValueID);
5526 assert(VLI != ValueIdToLinkageMap.end() &&
5527 "No linkage found for VST entry?");
Teresa Johnsonb43027d2016-03-15 02:13:19 +00005528 std::string GlobalId = GlobalValue::getGlobalIdentifier(
5529 ValueName, VLI->second, SourceFileName);
Teresa Johnson916495d2016-04-04 18:52:58 +00005530 auto ValueGUID = GlobalValue::getGUID(GlobalId);
5531 if (PrintSummaryGUIDs)
5532 dbgs() << "GUID " << ValueGUID << " is " << ValueName << "\n";
5533 TheIndex->addGlobalValueInfo(ValueGUID, std::move(GlobalValInfo));
5534 ValueIdToCallGraphGUIDMap[ValueID] = ValueGUID;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005535 ValueName.clear();
5536 break;
5537 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005538 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00005539 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005540 if (convertToString(Record, 2, ValueName))
5541 return error("Invalid record");
5542 unsigned ValueID = Record[0];
5543 uint64_t FuncOffset = Record[1];
Teresa Johnsone1164de2016-02-10 21:55:02 +00005544 assert(!IsLazy && "Lazy summary read only supported for combined index");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005545 std::unique_ptr<GlobalValueInfo> FuncInfo =
5546 llvm::make_unique<GlobalValueInfo>(FuncOffset);
5547 assert(!SourceFileName.empty());
5548 auto VLI = ValueIdToLinkageMap.find(ValueID);
5549 assert(VLI != ValueIdToLinkageMap.end() &&
5550 "No linkage found for VST entry?");
Teresa Johnsonb43027d2016-03-15 02:13:19 +00005551 std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier(
5552 ValueName, VLI->second, SourceFileName);
Teresa Johnson916495d2016-04-04 18:52:58 +00005553 auto FunctionGUID = GlobalValue::getGUID(FunctionGlobalId);
5554 if (PrintSummaryGUIDs)
5555 dbgs() << "GUID " << FunctionGUID << " is " << ValueName << "\n";
5556 TheIndex->addGlobalValueInfo(FunctionGUID, std::move(FuncInfo));
5557 ValueIdToCallGraphGUIDMap[ValueID] = FunctionGUID;
Teresa Johnson403a7872015-10-04 14:33:43 +00005558
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005559 ValueName.clear();
5560 break;
5561 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005562 case bitc::VST_CODE_COMBINED_GVDEFENTRY: {
5563 // VST_CODE_COMBINED_GVDEFENTRY: [valueid, offset, guid]
5564 unsigned ValueID = Record[0];
5565 uint64_t GlobalValSummaryOffset = Record[1];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005566 GlobalValue::GUID GlobalValGUID = Record[2];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005567 std::unique_ptr<GlobalValueInfo> GlobalValInfo =
5568 llvm::make_unique<GlobalValueInfo>(GlobalValSummaryOffset);
5569 SummaryOffsetToInfoMap[GlobalValSummaryOffset] = GlobalValInfo.get();
5570 TheIndex->addGlobalValueInfo(GlobalValGUID, std::move(GlobalValInfo));
5571 ValueIdToCallGraphGUIDMap[ValueID] = GlobalValGUID;
5572 break;
5573 }
5574 case bitc::VST_CODE_COMBINED_ENTRY: {
5575 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
5576 unsigned ValueID = Record[0];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005577 GlobalValue::GUID RefGUID = Record[1];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005578 ValueIdToCallGraphGUIDMap[ValueID] = RefGUID;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005579 break;
5580 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005581 }
5582 }
5583}
5584
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005585// Parse just the blocks needed for building the index out of the module.
5586// At the end of this routine the module Index is populated with a map
5587// from global value name to GlobalValueInfo. The global value info contains
5588// either the parsed summary information (when parsing summaries
5589// eagerly), or just to the summary record's offset
Teresa Johnson403a7872015-10-04 14:33:43 +00005590// if parsing lazily (IsLazy).
Teresa Johnson26ab5772016-03-15 00:04:37 +00005591std::error_code ModuleSummaryIndexBitcodeReader::parseModule() {
Teresa Johnson403a7872015-10-04 14:33:43 +00005592 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5593 return error("Invalid record");
5594
Teresa Johnsone1164de2016-02-10 21:55:02 +00005595 SmallVector<uint64_t, 64> Record;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005596 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
5597 unsigned ValueId = 0;
Teresa Johnsone1164de2016-02-10 21:55:02 +00005598
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005599 // Read the index for this module.
Teresa Johnson403a7872015-10-04 14:33:43 +00005600 while (1) {
5601 BitstreamEntry Entry = Stream.advance();
5602
5603 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005604 case BitstreamEntry::Error:
5605 return error("Malformed block");
5606 case BitstreamEntry::EndBlock:
5607 return std::error_code();
5608
5609 case BitstreamEntry::SubBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005610 if (CheckGlobalValSummaryPresenceOnly) {
5611 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
5612 SeenGlobalValSummary = true;
Teresa Johnson6290dbc2015-11-21 21:55:48 +00005613 // No need to parse the rest since we found the summary.
5614 return std::error_code();
5615 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005616 if (Stream.SkipBlock())
5617 return error("Invalid record");
Teresa Johnson6290dbc2015-11-21 21:55:48 +00005618 continue;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005619 }
5620 switch (Entry.ID) {
5621 default: // Skip unknown content.
5622 if (Stream.SkipBlock())
5623 return error("Invalid record");
5624 break;
5625 case bitc::BLOCKINFO_BLOCK_ID:
5626 // Need to parse these to get abbrev ids (e.g. for VST)
5627 if (Stream.ReadBlockInfoBlock())
5628 return error("Malformed block");
5629 break;
5630 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005631 // Should have been parsed earlier via VSTOffset, unless there
5632 // is no summary section.
5633 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
5634 !SeenGlobalValSummary) &&
5635 "Expected early VST parse via VSTOffset record");
5636 if (Stream.SkipBlock())
5637 return error("Invalid record");
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005638 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005639 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
5640 assert(VSTOffset > 0 && "Expected non-zero VST offset");
5641 assert(!SeenValueSymbolTable &&
5642 "Already read VST when parsing summary block?");
5643 if (std::error_code EC =
5644 parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
5645 return EC;
5646 SeenValueSymbolTable = true;
5647 SeenGlobalValSummary = true;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005648 if (IsLazy) {
5649 // Lazy parsing of summary info, skip it.
5650 if (Stream.SkipBlock())
5651 return error("Invalid record");
5652 } else if (std::error_code EC = parseEntireSummary())
5653 return EC;
5654 break;
5655 case bitc::MODULE_STRTAB_BLOCK_ID:
5656 if (std::error_code EC = parseModuleStringTable())
5657 return EC;
5658 break;
5659 }
5660 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00005661
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005662 case BitstreamEntry::Record: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00005663 Record.clear();
5664 auto BitCode = Stream.readRecord(Entry.ID, Record);
5665 switch (BitCode) {
5666 default:
5667 break; // Default behavior, ignore unknown content.
5668 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005669 case bitc::MODULE_CODE_SOURCE_FILENAME: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00005670 SmallString<128> ValueName;
5671 if (convertToString(Record, 0, ValueName))
5672 return error("Invalid record");
5673 SourceFileName = ValueName.c_str();
5674 break;
5675 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005676 /// MODULE_CODE_HASH: [5*i32]
5677 case bitc::MODULE_CODE_HASH: {
5678 if (Record.size() != 5)
5679 return error("Invalid hash length " + Twine(Record.size()).str());
5680 if (!TheIndex)
5681 break;
5682 if (TheIndex->modulePaths().empty())
5683 // Does not have any summary emitted.
5684 break;
5685 if (TheIndex->modulePaths().size() != 1)
5686 return error("Don't expect multiple modules defined?");
5687 auto &Hash = TheIndex->modulePaths().begin()->second.second;
5688 int Pos = 0;
5689 for (auto &Val : Record) {
5690 assert(!(Val >> 32) && "Unexpected high bits set");
5691 Hash[Pos++] = Val;
5692 }
5693 break;
5694 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005695 /// MODULE_CODE_VSTOFFSET: [offset]
5696 case bitc::MODULE_CODE_VSTOFFSET:
5697 if (Record.size() < 1)
5698 return error("Invalid record");
5699 VSTOffset = Record[0];
5700 break;
5701 // GLOBALVAR: [pointer type, isconst, initid,
5702 // linkage, alignment, section, visibility, threadlocal,
5703 // unnamed_addr, externally_initialized, dllstorageclass,
5704 // comdat]
5705 case bitc::MODULE_CODE_GLOBALVAR: {
5706 if (Record.size() < 6)
5707 return error("Invalid record");
5708 uint64_t RawLinkage = Record[3];
5709 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5710 ValueIdToLinkageMap[ValueId++] = Linkage;
5711 break;
5712 }
5713 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
5714 // alignment, section, visibility, gc, unnamed_addr,
5715 // prologuedata, dllstorageclass, comdat, prefixdata]
5716 case bitc::MODULE_CODE_FUNCTION: {
5717 if (Record.size() < 8)
5718 return error("Invalid record");
5719 uint64_t RawLinkage = Record[3];
5720 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5721 ValueIdToLinkageMap[ValueId++] = Linkage;
5722 break;
5723 }
5724 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
5725 // dllstorageclass]
5726 case bitc::MODULE_CODE_ALIAS: {
5727 if (Record.size() < 6)
5728 return error("Invalid record");
5729 uint64_t RawLinkage = Record[3];
5730 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5731 ValueIdToLinkageMap[ValueId++] = Linkage;
5732 break;
5733 }
5734 }
Teresa Johnsone1164de2016-02-10 21:55:02 +00005735 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005736 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00005737 }
5738 }
5739}
5740
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005741// Eagerly parse the entire summary block. This populates the GlobalValueSummary
5742// objects in the index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005743std::error_code ModuleSummaryIndexBitcodeReader::parseEntireSummary() {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005744 if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID))
Teresa Johnson403a7872015-10-04 14:33:43 +00005745 return error("Invalid record");
5746
5747 SmallVector<uint64_t, 64> Record;
5748
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005749 bool Combined = false;
Teresa Johnson403a7872015-10-04 14:33:43 +00005750 while (1) {
5751 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5752
5753 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005754 case BitstreamEntry::SubBlock: // Handled for us already.
5755 case BitstreamEntry::Error:
5756 return error("Malformed block");
5757 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005758 // For a per-module index, remove any entries that still have empty
5759 // summaries. The VST parsing creates entries eagerly for all symbols,
5760 // but not all have associated summaries (e.g. it doesn't know how to
5761 // distinguish between VST_CODE_ENTRY for function declarations vs global
5762 // variables with initializers that end up with a summary). Remove those
5763 // entries now so that we don't need to rely on the combined index merger
5764 // to clean them up (especially since that may not run for the first
5765 // module's index if we merge into that).
5766 if (!Combined)
5767 TheIndex->removeEmptySummaryEntries();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005768 return std::error_code();
5769 case BitstreamEntry::Record:
5770 // The interesting case.
5771 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005772 }
5773
5774 // Read a record. The record format depends on whether this
5775 // is a per-module index or a combined index file. In the per-module
5776 // case the records contain the associated value's ID for correlation
5777 // with VST entries. In the combined index the correlation is done
5778 // via the bitcode offset of the summary records (which were saved
5779 // in the combined index VST entries). The records also contain
5780 // information used for ThinLTO renaming and importing.
5781 Record.clear();
5782 uint64_t CurRecordBit = Stream.GetCurrentBitNo();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005783 auto BitCode = Stream.readRecord(Entry.ID, Record);
5784 switch (BitCode) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005785 default: // Default behavior: ignore.
5786 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005787 // FS_PERMODULE: [valueid, linkage, instcount, numrefs, numrefs x valueid,
5788 // n x (valueid, callsitecount)]
5789 // FS_PERMODULE_PROFILE: [valueid, linkage, instcount, numrefs,
5790 // numrefs x valueid,
5791 // n x (valueid, callsitecount, profilecount)]
5792 case bitc::FS_PERMODULE:
5793 case bitc::FS_PERMODULE_PROFILE: {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005794 unsigned ValueID = Record[0];
Teresa Johnson5e22e442016-02-06 16:07:35 +00005795 uint64_t RawLinkage = Record[1];
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005796 unsigned InstCount = Record[2];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005797 unsigned NumRefs = Record[3];
5798 std::unique_ptr<FunctionSummary> FS = llvm::make_unique<FunctionSummary>(
5799 getDecodedLinkage(RawLinkage), InstCount);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005800 // The module path string ref set in the summary must be owned by the
5801 // index's module string table. Since we don't have a module path
5802 // string table section in the per-module index, we create a single
5803 // module path string table entry with an empty (0) ID to take
5804 // ownership.
5805 FS->setModulePath(
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005806 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005807 static int RefListStartIndex = 4;
5808 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5809 assert(Record.size() >= RefListStartIndex + NumRefs &&
5810 "Record size inconsistent with number of references");
5811 for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) {
5812 unsigned RefValueId = Record[I];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005813 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005814 FS->addRefEdge(RefGUID);
5815 }
5816 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
5817 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
5818 ++I) {
5819 unsigned CalleeValueId = Record[I];
5820 unsigned CallsiteCount = Record[++I];
5821 uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005822 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005823 FS->addCallGraphEdge(CalleeGUID,
5824 CalleeInfo(CallsiteCount, ProfileCount));
5825 }
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005826 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID);
Teresa Johnsonfb7c7642016-04-05 00:40:16 +00005827 auto *Info = TheIndex->getGlobalValueInfo(GUID);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005828 assert(!Info->summary() && "Expected a single summary per VST entry");
5829 Info->setSummary(std::move(FS));
Teresa Johnsonbbe05452016-02-24 17:57:28 +00005830 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005831 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005832 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, linkage, n x valueid]
5833 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
5834 unsigned ValueID = Record[0];
5835 uint64_t RawLinkage = Record[1];
5836 std::unique_ptr<GlobalVarSummary> FS =
5837 llvm::make_unique<GlobalVarSummary>(getDecodedLinkage(RawLinkage));
5838 FS->setModulePath(
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005839 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005840 for (unsigned I = 2, E = Record.size(); I != E; ++I) {
5841 unsigned RefValueId = Record[I];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005842 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005843 FS->addRefEdge(RefGUID);
5844 }
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005845 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID);
Teresa Johnsonfb7c7642016-04-05 00:40:16 +00005846 auto *Info = TheIndex->getGlobalValueInfo(GUID);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005847 assert(!Info->summary() && "Expected a single summary per VST entry");
5848 Info->setSummary(std::move(FS));
5849 break;
5850 }
5851 // FS_COMBINED: [modid, linkage, instcount, numrefs, numrefs x valueid,
5852 // n x (valueid, callsitecount)]
5853 // FS_COMBINED_PROFILE: [modid, linkage, instcount, numrefs,
5854 // numrefs x valueid,
5855 // n x (valueid, callsitecount, profilecount)]
5856 case bitc::FS_COMBINED:
5857 case bitc::FS_COMBINED_PROFILE: {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005858 uint64_t ModuleId = Record[0];
Teresa Johnson5e22e442016-02-06 16:07:35 +00005859 uint64_t RawLinkage = Record[1];
5860 unsigned InstCount = Record[2];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005861 unsigned NumRefs = Record[3];
5862 std::unique_ptr<FunctionSummary> FS = llvm::make_unique<FunctionSummary>(
5863 getDecodedLinkage(RawLinkage), InstCount);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005864 FS->setModulePath(ModuleIdMap[ModuleId]);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005865 static int RefListStartIndex = 4;
5866 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5867 assert(Record.size() >= RefListStartIndex + NumRefs &&
5868 "Record size inconsistent with number of references");
5869 for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) {
5870 unsigned RefValueId = Record[I];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005871 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005872 FS->addRefEdge(RefGUID);
5873 }
5874 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
5875 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
5876 ++I) {
5877 unsigned CalleeValueId = Record[I];
5878 unsigned CallsiteCount = Record[++I];
5879 uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005880 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005881 FS->addCallGraphEdge(CalleeGUID,
5882 CalleeInfo(CallsiteCount, ProfileCount));
5883 }
5884 auto *Info = getInfoFromSummaryOffset(CurRecordBit);
5885 assert(!Info->summary() && "Expected a single summary per VST entry");
5886 Info->setSummary(std::move(FS));
5887 Combined = true;
5888 break;
5889 }
5890 // FS_COMBINED_GLOBALVAR_INIT_REFS: [modid, linkage, n x valueid]
5891 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
5892 uint64_t ModuleId = Record[0];
5893 uint64_t RawLinkage = Record[1];
5894 std::unique_ptr<GlobalVarSummary> FS =
5895 llvm::make_unique<GlobalVarSummary>(getDecodedLinkage(RawLinkage));
5896 FS->setModulePath(ModuleIdMap[ModuleId]);
5897 for (unsigned I = 2, E = Record.size(); I != E; ++I) {
5898 unsigned RefValueId = Record[I];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005899 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005900 FS->addRefEdge(RefGUID);
5901 }
5902 auto *Info = getInfoFromSummaryOffset(CurRecordBit);
5903 assert(!Info->summary() && "Expected a single summary per VST entry");
5904 Info->setSummary(std::move(FS));
5905 Combined = true;
Teresa Johnsonbbe05452016-02-24 17:57:28 +00005906 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005907 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005908 }
5909 }
5910 llvm_unreachable("Exit infinite loop");
5911}
5912
5913// Parse the module string table block into the Index.
5914// This populates the ModulePathStringTable map in the index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005915std::error_code ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
Teresa Johnson403a7872015-10-04 14:33:43 +00005916 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5917 return error("Invalid record");
5918
5919 SmallVector<uint64_t, 64> Record;
5920
5921 SmallString<128> ModulePath;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005922 ModulePathStringTableTy::iterator LastSeenModulePath;
Teresa Johnson403a7872015-10-04 14:33:43 +00005923 while (1) {
5924 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5925
5926 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005927 case BitstreamEntry::SubBlock: // Handled for us already.
5928 case BitstreamEntry::Error:
5929 return error("Malformed block");
5930 case BitstreamEntry::EndBlock:
5931 return std::error_code();
5932 case BitstreamEntry::Record:
5933 // The interesting case.
5934 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005935 }
5936
5937 Record.clear();
5938 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005939 default: // Default behavior: ignore.
5940 break;
5941 case bitc::MST_CODE_ENTRY: {
5942 // MST_ENTRY: [modid, namechar x N]
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005943 uint64_t ModuleId = Record[0];
5944
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005945 if (convertToString(Record, 1, ModulePath))
5946 return error("Invalid record");
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005947
5948 LastSeenModulePath = TheIndex->addModulePath(ModulePath, ModuleId);
5949 ModuleIdMap[ModuleId] = LastSeenModulePath->first();
5950
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005951 ModulePath.clear();
5952 break;
5953 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005954 /// MST_CODE_HASH: [5*i32]
5955 case bitc::MST_CODE_HASH: {
5956 if (Record.size() != 5)
5957 return error("Invalid hash length " + Twine(Record.size()).str());
5958 if (LastSeenModulePath == TheIndex->modulePaths().end())
5959 return error("Invalid hash that does not follow a module path");
5960 int Pos = 0;
5961 for (auto &Val : Record) {
5962 assert(!(Val >> 32) && "Unexpected high bits set");
5963 LastSeenModulePath->second.second[Pos++] = Val;
5964 }
5965 // Reset LastSeenModulePath to avoid overriding the hash unexpectedly.
5966 LastSeenModulePath = TheIndex->modulePaths().end();
5967 break;
5968 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005969 }
5970 }
5971 llvm_unreachable("Exit infinite loop");
5972}
5973
5974// Parse the function info index from the bitcode streamer into the given index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005975std::error_code ModuleSummaryIndexBitcodeReader::parseSummaryIndexInto(
5976 std::unique_ptr<DataStreamer> Streamer, ModuleSummaryIndex *I) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005977 TheIndex = I;
5978
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005979 if (std::error_code EC = initStream(std::move(Streamer)))
5980 return EC;
Teresa Johnson403a7872015-10-04 14:33:43 +00005981
5982 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005983 if (!hasValidBitcodeHeader(Stream))
5984 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00005985
5986 // We expect a number of well-defined blocks, though we don't necessarily
5987 // need to understand them all.
5988 while (1) {
5989 if (Stream.AtEndOfStream()) {
5990 // We didn't really read a proper Module block.
5991 return error("Malformed block");
5992 }
5993
5994 BitstreamEntry Entry =
5995 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
5996
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005997 if (Entry.Kind != BitstreamEntry::SubBlock)
5998 return error("Malformed block");
Teresa Johnson403a7872015-10-04 14:33:43 +00005999
6000 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
6001 // building the function summary index.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006002 if (Entry.ID == bitc::MODULE_BLOCK_ID)
6003 return parseModule();
Teresa Johnson403a7872015-10-04 14:33:43 +00006004
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006005 if (Stream.SkipBlock())
6006 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00006007 }
6008}
6009
Teresa Johnson26ab5772016-03-15 00:04:37 +00006010// Parse the summary information at the given offset in the buffer into
6011// the index. Used to support lazy parsing of summaries from the
Teresa Johnson403a7872015-10-04 14:33:43 +00006012// combined index during importing.
6013// TODO: This function is not yet complete as it won't have a consumer
6014// until ThinLTO function importing is added.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006015std::error_code ModuleSummaryIndexBitcodeReader::parseGlobalValueSummary(
6016 std::unique_ptr<DataStreamer> Streamer, ModuleSummaryIndex *I,
6017 size_t SummaryOffset) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006018 TheIndex = I;
6019
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006020 if (std::error_code EC = initStream(std::move(Streamer)))
6021 return EC;
Teresa Johnson403a7872015-10-04 14:33:43 +00006022
6023 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006024 if (!hasValidBitcodeHeader(Stream))
6025 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006026
Teresa Johnson26ab5772016-03-15 00:04:37 +00006027 Stream.JumpToBit(SummaryOffset);
Teresa Johnson403a7872015-10-04 14:33:43 +00006028
6029 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6030
6031 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006032 default:
6033 return error("Malformed block");
6034 case BitstreamEntry::Record:
6035 // The expected case.
6036 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00006037 }
6038
6039 // TODO: Read a record. This interface will be completed when ThinLTO
6040 // importing is added so that it can be tested.
6041 SmallVector<uint64_t, 64> Record;
6042 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006043 case bitc::FS_COMBINED:
6044 case bitc::FS_COMBINED_PROFILE:
6045 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006046 default:
6047 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00006048 }
6049
6050 return std::error_code();
6051}
6052
Teresa Johnson26ab5772016-03-15 00:04:37 +00006053std::error_code ModuleSummaryIndexBitcodeReader::initStream(
6054 std::unique_ptr<DataStreamer> Streamer) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006055 if (Streamer)
6056 return initLazyStream(std::move(Streamer));
Teresa Johnson403a7872015-10-04 14:33:43 +00006057 return initStreamFromBuffer();
6058}
6059
Teresa Johnson26ab5772016-03-15 00:04:37 +00006060std::error_code ModuleSummaryIndexBitcodeReader::initStreamFromBuffer() {
Teresa Johnson403a7872015-10-04 14:33:43 +00006061 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
6062 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
6063
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006064 if (Buffer->getBufferSize() & 3)
6065 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006066
6067 // If we have a wrapper header, parse it and ignore the non-bc file contents.
6068 // The magic number is 0x0B17C0DE stored in little endian.
6069 if (isBitcodeWrapper(BufPtr, BufEnd))
6070 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
6071 return error("Invalid bitcode wrapper header");
6072
6073 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
6074 Stream.init(&*StreamFile);
6075
6076 return std::error_code();
6077}
6078
Teresa Johnson26ab5772016-03-15 00:04:37 +00006079std::error_code ModuleSummaryIndexBitcodeReader::initLazyStream(
Teresa Johnson403a7872015-10-04 14:33:43 +00006080 std::unique_ptr<DataStreamer> Streamer) {
6081 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
6082 // see it.
6083 auto OwnedBytes =
6084 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
6085 StreamingMemoryObject &Bytes = *OwnedBytes;
6086 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
6087 Stream.init(&*StreamFile);
6088
6089 unsigned char buf[16];
6090 if (Bytes.readBytes(buf, 16, 0) != 16)
6091 return error("Invalid bitcode signature");
6092
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006093 if (!isBitcode(buf, buf + 16))
6094 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006095
6096 if (isBitcodeWrapper(buf, buf + 4)) {
6097 const unsigned char *bitcodeStart = buf;
6098 const unsigned char *bitcodeEnd = buf + 16;
6099 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
6100 Bytes.dropLeadingBytes(bitcodeStart - buf);
6101 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
6102 }
6103 return std::error_code();
6104}
6105
Rafael Espindola48da4f42013-11-04 16:16:24 +00006106namespace {
Rafael Espindola25188c92014-06-12 01:45:43 +00006107class BitcodeErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +00006108 const char *name() const LLVM_NOEXCEPT override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00006109 return "llvm.bitcode";
6110 }
Craig Topper73156022014-03-02 09:09:27 +00006111 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006112 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00006113 switch (E) {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006114 case BitcodeError::InvalidBitcodeSignature:
Rafael Espindola48da4f42013-11-04 16:16:24 +00006115 return "Invalid bitcode signature";
Rafael Espindolad0b23be2015-01-10 00:07:30 +00006116 case BitcodeError::CorruptedBitcode:
6117 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00006118 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00006119 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00006120 }
6121};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00006122} // end anonymous namespace
Rafael Espindola48da4f42013-11-04 16:16:24 +00006123
Chris Bieneman770163e2014-09-19 20:29:02 +00006124static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
6125
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006126const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00006127 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006128}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00006129
Chris Lattner6694f602007-04-29 07:54:31 +00006130//===----------------------------------------------------------------------===//
6131// External interface
6132//===----------------------------------------------------------------------===//
6133
Rafael Espindola456baad2015-06-17 01:15:47 +00006134static ErrorOr<std::unique_ptr<Module>>
6135getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
6136 BitcodeReader *R, LLVMContext &Context,
6137 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
6138 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
6139 M->setMaterializer(R);
6140
6141 auto cleanupOnError = [&](std::error_code EC) {
6142 R->releaseBuffer(); // Never take ownership on error.
6143 return EC;
6144 };
6145
6146 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
6147 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
6148 ShouldLazyLoadMetadata))
6149 return cleanupOnError(EC);
6150
6151 if (MaterializeAll) {
6152 // Read in the entire module, and destroy the BitcodeReader.
Rafael Espindolac4a03482015-12-18 20:13:39 +00006153 if (std::error_code EC = M->materializeAll())
Rafael Espindola456baad2015-06-17 01:15:47 +00006154 return cleanupOnError(EC);
6155 } else {
6156 // Resolve forward references from blockaddresses.
6157 if (std::error_code EC = R->materializeForwardReferencedFunctions())
6158 return cleanupOnError(EC);
6159 }
6160 return std::move(M);
6161}
6162
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006163/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00006164///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006165/// This isn't always used in a lazy context. In particular, it's also used by
6166/// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
6167/// in forward-referenced functions from block address references.
6168///
Rafael Espindola728074b2015-06-17 00:40:56 +00006169/// \param[in] MaterializeAll Set to \c true if we should materialize
6170/// everything.
Rafael Espindoladcd1dca2015-06-16 22:27:55 +00006171static ErrorOr<std::unique_ptr<Module>>
Rafael Espindola68812152014-09-03 17:31:46 +00006172getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindola728074b2015-06-17 00:40:56 +00006173 LLVMContext &Context, bool MaterializeAll,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00006174 bool ShouldLazyLoadMetadata = false) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006175 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00006176
Rafael Espindola456baad2015-06-17 01:15:47 +00006177 ErrorOr<std::unique_ptr<Module>> Ret =
6178 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
6179 MaterializeAll, ShouldLazyLoadMetadata);
6180 if (!Ret)
6181 return Ret;
Rafael Espindolab7993462012-01-02 07:49:53 +00006182
Rafael Espindolae2c1d772014-08-26 22:00:09 +00006183 Buffer.release(); // The BitcodeReader owns it now.
Rafael Espindola456baad2015-06-17 01:15:47 +00006184 return Ret;
Chris Lattner6694f602007-04-29 07:54:31 +00006185}
6186
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006187ErrorOr<std::unique_ptr<Module>>
6188llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
6189 LLVMContext &Context, bool ShouldLazyLoadMetadata) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00006190 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006191 ShouldLazyLoadMetadata);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006192}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006193
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006194ErrorOr<std::unique_ptr<Module>>
6195llvm::getStreamedBitcodeModule(StringRef Name,
6196 std::unique_ptr<DataStreamer> Streamer,
6197 LLVMContext &Context) {
Rafael Espindola7d727b52014-12-18 05:08:43 +00006198 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006199 BitcodeReader *R = new BitcodeReader(Context);
Rafael Espindola456baad2015-06-17 01:15:47 +00006200
6201 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
6202 false);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006203}
6204
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006205ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
6206 LLVMContext &Context) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00006207 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006208 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
Chad Rosierca2567b2011-12-07 21:44:12 +00006209 // TODO: Restore the use-lists to the in-memory state when the bitcode was
6210 // written. We must defer until the Module has been fully materialized.
Chris Lattner6694f602007-04-29 07:54:31 +00006211}
Bill Wendling0198ce02010-10-06 01:22:42 +00006212
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006213std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
6214 LLVMContext &Context) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00006215 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006216 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00006217 ErrorOr<std::string> Triple = R->parseTriple();
Rafael Espindolad346cc82014-07-04 13:52:01 +00006218 if (Triple.getError())
6219 return "";
6220 return Triple.get();
Bill Wendling0198ce02010-10-06 01:22:42 +00006221}
Teresa Johnson403a7872015-10-04 14:33:43 +00006222
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006223std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
6224 LLVMContext &Context) {
Mehdi Amini3383ccc2015-11-09 02:46:41 +00006225 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006226 BitcodeReader R(Buf.release(), Context);
Mehdi Amini3383ccc2015-11-09 02:46:41 +00006227 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
6228 if (ProducerString.getError())
6229 return "";
6230 return ProducerString.get();
6231}
6232
Teresa Johnson403a7872015-10-04 14:33:43 +00006233// Parse the specified bitcode buffer, returning the function info index.
6234// If IsLazy is false, parse the entire function summary into
6235// the index. Otherwise skip the function summary section, and only create
6236// an index object with a map from function name to function summary offset.
6237// The index is used to perform lazy function summary reading later.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006238ErrorOr<std::unique_ptr<ModuleSummaryIndex>>
6239llvm::getModuleSummaryIndex(MemoryBufferRef Buffer,
6240 DiagnosticHandlerFunction DiagnosticHandler,
6241 bool IsLazy) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006242 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Teresa Johnson26ab5772016-03-15 00:04:37 +00006243 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler, IsLazy);
Teresa Johnson403a7872015-10-04 14:33:43 +00006244
Teresa Johnson26ab5772016-03-15 00:04:37 +00006245 auto Index = llvm::make_unique<ModuleSummaryIndex>();
Teresa Johnson403a7872015-10-04 14:33:43 +00006246
6247 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006248 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00006249 return EC;
6250 };
6251
6252 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
6253 return cleanupOnError(EC);
6254
Teresa Johnson26ab5772016-03-15 00:04:37 +00006255 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
Teresa Johnson403a7872015-10-04 14:33:43 +00006256 return std::move(Index);
6257}
6258
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006259// Check if the given bitcode buffer contains a global value summary block.
6260bool llvm::hasGlobalValueSummary(MemoryBufferRef Buffer,
6261 DiagnosticHandlerFunction DiagnosticHandler) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006262 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Teresa Johnson26ab5772016-03-15 00:04:37 +00006263 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler, false, true);
Teresa Johnson403a7872015-10-04 14:33:43 +00006264
6265 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006266 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00006267 return false;
6268 };
6269
6270 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
6271 return cleanupOnError(EC);
6272
Teresa Johnson26ab5772016-03-15 00:04:37 +00006273 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006274 return R.foundGlobalValSummary();
Teresa Johnson403a7872015-10-04 14:33:43 +00006275}
6276
Teresa Johnson26ab5772016-03-15 00:04:37 +00006277// This method supports lazy reading of summary data from the combined
Teresa Johnson403a7872015-10-04 14:33:43 +00006278// index during ThinLTO function importing. When reading the combined index
Teresa Johnson26ab5772016-03-15 00:04:37 +00006279// file, getModuleSummaryIndex is first invoked with IsLazy=true.
6280// Then this method is called for each value considered for importing,
6281// to parse the summary information for the given value name into
Teresa Johnson403a7872015-10-04 14:33:43 +00006282// the index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006283std::error_code llvm::readGlobalValueSummary(
Mehdi Amini354f5202015-11-19 05:52:29 +00006284 MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson26ab5772016-03-15 00:04:37 +00006285 StringRef ValueName, std::unique_ptr<ModuleSummaryIndex> Index) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006286 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Teresa Johnson26ab5772016-03-15 00:04:37 +00006287 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler);
Teresa Johnson403a7872015-10-04 14:33:43 +00006288
6289 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006290 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00006291 return EC;
6292 };
6293
Teresa Johnson26ab5772016-03-15 00:04:37 +00006294 // Lookup the given value name in the GlobalValueMap, which may
6295 // contain a list of global value infos in the case of a COMDAT. Walk through
6296 // and parse each summary info at the summary offset
Teresa Johnson403a7872015-10-04 14:33:43 +00006297 // recorded when parsing the value symbol table.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006298 for (const auto &FI : Index->getGlobalValueInfoList(ValueName)) {
6299 size_t SummaryOffset = FI->bitcodeIndex();
Teresa Johnson403a7872015-10-04 14:33:43 +00006300 if (std::error_code EC =
Teresa Johnson26ab5772016-03-15 00:04:37 +00006301 R.parseGlobalValueSummary(nullptr, Index.get(), SummaryOffset))
Teresa Johnson403a7872015-10-04 14:33:43 +00006302 return cleanupOnError(EC);
6303 }
6304
Teresa Johnson26ab5772016-03-15 00:04:37 +00006305 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
Teresa Johnson403a7872015-10-04 14:33:43 +00006306 return std::error_code();
6307}