blob: 4689d37b1b81f6d8aa42490fa9f99723c37f1950 [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"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000018#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/Constants.h"
Rafael Espindola0d68b4c2015-03-30 21:36:43 +000020#include "llvm/IR/DebugInfo.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000021#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/DerivedTypes.h"
Rafael Espindolad0b23be2015-01-10 00:07:30 +000023#include "llvm/IR/DiagnosticPrinter.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000024#include "llvm/IR/GVMaterializer.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/InlineAsm.h"
26#include "llvm/IR/IntrinsicInst.h"
Manman Ren209b17c2013-09-28 00:22:27 +000027#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Module.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000029#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/OperandTraits.h"
31#include "llvm/IR/Operator.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000032#include "llvm/IR/ValueHandle.h"
Teresa Johnson916495d2016-04-04 18:52:58 +000033#include "llvm/Support/CommandLine.h"
Derek Schuff8b2dcad2012-02-06 22:30:29 +000034#include "llvm/Support/DataStream.h"
Teresa Johnson916495d2016-04-04 18:52:58 +000035#include "llvm/Support/Debug.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000036#include "llvm/Support/ManagedStatic.h"
Chris Lattner08feb1e2007-04-24 04:04:35 +000037#include "llvm/Support/MathExtras.h"
Chris Lattner6694f602007-04-29 07:54:31 +000038#include "llvm/Support/MemoryBuffer.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000039#include "llvm/Support/raw_ostream.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000040#include <deque>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000041#include <utility>
Eugene Zelenko6ac3f732016-01-26 18:48:36 +000042
Chris Lattner1314b992007-04-22 06:23:29 +000043using namespace llvm;
44
Teresa Johnson916495d2016-04-04 18:52:58 +000045static cl::opt<bool> PrintSummaryGUIDs(
46 "print-summary-global-ids", cl::init(false), cl::Hidden,
47 cl::desc(
48 "Print the global id for each value when reading the module summary"));
49
Benjamin Kramercced8be2015-03-17 20:40:24 +000050namespace {
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +000051enum {
52 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
53};
54
Benjamin Kramercced8be2015-03-17 20:40:24 +000055class BitcodeReaderValueList {
56 std::vector<WeakVH> ValuePtrs;
57
Rafael Espindolacbdcb502015-06-15 20:55:37 +000058 /// As we resolve forward-referenced constants, we add information about them
59 /// to this vector. This allows us to resolve them in bulk instead of
60 /// resolving each reference at a time. See the code in
Benjamin Kramercced8be2015-03-17 20:40:24 +000061 /// ResolveConstantForwardRefs for more information about this.
62 ///
63 /// The key of this vector is the placeholder constant, the value is the slot
64 /// number that holds the resolved value.
65 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
66 ResolveConstantsTy ResolveConstants;
67 LLVMContext &Context;
68public:
69 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
70 ~BitcodeReaderValueList() {
71 assert(ResolveConstants.empty() && "Constants not resolved?");
72 }
73
74 // vector compatibility methods
75 unsigned size() const { return ValuePtrs.size(); }
76 void resize(unsigned N) { ValuePtrs.resize(N); }
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +000077 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
Benjamin Kramercced8be2015-03-17 20:40:24 +000078
79 void clear() {
80 assert(ResolveConstants.empty() && "Constants not resolved?");
81 ValuePtrs.clear();
82 }
83
84 Value *operator[](unsigned i) const {
85 assert(i < ValuePtrs.size());
86 return ValuePtrs[i];
87 }
88
89 Value *back() const { return ValuePtrs.back(); }
Duncan P. N. Exon Smith7457ecb2016-03-30 04:21:52 +000090 void pop_back() { ValuePtrs.pop_back(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +000091 bool empty() const { return ValuePtrs.empty(); }
92 void shrinkTo(unsigned N) {
93 assert(N <= size() && "Invalid shrinkTo request!");
94 ValuePtrs.resize(N);
95 }
96
97 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
David Majnemer8a1c45d2015-12-12 05:38:55 +000098 Value *getValueFwdRef(unsigned Idx, Type *Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +000099
David Majnemer8a1c45d2015-12-12 05:38:55 +0000100 void assignValue(Value *V, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000101
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000102 /// Once all constants are read, this method bulk resolves any forward
103 /// references.
104 void resolveConstantForwardRefs();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000105};
106
Teresa Johnson61b406e2015-12-29 23:00:22 +0000107class BitcodeReaderMetadataList {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000108 unsigned NumFwdRefs;
109 bool AnyFwdRefs;
110 unsigned MinFwdRef;
111 unsigned MaxFwdRef;
Duncan P. N. Exon Smith3c406c22016-04-20 20:14:09 +0000112
113 /// Array of metadata references.
114 ///
115 /// Don't use std::vector here. Some versions of libc++ copy (instead of
116 /// move) on resize, and TrackingMDRef is very expensive to copy.
117 SmallVector<TrackingMDRef, 1> MetadataPtrs;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000118
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000119 /// Structures for resolving old type refs.
120 struct {
121 SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
122 SmallDenseMap<MDString *, DICompositeType *, 1> Final;
123 SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
Duncan P. N. Exon Smith69bdc8a2016-04-23 21:36:59 +0000124 SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000125 } OldTypeRefs;
126
Benjamin Kramercced8be2015-03-17 20:40:24 +0000127 LLVMContext &Context;
128public:
Teresa Johnson61b406e2015-12-29 23:00:22 +0000129 BitcodeReaderMetadataList(LLVMContext &C)
Teresa Johnson34702952015-12-21 15:38:13 +0000130 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
Benjamin Kramercced8be2015-03-17 20:40:24 +0000131
132 // vector compatibility methods
Teresa Johnson61b406e2015-12-29 23:00:22 +0000133 unsigned size() const { return MetadataPtrs.size(); }
134 void resize(unsigned N) { MetadataPtrs.resize(N); }
135 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
136 void clear() { MetadataPtrs.clear(); }
137 Metadata *back() const { return MetadataPtrs.back(); }
138 void pop_back() { MetadataPtrs.pop_back(); }
139 bool empty() const { return MetadataPtrs.empty(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000140
141 Metadata *operator[](unsigned i) const {
Teresa Johnson61b406e2015-12-29 23:00:22 +0000142 assert(i < MetadataPtrs.size());
143 return MetadataPtrs[i];
Benjamin Kramercced8be2015-03-17 20:40:24 +0000144 }
145
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000146 Metadata *lookup(unsigned I) const {
Duncan P. N. Exon Smithe9f85c42016-04-23 04:23:57 +0000147 if (I < MetadataPtrs.size())
148 return MetadataPtrs[I];
149 return nullptr;
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000150 }
151
Benjamin Kramercced8be2015-03-17 20:40:24 +0000152 void shrinkTo(unsigned N) {
153 assert(N <= size() && "Invalid shrinkTo request!");
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +0000154 assert(!AnyFwdRefs && "Unexpected forward refs");
Teresa Johnson61b406e2015-12-29 23:00:22 +0000155 MetadataPtrs.resize(N);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000156 }
157
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000158 /// Return the given metadata, creating a replaceable forward reference if
159 /// necessary.
Justin Bognerae341c62016-03-17 20:12:06 +0000160 Metadata *getMetadataFwdRef(unsigned Idx);
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +0000161
162 /// Return the the given metadata only if it is fully resolved.
163 ///
164 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
165 /// would give \c false.
166 Metadata *getMetadataIfResolved(unsigned Idx);
167
Justin Bognerae341c62016-03-17 20:12:06 +0000168 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000169 void assignValue(Metadata *MD, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000170 void tryToResolveCycles();
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +0000171 bool hasFwdRefs() const { return AnyFwdRefs; }
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000172
173 /// Upgrade a type that had an MDString reference.
174 void addTypeRef(MDString &UUID, DICompositeType &CT);
175
176 /// Upgrade a type that had an MDString reference.
177 Metadata *upgradeTypeRef(Metadata *MaybeUUID);
178
179 /// Upgrade a type ref array that may have MDString references.
180 Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
181
182private:
183 Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000184};
185
186class BitcodeReader : public GVMaterializer {
187 LLVMContext &Context;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000188 Module *TheModule = nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000189 std::unique_ptr<MemoryBuffer> Buffer;
190 std::unique_ptr<BitstreamReader> StreamFile;
191 BitstreamCursor Stream;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000192 // Next offset to start scanning for lazy parsing of function bodies.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000193 uint64_t NextUnreadBit = 0;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000194 // Last function offset found in the VST.
195 uint64_t LastFunctionBlockBit = 0;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000196 bool SeenValueSymbolTable = false;
Peter Collingbourne128a9762015-10-27 23:01:25 +0000197 uint64_t VSTOffset = 0;
Mehdi Amini5d303282015-10-26 18:37:00 +0000198 // Contains an arbitrary and optional string identifying the bitcode producer
199 std::string ProducerIdentification;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000200
201 std::vector<Type*> TypeList;
202 BitcodeReaderValueList ValueList;
Teresa Johnson61b406e2015-12-29 23:00:22 +0000203 BitcodeReaderMetadataList MetadataList;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000204 std::vector<Comdat *> ComdatList;
205 SmallVector<Instruction *, 64> InstructionList;
206
207 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000208 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > IndirectSymbolInits;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000209 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
210 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
David Majnemer7fddecc2015-06-17 20:52:32 +0000211 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000212
213 SmallVector<Instruction*, 64> InstsWithTBAATag;
214
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +0000215 bool HasSeenOldLoopTags = false;
216
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000217 /// The set of attributes by index. Index zero in the file is for null, and
218 /// is thus not represented here. As such all indices are off by one.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000219 std::vector<AttributeSet> MAttributes;
220
Karl Schimpf36440082015-08-31 16:43:55 +0000221 /// The set of attribute groups.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000222 std::map<unsigned, AttributeSet> MAttributeGroups;
223
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000224 /// While parsing a function body, this is a list of the basic blocks for the
225 /// function.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000226 std::vector<BasicBlock*> FunctionBBs;
227
228 // When reading the module header, this list is populated with functions that
229 // have bodies later in the file.
230 std::vector<Function*> FunctionsWithBodies;
231
232 // When intrinsic functions are encountered which require upgrading they are
233 // stored here with their replacement function.
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000234 typedef DenseMap<Function*, Function*> UpdatedIntrinsicMap;
235 UpdatedIntrinsicMap UpgradedIntrinsics;
236 // Intrinsics which were remangled because of types rename
237 UpdatedIntrinsicMap RemangledIntrinsics;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000238
239 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
240 DenseMap<unsigned, unsigned> MDKindMap;
241
242 // Several operations happen after the module header has been read, but
243 // before function bodies are processed. This keeps track of whether
244 // we've done this yet.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000245 bool SeenFirstFunctionBody = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000246
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000247 /// When function bodies are initially scanned, this map contains info about
248 /// where to find deferred function body in the stream.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000249 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
250
251 /// When Metadata block is initially scanned when parsing the module, we may
252 /// choose to defer parsing of the metadata. This vector contains info about
253 /// which Metadata blocks are deferred.
254 std::vector<uint64_t> DeferredMetadataInfo;
255
256 /// These are basic blocks forward-referenced by block addresses. They are
257 /// inserted lazily into functions when they're loaded. The basic block ID is
258 /// its index into the vector.
259 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
260 std::deque<Function *> BasicBlockFwdRefQueue;
261
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000262 /// Indicates that we are using a new encoding for instruction operands where
263 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
264 /// instruction number, for a more compact encoding. Some instruction
265 /// operands are not relative to the instruction ID: basic block numbers, and
266 /// types. Once the old style function blocks have been phased out, we would
Benjamin Kramercced8be2015-03-17 20:40:24 +0000267 /// not need this flag.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000268 bool UseRelativeIDs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000269
270 /// True if all functions will be materialized, negating the need to process
271 /// (e.g.) blockaddress forward references.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000272 bool WillMaterializeAllForwardRefs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000273
Benjamin Kramercced8be2015-03-17 20:40:24 +0000274 /// True if any Metadata block has been materialized.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000275 bool IsMetadataMaterialized = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000276
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000277 bool StripDebugInfo = false;
278
Peter Collingbourned4bff302015-11-05 22:03:56 +0000279 /// Functions that need to be matched with subprograms when upgrading old
280 /// metadata.
281 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
282
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000283 std::vector<std::string> BundleTags;
284
Benjamin Kramercced8be2015-03-17 20:40:24 +0000285public:
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000286 std::error_code error(BitcodeError E, const Twine &Message);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000287 std::error_code error(const Twine &Message);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000288
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000289 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context);
290 BitcodeReader(LLVMContext &Context);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000291 ~BitcodeReader() override { freeState(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000292
293 std::error_code materializeForwardReferencedFunctions();
294
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000295 void freeState();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000296
297 void releaseBuffer();
298
Benjamin Kramercced8be2015-03-17 20:40:24 +0000299 std::error_code materialize(GlobalValue *GV) override;
Rafael Espindola79753a02015-12-18 21:18:57 +0000300 std::error_code materializeModule() override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000301 std::vector<StructType *> getIdentifiedStructTypes() const override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000302
Rafael Espindola6ace6852015-06-15 21:02:49 +0000303 /// \brief Main interface to parsing a bitcode buffer.
304 /// \returns true if an error occurred.
Rafael Espindola1aabf982015-06-16 23:29:49 +0000305 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
306 Module *M,
Benjamin Kramercced8be2015-03-17 20:40:24 +0000307 bool ShouldLazyLoadMetadata = false);
308
Rafael Espindola6ace6852015-06-15 21:02:49 +0000309 /// \brief Cheap mechanism to just extract module triple
310 /// \returns true if an error occurred.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000311 ErrorOr<std::string> parseTriple();
312
Mehdi Amini3383ccc2015-11-09 02:46:41 +0000313 /// Cheap mechanism to just extract the identification block out of bitcode.
314 ErrorOr<std::string> parseIdentificationBlock();
315
Benjamin Kramercced8be2015-03-17 20:40:24 +0000316 static uint64_t decodeSignRotatedValue(uint64_t V);
317
318 /// Materialize any deferred Metadata block.
319 std::error_code materializeMetadata() override;
320
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000321 void setStripDebugInfo() override;
322
Benjamin Kramercced8be2015-03-17 20:40:24 +0000323private:
Mehdi Amini5d303282015-10-26 18:37:00 +0000324 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
325 // ProducerIdentification data member, and do some basic enforcement on the
326 // "epoch" encoded in the bitcode.
327 std::error_code parseBitcodeVersion();
328
Benjamin Kramercced8be2015-03-17 20:40:24 +0000329 std::vector<StructType *> IdentifiedStructTypes;
330 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
331 StructType *createIdentifiedStructType(LLVMContext &Context);
332
333 Type *getTypeByID(unsigned ID);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000334 Value *getFnValueByID(unsigned ID, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000335 if (Ty && Ty->isMetadataTy())
336 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
David Majnemer8a1c45d2015-12-12 05:38:55 +0000337 return ValueList.getValueFwdRef(ID, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000338 }
339 Metadata *getFnMetadataByID(unsigned ID) {
Justin Bognerae341c62016-03-17 20:12:06 +0000340 return MetadataList.getMetadataFwdRef(ID);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000341 }
342 BasicBlock *getBasicBlock(unsigned ID) const {
343 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
344 return FunctionBBs[ID];
345 }
346 AttributeSet getAttributes(unsigned i) const {
347 if (i-1 < MAttributes.size())
348 return MAttributes[i-1];
349 return AttributeSet();
350 }
351
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000352 /// Read a value/type pair out of the specified record from slot 'Slot'.
353 /// Increment Slot past the number of slots used in the record. Return true on
354 /// failure.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000355 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
356 unsigned InstNum, Value *&ResVal) {
357 if (Slot == Record.size()) return true;
358 unsigned ValNo = (unsigned)Record[Slot++];
359 // Adjust the ValNo, if it was encoded relative to the InstNum.
360 if (UseRelativeIDs)
361 ValNo = InstNum - ValNo;
362 if (ValNo < InstNum) {
363 // If this is not a forward reference, just return the value we already
364 // have.
365 ResVal = getFnValueByID(ValNo, nullptr);
366 return ResVal == nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000367 }
David Blaikiedbe6e0f2015-04-17 06:40:14 +0000368 if (Slot == Record.size())
369 return true;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000370
371 unsigned TypeNo = (unsigned)Record[Slot++];
372 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
373 return ResVal == nullptr;
374 }
375
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000376 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
377 /// past the number of slots used by the value in the record. Return true if
378 /// there is an error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000379 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000380 unsigned InstNum, Type *Ty, Value *&ResVal) {
381 if (getValue(Record, Slot, InstNum, Ty, ResVal))
Benjamin Kramercced8be2015-03-17 20:40:24 +0000382 return true;
383 // All values currently take a single record slot.
384 ++Slot;
385 return false;
386 }
387
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000388 /// Like popValue, but does not increment the Slot number.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000389 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000390 unsigned InstNum, Type *Ty, Value *&ResVal) {
391 ResVal = getValue(Record, Slot, InstNum, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000392 return ResVal == nullptr;
393 }
394
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000395 /// Version of getValue that returns ResVal directly, or 0 if there is an
396 /// error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000397 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000398 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000399 if (Slot == Record.size()) return nullptr;
400 unsigned ValNo = (unsigned)Record[Slot];
401 // Adjust the ValNo, if it was encoded relative to the InstNum.
402 if (UseRelativeIDs)
403 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000404 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000405 }
406
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000407 /// Like getValue, but decodes signed VBRs.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000408 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000409 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000410 if (Slot == Record.size()) return nullptr;
411 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
412 // Adjust the ValNo, if it was encoded relative to the InstNum.
413 if (UseRelativeIDs)
414 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000415 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000416 }
417
418 /// Converts alignment exponent (i.e. power of two (or zero)) to the
419 /// corresponding alignment to use. If alignment is too large, returns
420 /// a corresponding error code.
421 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000422 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
Teresa Johnson1493ad92015-10-10 14:18:36 +0000423 std::error_code parseModule(uint64_t ResumeBit,
424 bool ShouldLazyLoadMetadata = false);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000425 std::error_code parseAttributeBlock();
426 std::error_code parseAttributeGroupBlock();
427 std::error_code parseTypeTable();
428 std::error_code parseTypeTableBody();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000429 std::error_code parseOperandBundleTags();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000430
Teresa Johnsonff642b92015-09-17 20:12:00 +0000431 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
432 unsigned NameIndex, Triple &TT);
Peter Collingbourne128a9762015-10-27 23:01:25 +0000433 std::error_code parseValueSymbolTable(uint64_t Offset = 0);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000434 std::error_code parseConstants();
Teresa Johnson1493ad92015-10-10 14:18:36 +0000435 std::error_code rememberAndSkipFunctionBodies();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000436 std::error_code rememberAndSkipFunctionBody();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000437 /// Save the positions of the Metadata blocks and skip parsing the blocks.
438 std::error_code rememberAndSkipMetadata();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000439 std::error_code parseFunctionBody(Function *F);
440 std::error_code globalCleanup();
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000441 std::error_code resolveGlobalAndIndirectSymbolInits();
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +0000442 std::error_code parseMetadata(bool ModuleLevel = false);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +0000443 std::error_code parseMetadataStrings(ArrayRef<uint64_t> Record,
444 StringRef Blob,
445 unsigned &NextMetadataNo);
Teresa Johnson12545072015-11-15 02:00:09 +0000446 std::error_code parseMetadataKinds();
447 std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
Peter Collingbournecceae7f2016-05-31 23:01:54 +0000448 std::error_code
449 parseGlobalObjectAttachment(GlobalObject &GO,
450 ArrayRef<uint64_t> Record);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000451 std::error_code parseMetadataAttachment(Function &F);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000452 ErrorOr<std::string> parseModuleTriple();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000453 std::error_code parseUseLists();
Rafael Espindola1aabf982015-06-16 23:29:49 +0000454 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000455 std::error_code initStreamFromBuffer();
Rafael Espindola1aabf982015-06-16 23:29:49 +0000456 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000457 std::error_code findFunctionInStream(
Benjamin Kramercced8be2015-03-17 20:40:24 +0000458 Function *F,
459 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
460};
Teresa Johnson403a7872015-10-04 14:33:43 +0000461
462/// Class to manage reading and parsing function summary index bitcode
463/// files/sections.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000464class ModuleSummaryIndexBitcodeReader {
Teresa Johnson403a7872015-10-04 14:33:43 +0000465 DiagnosticHandlerFunction DiagnosticHandler;
466
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000467 /// Eventually points to the module index built during parsing.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000468 ModuleSummaryIndex *TheIndex = nullptr;
Teresa Johnson403a7872015-10-04 14:33:43 +0000469
470 std::unique_ptr<MemoryBuffer> Buffer;
471 std::unique_ptr<BitstreamReader> StreamFile;
472 BitstreamCursor Stream;
473
Teresa Johnson403a7872015-10-04 14:33:43 +0000474 /// Used to indicate whether caller only wants to check for the presence
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000475 /// of the global value summary bitcode section. All blocks are skipped,
476 /// but the SeenGlobalValSummary boolean is set.
477 bool CheckGlobalValSummaryPresenceOnly = false;
Teresa Johnson403a7872015-10-04 14:33:43 +0000478
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000479 /// Indicates whether we have encountered a global value summary section
480 /// yet during parsing, used when checking if file contains global value
Teresa Johnson403a7872015-10-04 14:33:43 +0000481 /// summary section.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000482 bool SeenGlobalValSummary = false;
Teresa Johnson403a7872015-10-04 14:33:43 +0000483
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000484 /// Indicates whether we have already parsed the VST, used for error checking.
485 bool SeenValueSymbolTable = false;
486
487 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
488 /// Used to enable on-demand parsing of the VST.
489 uint64_t VSTOffset = 0;
490
491 // Map to save ValueId to GUID association that was recorded in the
492 // ValueSymbolTable. It is used after the VST is parsed to convert
493 // call graph edges read from the function summary from referencing
494 // callees by their ValueId to using the GUID instead, which is how
Teresa Johnson26ab5772016-03-15 00:04:37 +0000495 // they are recorded in the summary index being built.
Mehdi Aminiae64eaf2016-04-23 23:38:17 +0000496 // We save a second GUID which is the same as the first one, but ignoring the
497 // linkage, i.e. for value other than local linkage they are identical.
498 DenseMap<unsigned, std::pair<GlobalValue::GUID, GlobalValue::GUID>>
499 ValueIdToCallGraphGUIDMap;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000500
Teresa Johnson403a7872015-10-04 14:33:43 +0000501 /// Map populated during module path string table parsing, from the
502 /// module ID to a string reference owned by the index's module
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000503 /// path string table, used to correlate with combined index
Teresa Johnson403a7872015-10-04 14:33:43 +0000504 /// summary records.
505 DenseMap<uint64_t, StringRef> ModuleIdMap;
506
Teresa Johnsone1164de2016-02-10 21:55:02 +0000507 /// Original source file name recorded in a bitcode record.
508 std::string SourceFileName;
509
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000510public:
Teresa Johnson403a7872015-10-04 14:33:43 +0000511 std::error_code error(const Twine &Message);
512
Teresa Johnson26ab5772016-03-15 00:04:37 +0000513 ModuleSummaryIndexBitcodeReader(
514 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson6fb3f192016-04-22 01:52:00 +0000515 bool CheckGlobalValSummaryPresenceOnly = false);
Teresa Johnson26ab5772016-03-15 00:04:37 +0000516 ~ModuleSummaryIndexBitcodeReader() { freeState(); }
Teresa Johnson403a7872015-10-04 14:33:43 +0000517
518 void freeState();
519
520 void releaseBuffer();
521
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000522 /// Check if the parser has encountered a summary section.
523 bool foundGlobalValSummary() { return SeenGlobalValSummary; }
Teresa Johnson403a7872015-10-04 14:33:43 +0000524
525 /// \brief Main interface to parsing a bitcode buffer.
526 /// \returns true if an error occurred.
527 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000528 ModuleSummaryIndex *I);
Teresa Johnson403a7872015-10-04 14:33:43 +0000529
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000530private:
Teresa Johnson403a7872015-10-04 14:33:43 +0000531 std::error_code parseModule();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000532 std::error_code parseValueSymbolTable(
533 uint64_t Offset,
534 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
Teresa Johnson403a7872015-10-04 14:33:43 +0000535 std::error_code parseEntireSummary();
536 std::error_code parseModuleStringTable();
537 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
538 std::error_code initStreamFromBuffer();
539 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +0000540 std::pair<GlobalValue::GUID, GlobalValue::GUID>
541 getGUIDFromValueId(unsigned ValueId);
Teresa Johnson403a7872015-10-04 14:33:43 +0000542};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000543} // end anonymous namespace
Benjamin Kramercced8be2015-03-17 20:40:24 +0000544
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000545BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
546 DiagnosticSeverity Severity,
547 const Twine &Msg)
548 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
549
550void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
551
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000552static std::error_code error(const DiagnosticHandlerFunction &DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000553 std::error_code EC, const Twine &Message) {
554 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
555 DiagnosticHandler(DI);
556 return EC;
557}
558
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000559static std::error_code error(LLVMContext &Context, std::error_code EC,
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000560 const Twine &Message) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000561 return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC,
562 Message);
563}
564
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000565static std::error_code error(LLVMContext &Context, const Twine &Message) {
566 return error(Context, make_error_code(BitcodeError::CorruptedBitcode),
567 Message);
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000568}
569
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000570std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
Mehdi Amini5d303282015-10-26 18:37:00 +0000571 if (!ProducerIdentification.empty()) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000572 return ::error(Context, make_error_code(E),
Filipe Cabecinhasf3e167a2015-11-03 13:48:21 +0000573 Message + " (Producer: '" + ProducerIdentification +
574 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
Mehdi Amini5d303282015-10-26 18:37:00 +0000575 }
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000576 return ::error(Context, make_error_code(E), Message);
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000577}
578
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000579std::error_code BitcodeReader::error(const Twine &Message) {
Mehdi Amini5d303282015-10-26 18:37:00 +0000580 if (!ProducerIdentification.empty()) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000581 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
Filipe Cabecinhasf3e167a2015-11-03 13:48:21 +0000582 Message + " (Producer: '" + ProducerIdentification +
583 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
Mehdi Amini5d303282015-10-26 18:37:00 +0000584 }
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000585 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
586 Message);
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000587}
588
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000589BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context)
590 : Context(Context), Buffer(Buffer), ValueList(Context),
Teresa Johnson61b406e2015-12-29 23:00:22 +0000591 MetadataList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000592
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000593BitcodeReader::BitcodeReader(LLVMContext &Context)
594 : Context(Context), Buffer(nullptr), ValueList(Context),
Teresa Johnson61b406e2015-12-29 23:00:22 +0000595 MetadataList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000596
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000597std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
598 if (WillMaterializeAllForwardRefs)
599 return std::error_code();
600
601 // Prevent recursion.
602 WillMaterializeAllForwardRefs = true;
603
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000604 while (!BasicBlockFwdRefQueue.empty()) {
605 Function *F = BasicBlockFwdRefQueue.front();
606 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000607 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000608 if (!BasicBlockFwdRefs.count(F))
609 // Already materialized.
610 continue;
611
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000612 // Check for a function that isn't materializable to prevent an infinite
613 // loop. When parsing a blockaddress stored in a global variable, there
614 // isn't a trivial way to check if a function will have a body without a
615 // linear search through FunctionsWithBodies, so just check it here.
616 if (!F->isMaterializable())
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000617 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000618
619 // Try to materialize F.
Rafael Espindola5a52e6d2014-10-24 22:50:48 +0000620 if (std::error_code EC = materialize(F))
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000621 return EC;
Rafael Espindolab7993462012-01-02 07:49:53 +0000622 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000623 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000624
625 // Reset state.
626 WillMaterializeAllForwardRefs = false;
627 return std::error_code();
Rafael Espindolab7993462012-01-02 07:49:53 +0000628}
629
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000630void BitcodeReader::freeState() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000631 Buffer = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000632 std::vector<Type*>().swap(TypeList);
Chris Lattner9eeada92007-05-18 04:02:46 +0000633 ValueList.clear();
Teresa Johnson61b406e2015-12-29 23:00:22 +0000634 MetadataList.clear();
David Majnemerdad0a642014-06-27 18:19:56 +0000635 std::vector<Comdat *>().swap(ComdatList);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000636
Bill Wendlinge94d8432012-12-07 23:16:57 +0000637 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattner9eeada92007-05-18 04:02:46 +0000638 std::vector<BasicBlock*>().swap(FunctionBBs);
639 std::vector<Function*>().swap(FunctionsWithBodies);
640 DeferredFunctionInfo.clear();
Manman Ren4a9b0eb2015-03-13 19:24:30 +0000641 DeferredMetadataInfo.clear();
Dan Gohman43aa8f02010-07-20 21:42:28 +0000642 MDKindMap.clear();
Benjamin Kramer736a4fc2012-09-21 14:34:31 +0000643
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +0000644 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000645 BasicBlockFwdRefQueue.clear();
Chris Lattner6694f602007-04-29 07:54:31 +0000646}
647
Chris Lattnerfee5a372007-05-04 03:30:17 +0000648//===----------------------------------------------------------------------===//
649// Helper functions to implement forward reference resolution, etc.
650//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +0000651
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000652/// Convert a string from a record into an std::string, return true on failure.
653template <typename StrTy>
654static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattnerccaa4482007-04-23 21:26:05 +0000655 StrTy &Result) {
Chris Lattnere14cb882007-05-04 19:11:41 +0000656 if (Idx > Record.size())
Chris Lattner1314b992007-04-22 06:23:29 +0000657 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000658
Chris Lattnere14cb882007-05-04 19:11:41 +0000659 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
660 Result += (char)Record[i];
Chris Lattner1314b992007-04-22 06:23:29 +0000661 return false;
662}
663
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000664static bool hasImplicitComdat(size_t Val) {
665 switch (Val) {
666 default:
667 return false;
668 case 1: // Old WeakAnyLinkage
669 case 4: // Old LinkOnceAnyLinkage
670 case 10: // Old WeakODRLinkage
671 case 11: // Old LinkOnceODRLinkage
672 return true;
673 }
674}
675
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000676static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000677 switch (Val) {
678 default: // Map unknown/new linkages to external
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000679 case 0:
680 return GlobalValue::ExternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000681 case 2:
682 return GlobalValue::AppendingLinkage;
683 case 3:
684 return GlobalValue::InternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000685 case 5:
686 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
687 case 6:
688 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
689 case 7:
690 return GlobalValue::ExternalWeakLinkage;
691 case 8:
692 return GlobalValue::CommonLinkage;
693 case 9:
694 return GlobalValue::PrivateLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000695 case 12:
696 return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000697 case 13:
698 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
699 case 14:
700 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Rafael Espindolabec6af62015-01-08 15:39:50 +0000701 case 15:
702 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000703 case 1: // Old value with implicit comdat.
704 case 16:
705 return GlobalValue::WeakAnyLinkage;
706 case 10: // Old value with implicit comdat.
707 case 17:
708 return GlobalValue::WeakODRLinkage;
709 case 4: // Old value with implicit comdat.
710 case 18:
711 return GlobalValue::LinkOnceAnyLinkage;
712 case 11: // Old value with implicit comdat.
713 case 19:
714 return GlobalValue::LinkOnceODRLinkage;
Chris Lattner1314b992007-04-22 06:23:29 +0000715 }
716}
717
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000718// Decode the flags for GlobalValue in the summary
719static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
720 uint64_t Version) {
721 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
722 // like getDecodedLinkage() above. Any future change to the linkage enum and
723 // to getDecodedLinkage() will need to be taken into account here as above.
724 auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
Mehdi Aminica2c54e2016-04-24 05:31:43 +0000725 RawFlags = RawFlags >> 4;
726 auto HasSection = RawFlags & 0x1; // bool
727 return GlobalValueSummary::GVFlags(Linkage, HasSection);
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000728}
729
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000730static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000731 switch (Val) {
732 default: // Map unknown visibilities to default.
733 case 0: return GlobalValue::DefaultVisibility;
734 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000735 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000736 }
737}
738
Nico Rieck7157bb72014-01-14 15:22:47 +0000739static GlobalValue::DLLStorageClassTypes
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000740getDecodedDLLStorageClass(unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000741 switch (Val) {
742 default: // Map unknown values to default.
743 case 0: return GlobalValue::DefaultStorageClass;
744 case 1: return GlobalValue::DLLImportStorageClass;
745 case 2: return GlobalValue::DLLExportStorageClass;
746 }
747}
748
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000749static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000750 switch (Val) {
751 case 0: return GlobalVariable::NotThreadLocal;
752 default: // Map unknown non-zero value to general dynamic.
753 case 1: return GlobalVariable::GeneralDynamicTLSModel;
754 case 2: return GlobalVariable::LocalDynamicTLSModel;
755 case 3: return GlobalVariable::InitialExecTLSModel;
756 case 4: return GlobalVariable::LocalExecTLSModel;
757 }
758}
759
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000760static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
761 switch (Val) {
762 default: // Map unknown to UnnamedAddr::None.
763 case 0: return GlobalVariable::UnnamedAddr::None;
764 case 1: return GlobalVariable::UnnamedAddr::Global;
765 case 2: return GlobalVariable::UnnamedAddr::Local;
766 }
767}
768
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000769static int getDecodedCastOpcode(unsigned Val) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000770 switch (Val) {
771 default: return -1;
772 case bitc::CAST_TRUNC : return Instruction::Trunc;
773 case bitc::CAST_ZEXT : return Instruction::ZExt;
774 case bitc::CAST_SEXT : return Instruction::SExt;
775 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
776 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
777 case bitc::CAST_UITOFP : return Instruction::UIToFP;
778 case bitc::CAST_SITOFP : return Instruction::SIToFP;
779 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
780 case bitc::CAST_FPEXT : return Instruction::FPExt;
781 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
782 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
783 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000784 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000785 }
786}
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000787
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000788static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000789 bool IsFP = Ty->isFPOrFPVectorTy();
790 // BinOps are only valid for int/fp or vector of int/fp types
791 if (!IsFP && !Ty->isIntOrIntVectorTy())
792 return -1;
793
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000794 switch (Val) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000795 default:
796 return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000797 case bitc::BINOP_ADD:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000798 return IsFP ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000799 case bitc::BINOP_SUB:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000800 return IsFP ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000801 case bitc::BINOP_MUL:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000802 return IsFP ? Instruction::FMul : Instruction::Mul;
803 case bitc::BINOP_UDIV:
804 return IsFP ? -1 : Instruction::UDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000805 case bitc::BINOP_SDIV:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000806 return IsFP ? Instruction::FDiv : Instruction::SDiv;
807 case bitc::BINOP_UREM:
808 return IsFP ? -1 : Instruction::URem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000809 case bitc::BINOP_SREM:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000810 return IsFP ? Instruction::FRem : Instruction::SRem;
811 case bitc::BINOP_SHL:
812 return IsFP ? -1 : Instruction::Shl;
813 case bitc::BINOP_LSHR:
814 return IsFP ? -1 : Instruction::LShr;
815 case bitc::BINOP_ASHR:
816 return IsFP ? -1 : Instruction::AShr;
817 case bitc::BINOP_AND:
818 return IsFP ? -1 : Instruction::And;
819 case bitc::BINOP_OR:
820 return IsFP ? -1 : Instruction::Or;
821 case bitc::BINOP_XOR:
822 return IsFP ? -1 : Instruction::Xor;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000823 }
824}
825
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000826static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000827 switch (Val) {
828 default: return AtomicRMWInst::BAD_BINOP;
829 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
830 case bitc::RMW_ADD: return AtomicRMWInst::Add;
831 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
832 case bitc::RMW_AND: return AtomicRMWInst::And;
833 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
834 case bitc::RMW_OR: return AtomicRMWInst::Or;
835 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
836 case bitc::RMW_MAX: return AtomicRMWInst::Max;
837 case bitc::RMW_MIN: return AtomicRMWInst::Min;
838 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
839 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
840 }
841}
842
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000843static AtomicOrdering getDecodedOrdering(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000844 switch (Val) {
JF Bastien800f87a2016-04-06 21:19:33 +0000845 case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
846 case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
847 case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
848 case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
849 case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
850 case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000851 default: // Map unknown orderings to sequentially-consistent.
JF Bastien800f87a2016-04-06 21:19:33 +0000852 case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
Eli Friedmanfee02c62011-07-25 23:16:38 +0000853 }
854}
855
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000856static SynchronizationScope getDecodedSynchScope(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000857 switch (Val) {
858 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
859 default: // Map unknown scopes to cross-thread.
860 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
861 }
862}
863
David Majnemerdad0a642014-06-27 18:19:56 +0000864static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
865 switch (Val) {
866 default: // Map unknown selection kinds to any.
867 case bitc::COMDAT_SELECTION_KIND_ANY:
868 return Comdat::Any;
869 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
870 return Comdat::ExactMatch;
871 case bitc::COMDAT_SELECTION_KIND_LARGEST:
872 return Comdat::Largest;
873 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
874 return Comdat::NoDuplicates;
875 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
876 return Comdat::SameSize;
877 }
878}
879
James Molloy88eb5352015-07-10 12:52:00 +0000880static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
881 FastMathFlags FMF;
882 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
883 FMF.setUnsafeAlgebra();
884 if (0 != (Val & FastMathFlags::NoNaNs))
885 FMF.setNoNaNs();
886 if (0 != (Val & FastMathFlags::NoInfs))
887 FMF.setNoInfs();
888 if (0 != (Val & FastMathFlags::NoSignedZeros))
889 FMF.setNoSignedZeros();
890 if (0 != (Val & FastMathFlags::AllowReciprocal))
891 FMF.setAllowReciprocal();
892 return FMF;
893}
894
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000895static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000896 switch (Val) {
897 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
898 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
899 }
900}
901
Gabor Greiff6caff662008-05-10 08:32:32 +0000902namespace llvm {
Chris Lattner1663cca2007-04-24 05:48:56 +0000903namespace {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000904/// \brief A class for maintaining the slot number definition
905/// as a placeholder for the actual definition for forward constants defs.
906class ConstantPlaceHolder : public ConstantExpr {
907 void operator=(const ConstantPlaceHolder &) = delete;
908
909public:
910 // allocate space for exactly one operand
911 void *operator new(size_t s) { return User::operator new(s, 1); }
912 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
Gabor Greiff6caff662008-05-10 08:32:32 +0000913 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000914 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
915 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000916
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000917 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
918 static bool classof(const Value *V) {
919 return isa<ConstantExpr>(V) &&
920 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
921 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000922
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000923 /// Provide fast operand accessors
924 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
925};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000926} // end anonymous namespace
Chris Lattner1663cca2007-04-24 05:48:56 +0000927
Chris Lattner2d8cd802009-03-31 22:55:09 +0000928// FIXME: can we inherit this from ConstantExpr?
Gabor Greiff6caff662008-05-10 08:32:32 +0000929template <>
Jay Foadc8adf5f2011-01-11 15:07:38 +0000930struct OperandTraits<ConstantPlaceHolder> :
931 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greiff6caff662008-05-10 08:32:32 +0000932};
Richard Trieue3d126c2014-11-21 02:42:08 +0000933DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000934} // end namespace llvm
Gabor Greiff6caff662008-05-10 08:32:32 +0000935
David Majnemer8a1c45d2015-12-12 05:38:55 +0000936void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000937 if (Idx == size()) {
938 push_back(V);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000939 return;
Chris Lattner2d8cd802009-03-31 22:55:09 +0000940 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000941
Chris Lattner2d8cd802009-03-31 22:55:09 +0000942 if (Idx >= size())
943 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000944
Chris Lattner2d8cd802009-03-31 22:55:09 +0000945 WeakVH &OldV = ValuePtrs[Idx];
Craig Topper2617dcc2014-04-15 06:32:26 +0000946 if (!OldV) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000947 OldV = V;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000948 return;
Chris Lattner2d8cd802009-03-31 22:55:09 +0000949 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000950
Chris Lattner2d8cd802009-03-31 22:55:09 +0000951 // Handle constants and non-constants (e.g. instrs) differently for
952 // efficiency.
953 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
954 ResolveConstants.push_back(std::make_pair(PHC, Idx));
955 OldV = V;
956 } else {
957 // If there was a forward reference to this value, replace it.
958 Value *PrevVal = OldV;
959 OldV->replaceAllUsesWith(V);
960 delete PrevVal;
Gabor Greiff6caff662008-05-10 08:32:32 +0000961 }
962}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000963
Chris Lattner1663cca2007-04-24 05:48:56 +0000964Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattner229907c2011-07-18 04:54:35 +0000965 Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000966 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000967 resize(Idx + 1);
Chris Lattner1663cca2007-04-24 05:48:56 +0000968
Chris Lattner2d8cd802009-03-31 22:55:09 +0000969 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhas6a92a3f2015-05-27 01:05:40 +0000970 if (Ty != V->getType())
971 report_fatal_error("Type mismatch in constant table!");
Chris Lattner83930552007-05-01 07:01:57 +0000972 return cast<Constant>(V);
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000973 }
Chris Lattner1663cca2007-04-24 05:48:56 +0000974
975 // Create and return a placeholder, which will later be RAUW'd.
Owen Andersone9f98042009-07-07 20:18:58 +0000976 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000977 ValuePtrs[Idx] = C;
Chris Lattner1663cca2007-04-24 05:48:56 +0000978 return C;
979}
980
David Majnemer8a1c45d2015-12-12 05:38:55 +0000981Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Filipe Cabecinhasbad07792015-04-30 00:52:42 +0000982 // Bail out for a clearly invalid value. This would make us call resize(0)
983 if (Idx == UINT_MAX)
984 return nullptr;
985
Chris Lattner2d8cd802009-03-31 22:55:09 +0000986 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000987 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000988
Chris Lattner2d8cd802009-03-31 22:55:09 +0000989 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhasb435d0f2015-04-28 20:18:47 +0000990 // If the types don't match, it's invalid.
991 if (Ty && Ty != V->getType())
992 return nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000993 return V;
Chris Lattner83930552007-05-01 07:01:57 +0000994 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000995
Chris Lattner1fc27f02007-05-02 05:16:49 +0000996 // No type specified, must be invalid reference.
Craig Topper2617dcc2014-04-15 06:32:26 +0000997 if (!Ty) return nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000998
Chris Lattner83930552007-05-01 07:01:57 +0000999 // Create and return a placeholder, which will later be RAUW'd.
David Majnemer8a1c45d2015-12-12 05:38:55 +00001000 Value *V = new Argument(Ty);
Chris Lattner2d8cd802009-03-31 22:55:09 +00001001 ValuePtrs[Idx] = V;
Chris Lattner83930552007-05-01 07:01:57 +00001002 return V;
1003}
1004
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001005/// Once all constants are read, this method bulk resolves any forward
1006/// references. The idea behind this is that we sometimes get constants (such
1007/// as large arrays) which reference *many* forward ref constants. Replacing
1008/// each of these causes a lot of thrashing when building/reuniquing the
1009/// constant. Instead of doing this, we look at all the uses and rewrite all
1010/// the place holders at once for any constant that uses a placeholder.
1011void BitcodeReaderValueList::resolveConstantForwardRefs() {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001012 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattner74429932008-08-21 02:34:16 +00001013 // binary search.
1014 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001015
Chris Lattner74429932008-08-21 02:34:16 +00001016 SmallVector<Constant*, 64> NewOps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001017
Chris Lattner74429932008-08-21 02:34:16 +00001018 while (!ResolveConstants.empty()) {
Chris Lattner2d8cd802009-03-31 22:55:09 +00001019 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattner74429932008-08-21 02:34:16 +00001020 Constant *Placeholder = ResolveConstants.back().first;
1021 ResolveConstants.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001022
Chris Lattner74429932008-08-21 02:34:16 +00001023 // Loop over all users of the placeholder, updating them to reference the
1024 // new value. If they reference more than one placeholder, update them all
1025 // at once.
1026 while (!Placeholder->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001027 auto UI = Placeholder->user_begin();
Gabor Greif2c0ab482010-07-09 16:01:21 +00001028 User *U = *UI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001029
Chris Lattner74429932008-08-21 02:34:16 +00001030 // If the using object isn't uniqued, just update the operands. This
1031 // handles instructions and initializers for global variables.
Gabor Greif2c0ab482010-07-09 16:01:21 +00001032 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattner479c5d92008-08-21 17:31:45 +00001033 UI.getUse().set(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +00001034 continue;
1035 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001036
Chris Lattner74429932008-08-21 02:34:16 +00001037 // Otherwise, we have a constant that uses the placeholder. Replace that
1038 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greif2c0ab482010-07-09 16:01:21 +00001039 Constant *UserC = cast<Constant>(U);
Chris Lattner74429932008-08-21 02:34:16 +00001040 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
1041 I != E; ++I) {
1042 Value *NewOp;
1043 if (!isa<ConstantPlaceHolder>(*I)) {
1044 // Not a placeholder reference.
1045 NewOp = *I;
1046 } else if (*I == Placeholder) {
1047 // Common case is that it just references this one placeholder.
1048 NewOp = RealVal;
1049 } else {
1050 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001051 ResolveConstantsTy::iterator It =
1052 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattner74429932008-08-21 02:34:16 +00001053 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1054 0));
1055 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner2d8cd802009-03-31 22:55:09 +00001056 NewOp = operator[](It->second);
Chris Lattner74429932008-08-21 02:34:16 +00001057 }
1058
1059 NewOps.push_back(cast<Constant>(NewOp));
1060 }
1061
1062 // Make the new constant.
1063 Constant *NewC;
1064 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad83be3612011-06-22 09:24:39 +00001065 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001066 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnercc19efa2011-06-20 04:01:31 +00001067 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001068 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner69229312011-02-15 00:14:00 +00001069 NewC = ConstantVector::get(NewOps);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001070 } else {
1071 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foad5c984e562011-04-13 13:46:01 +00001072 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001073 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001074
Chris Lattner74429932008-08-21 02:34:16 +00001075 UserC->replaceAllUsesWith(NewC);
1076 UserC->destroyConstant();
1077 NewOps.clear();
1078 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001079
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001080 // Update all ValueHandles, they should be the only users at this point.
1081 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +00001082 delete Placeholder;
1083 }
1084}
1085
Teresa Johnson61b406e2015-12-29 23:00:22 +00001086void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +00001087 if (Idx == size()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001088 push_back(MD);
Devang Patel05eb6172009-08-04 06:00:18 +00001089 return;
1090 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001091
Devang Patel05eb6172009-08-04 06:00:18 +00001092 if (Idx >= size())
1093 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001094
Teresa Johnson61b406e2015-12-29 23:00:22 +00001095 TrackingMDRef &OldMD = MetadataPtrs[Idx];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001096 if (!OldMD) {
1097 OldMD.reset(MD);
Devang Patel05eb6172009-08-04 06:00:18 +00001098 return;
1099 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001100
Devang Patel05eb6172009-08-04 06:00:18 +00001101 // If there was a forward reference to this value, replace it.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +00001102 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001103 PrevMD->replaceAllUsesWith(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001104 --NumFwdRefs;
Devang Patel05eb6172009-08-04 06:00:18 +00001105}
1106
Justin Bognerae341c62016-03-17 20:12:06 +00001107Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +00001108 if (Idx >= size())
1109 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001110
Teresa Johnson61b406e2015-12-29 23:00:22 +00001111 if (Metadata *MD = MetadataPtrs[Idx])
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001112 return MD;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001113
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001114 // Track forward refs to be resolved later.
1115 if (AnyFwdRefs) {
1116 MinFwdRef = std::min(MinFwdRef, Idx);
1117 MaxFwdRef = std::max(MaxFwdRef, Idx);
1118 } else {
1119 AnyFwdRefs = true;
1120 MinFwdRef = MaxFwdRef = Idx;
1121 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001122 ++NumFwdRefs;
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001123
1124 // Create and return a placeholder, which will later be RAUW'd.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +00001125 Metadata *MD = MDNode::getTemporary(Context, None).release();
Teresa Johnson61b406e2015-12-29 23:00:22 +00001126 MetadataPtrs[Idx].reset(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001127 return MD;
1128}
1129
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00001130Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
1131 Metadata *MD = lookup(Idx);
1132 if (auto *N = dyn_cast_or_null<MDNode>(MD))
1133 if (!N->isResolved())
1134 return nullptr;
1135 return MD;
1136}
1137
Justin Bognerae341c62016-03-17 20:12:06 +00001138MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
1139 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
1140}
1141
Teresa Johnson61b406e2015-12-29 23:00:22 +00001142void BitcodeReaderMetadataList::tryToResolveCycles() {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001143 if (NumFwdRefs)
1144 // Still forward references... can't resolve cycles.
1145 return;
1146
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00001147 bool DidReplaceTypeRefs = false;
1148
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001149 // Give up on finding a full definition for any forward decls that remain.
1150 for (const auto &Ref : OldTypeRefs.FwdDecls)
1151 OldTypeRefs.Final.insert(Ref);
1152 OldTypeRefs.FwdDecls.clear();
1153
1154 // Upgrade from old type ref arrays. In strange cases, this could add to
1155 // OldTypeRefs.Unknown.
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00001156 for (const auto &Array : OldTypeRefs.Arrays) {
1157 DidReplaceTypeRefs = true;
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001158 Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00001159 }
1160 OldTypeRefs.Arrays.clear();
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001161
1162 // Replace old string-based type refs with the resolved node, if possible.
1163 // If we haven't seen the node, leave it to the verifier to complain about
1164 // the invalid string reference.
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00001165 for (const auto &Ref : OldTypeRefs.Unknown) {
1166 DidReplaceTypeRefs = true;
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001167 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
1168 Ref.second->replaceAllUsesWith(CT);
1169 else
1170 Ref.second->replaceAllUsesWith(Ref.first);
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00001171 }
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001172 OldTypeRefs.Unknown.clear();
1173
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00001174 // Make sure all the upgraded types are resolved.
1175 if (DidReplaceTypeRefs) {
1176 AnyFwdRefs = true;
1177 MinFwdRef = 0;
1178 MaxFwdRef = MetadataPtrs.size() - 1;
1179 }
1180
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001181 if (!AnyFwdRefs)
1182 // Nothing to do.
1183 return;
1184
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001185 // Resolve any cycles.
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001186 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
Teresa Johnson61b406e2015-12-29 23:00:22 +00001187 auto &MD = MetadataPtrs[I];
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +00001188 auto *N = dyn_cast_or_null<MDNode>(MD);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +00001189 if (!N)
1190 continue;
1191
1192 assert(!N->isTemporary() && "Unexpected forward reference");
1193 N->resolveCycles();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001194 }
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001195
1196 // Make sure we return early again until there's another forward ref.
1197 AnyFwdRefs = false;
Devang Patel05eb6172009-08-04 06:00:18 +00001198}
Chris Lattner1314b992007-04-22 06:23:29 +00001199
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001200void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
1201 DICompositeType &CT) {
1202 assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
1203 if (CT.isForwardDecl())
1204 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
1205 else
1206 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
1207}
1208
1209Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
1210 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
1211 if (LLVM_LIKELY(!UUID))
1212 return MaybeUUID;
1213
1214 if (auto *CT = OldTypeRefs.Final.lookup(UUID))
1215 return CT;
1216
1217 auto &Ref = OldTypeRefs.Unknown[UUID];
1218 if (!Ref)
1219 Ref = MDNode::getTemporary(Context, None);
1220 return Ref.get();
1221}
1222
1223Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
1224 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
1225 if (!Tuple || Tuple->isDistinct())
1226 return MaybeTuple;
1227
1228 // Look through the array immediately if possible.
1229 if (!Tuple->isTemporary())
1230 return resolveTypeRefArray(Tuple);
1231
1232 // Create and return a placeholder to use for now. Eventually
1233 // resolveTypeRefArrays() will be resolve this forward reference.
Duncan P. N. Exon Smithc3f89972016-06-09 20:46:33 +00001234 OldTypeRefs.Arrays.emplace_back(
1235 std::piecewise_construct, std::forward_as_tuple(Tuple),
1236 std::forward_as_tuple(MDTuple::getTemporary(Context, None)));
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001237 return OldTypeRefs.Arrays.back().second.get();
1238}
1239
1240Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
1241 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
1242 if (!Tuple || Tuple->isDistinct())
1243 return MaybeTuple;
1244
1245 // Look through the DITypeRefArray, upgrading each DITypeRef.
1246 SmallVector<Metadata *, 32> Ops;
1247 Ops.reserve(Tuple->getNumOperands());
1248 for (Metadata *MD : Tuple->operands())
1249 Ops.push_back(upgradeTypeRef(MD));
1250
1251 return MDTuple::get(Context, Ops);
1252}
1253
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001254Type *BitcodeReader::getTypeByID(unsigned ID) {
1255 // The type table size is always specified correctly.
1256 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +00001257 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +00001258
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001259 if (Type *Ty = TypeList[ID])
1260 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001261
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001262 // If we have a forward reference, the only possible case is when it is to a
1263 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001264 return TypeList[ID] = createIdentifiedStructType(Context);
1265}
1266
1267StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1268 StringRef Name) {
1269 auto *Ret = StructType::create(Context, Name);
1270 IdentifiedStructTypes.push_back(Ret);
1271 return Ret;
1272}
1273
1274StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1275 auto *Ret = StructType::create(Context);
1276 IdentifiedStructTypes.push_back(Ret);
1277 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +00001278}
1279
Chris Lattnerfee5a372007-05-04 03:30:17 +00001280//===----------------------------------------------------------------------===//
1281// Functions for parsing blocks from the bitcode file
1282//===----------------------------------------------------------------------===//
1283
Bill Wendling56aeccc2013-02-04 23:32:23 +00001284
1285/// \brief This fills an AttrBuilder object with the LLVM attributes that have
1286/// been decoded from the given integer. This function must stay in sync with
1287/// 'encodeLLVMAttributesForBitcode'.
1288static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1289 uint64_t EncodedAttrs) {
1290 // FIXME: Remove in 4.0.
1291
1292 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1293 // the bits above 31 down by 11 bits.
1294 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1295 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1296 "Alignment must be a power of two.");
1297
1298 if (Alignment)
1299 B.addAlignmentAttr(Alignment);
Kostya Serebryanyd688bab2013-02-11 08:13:54 +00001300 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
Bill Wendling56aeccc2013-02-04 23:32:23 +00001301 (EncodedAttrs & 0xffff));
1302}
1303
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001304std::error_code BitcodeReader::parseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001305 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001306 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001307
Devang Patela05633e2008-09-26 22:53:05 +00001308 if (!MAttributes.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001309 return error("Invalid multiple blocks");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001310
Chris Lattnerfee5a372007-05-04 03:30:17 +00001311 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001312
Bill Wendling71173cb2013-01-27 00:36:48 +00001313 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001314
Chris Lattnerfee5a372007-05-04 03:30:17 +00001315 // Read all the records.
1316 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001317 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001318
Chris Lattner27d38752013-01-20 02:13:19 +00001319 switch (Entry.Kind) {
1320 case BitstreamEntry::SubBlock: // Handled for us already.
1321 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001322 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001323 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001324 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001325 case BitstreamEntry::Record:
1326 // The interesting case.
1327 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001328 }
Joe Abbey97b7a172013-02-06 22:14:06 +00001329
Chris Lattnerfee5a372007-05-04 03:30:17 +00001330 // Read a record.
1331 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001332 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +00001333 default: // Default behavior: ignore.
1334 break;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001335 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1336 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +00001337 if (Record.size() & 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001338 return error("Invalid record");
Chris Lattnerfee5a372007-05-04 03:30:17 +00001339
Chris Lattnerfee5a372007-05-04 03:30:17 +00001340 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +00001341 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001342 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling60011b82013-01-29 01:43:29 +00001343 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +00001344 }
Devang Patela05633e2008-09-26 22:53:05 +00001345
Bill Wendlinge94d8432012-12-07 23:16:57 +00001346 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +00001347 Attrs.clear();
1348 break;
1349 }
Bill Wendling0dc08912013-02-12 08:13:50 +00001350 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1351 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1352 Attrs.push_back(MAttributeGroups[Record[i]]);
1353
1354 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1355 Attrs.clear();
1356 break;
1357 }
Duncan Sands04eb67e2007-11-20 14:09:29 +00001358 }
Chris Lattnerfee5a372007-05-04 03:30:17 +00001359 }
1360}
1361
Reid Klecknere9f36af2013-11-12 01:31:00 +00001362// Returns Attribute::None on unrecognized codes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001363static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
Reid Klecknere9f36af2013-11-12 01:31:00 +00001364 switch (Code) {
1365 default:
1366 return Attribute::None;
1367 case bitc::ATTR_KIND_ALIGNMENT:
1368 return Attribute::Alignment;
1369 case bitc::ATTR_KIND_ALWAYS_INLINE:
1370 return Attribute::AlwaysInline;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001371 case bitc::ATTR_KIND_ARGMEMONLY:
1372 return Attribute::ArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001373 case bitc::ATTR_KIND_BUILTIN:
1374 return Attribute::Builtin;
1375 case bitc::ATTR_KIND_BY_VAL:
1376 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +00001377 case bitc::ATTR_KIND_IN_ALLOCA:
1378 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001379 case bitc::ATTR_KIND_COLD:
1380 return Attribute::Cold;
Owen Anderson85fa7d52015-05-26 23:48:40 +00001381 case bitc::ATTR_KIND_CONVERGENT:
1382 return Attribute::Convergent;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001383 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1384 return Attribute::InaccessibleMemOnly;
1385 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1386 return Attribute::InaccessibleMemOrArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001387 case bitc::ATTR_KIND_INLINE_HINT:
1388 return Attribute::InlineHint;
1389 case bitc::ATTR_KIND_IN_REG:
1390 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +00001391 case bitc::ATTR_KIND_JUMP_TABLE:
1392 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001393 case bitc::ATTR_KIND_MIN_SIZE:
1394 return Attribute::MinSize;
1395 case bitc::ATTR_KIND_NAKED:
1396 return Attribute::Naked;
1397 case bitc::ATTR_KIND_NEST:
1398 return Attribute::Nest;
1399 case bitc::ATTR_KIND_NO_ALIAS:
1400 return Attribute::NoAlias;
1401 case bitc::ATTR_KIND_NO_BUILTIN:
1402 return Attribute::NoBuiltin;
1403 case bitc::ATTR_KIND_NO_CAPTURE:
1404 return Attribute::NoCapture;
1405 case bitc::ATTR_KIND_NO_DUPLICATE:
1406 return Attribute::NoDuplicate;
1407 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1408 return Attribute::NoImplicitFloat;
1409 case bitc::ATTR_KIND_NO_INLINE:
1410 return Attribute::NoInline;
James Molloye6f87ca2015-11-06 10:32:53 +00001411 case bitc::ATTR_KIND_NO_RECURSE:
1412 return Attribute::NoRecurse;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001413 case bitc::ATTR_KIND_NON_LAZY_BIND:
1414 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001415 case bitc::ATTR_KIND_NON_NULL:
1416 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001417 case bitc::ATTR_KIND_DEREFERENCEABLE:
1418 return Attribute::Dereferenceable;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001419 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1420 return Attribute::DereferenceableOrNull;
George Burgess IV278199f2016-04-12 01:05:35 +00001421 case bitc::ATTR_KIND_ALLOC_SIZE:
1422 return Attribute::AllocSize;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001423 case bitc::ATTR_KIND_NO_RED_ZONE:
1424 return Attribute::NoRedZone;
1425 case bitc::ATTR_KIND_NO_RETURN:
1426 return Attribute::NoReturn;
1427 case bitc::ATTR_KIND_NO_UNWIND:
1428 return Attribute::NoUnwind;
1429 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1430 return Attribute::OptimizeForSize;
1431 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1432 return Attribute::OptimizeNone;
1433 case bitc::ATTR_KIND_READ_NONE:
1434 return Attribute::ReadNone;
1435 case bitc::ATTR_KIND_READ_ONLY:
1436 return Attribute::ReadOnly;
1437 case bitc::ATTR_KIND_RETURNED:
1438 return Attribute::Returned;
1439 case bitc::ATTR_KIND_RETURNS_TWICE:
1440 return Attribute::ReturnsTwice;
1441 case bitc::ATTR_KIND_S_EXT:
1442 return Attribute::SExt;
1443 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1444 return Attribute::StackAlignment;
1445 case bitc::ATTR_KIND_STACK_PROTECT:
1446 return Attribute::StackProtect;
1447 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1448 return Attribute::StackProtectReq;
1449 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1450 return Attribute::StackProtectStrong;
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001451 case bitc::ATTR_KIND_SAFESTACK:
1452 return Attribute::SafeStack;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001453 case bitc::ATTR_KIND_STRUCT_RET:
1454 return Attribute::StructRet;
1455 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1456 return Attribute::SanitizeAddress;
1457 case bitc::ATTR_KIND_SANITIZE_THREAD:
1458 return Attribute::SanitizeThread;
1459 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1460 return Attribute::SanitizeMemory;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001461 case bitc::ATTR_KIND_SWIFT_ERROR:
1462 return Attribute::SwiftError;
Manman Renf46262e2016-03-29 17:37:21 +00001463 case bitc::ATTR_KIND_SWIFT_SELF:
1464 return Attribute::SwiftSelf;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001465 case bitc::ATTR_KIND_UW_TABLE:
1466 return Attribute::UWTable;
1467 case bitc::ATTR_KIND_Z_EXT:
1468 return Attribute::ZExt;
1469 }
1470}
1471
JF Bastien30bf96b2015-02-22 19:32:03 +00001472std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1473 unsigned &Alignment) {
1474 // Note: Alignment in bitcode files is incremented by 1, so that zero
1475 // can be used for default alignment.
1476 if (Exponent > Value::MaxAlignmentExponent + 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001477 return error("Invalid alignment value");
JF Bastien30bf96b2015-02-22 19:32:03 +00001478 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1479 return std::error_code();
1480}
1481
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001482std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001483 Attribute::AttrKind *Kind) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001484 *Kind = getAttrFromCode(Code);
Reid Klecknere9f36af2013-11-12 01:31:00 +00001485 if (*Kind == Attribute::None)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001486 return error(BitcodeError::CorruptedBitcode,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001487 "Unknown attribute kind (" + Twine(Code) + ")");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001488 return std::error_code();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001489}
1490
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001491std::error_code BitcodeReader::parseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +00001492 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001493 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001494
1495 if (!MAttributeGroups.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001496 return error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +00001497
1498 SmallVector<uint64_t, 64> Record;
1499
1500 // Read all the records.
1501 while (1) {
1502 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1503
1504 switch (Entry.Kind) {
1505 case BitstreamEntry::SubBlock: // Handled for us already.
1506 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001507 return error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +00001508 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001509 return std::error_code();
Bill Wendlingba629332013-02-10 23:24:25 +00001510 case BitstreamEntry::Record:
1511 // The interesting case.
1512 break;
1513 }
1514
1515 // Read a record.
1516 Record.clear();
1517 switch (Stream.readRecord(Entry.ID, Record)) {
1518 default: // Default behavior: ignore.
1519 break;
1520 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1521 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001522 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001523
Bill Wendlinge46707e2013-02-11 22:32:29 +00001524 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +00001525 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1526
1527 AttrBuilder B;
1528 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1529 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001530 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001531 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001532 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001533
1534 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +00001535 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001536 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001537 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001538 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001539 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001540 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001541 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001542 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001543 else if (Kind == Attribute::Dereferenceable)
1544 B.addDereferenceableAttr(Record[++i]);
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001545 else if (Kind == Attribute::DereferenceableOrNull)
1546 B.addDereferenceableOrNullAttr(Record[++i]);
George Burgess IV278199f2016-04-12 01:05:35 +00001547 else if (Kind == Attribute::AllocSize)
1548 B.addAllocSizeAttrFromRawRepr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +00001549 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +00001550 assert((Record[i] == 3 || Record[i] == 4) &&
1551 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +00001552 bool HasValue = (Record[i++] == 4);
1553 SmallString<64> KindStr;
1554 SmallString<64> ValStr;
1555
1556 while (Record[i] != 0 && i != e)
1557 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001558 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001559
1560 if (HasValue) {
1561 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +00001562 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +00001563 while (Record[i] != 0 && i != e)
1564 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001565 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001566 }
1567
1568 B.addAttribute(KindStr.str(), ValStr.str());
1569 }
1570 }
1571
Bill Wendlinge46707e2013-02-11 22:32:29 +00001572 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +00001573 break;
1574 }
1575 }
1576 }
1577}
1578
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001579std::error_code BitcodeReader::parseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001580 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001581 return error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +00001582
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001583 return parseTypeTableBody();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001584}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001585
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001586std::error_code BitcodeReader::parseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +00001587 if (!TypeList.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001588 return error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +00001589
1590 SmallVector<uint64_t, 64> Record;
1591 unsigned NumRecords = 0;
1592
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001593 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +00001594
Chris Lattner1314b992007-04-22 06:23:29 +00001595 // Read all the records for this type table.
1596 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001597 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001598
Chris Lattner27d38752013-01-20 02:13:19 +00001599 switch (Entry.Kind) {
1600 case BitstreamEntry::SubBlock: // Handled for us already.
1601 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001602 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001603 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +00001604 if (NumRecords != TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001605 return error("Malformed block");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001606 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001607 case BitstreamEntry::Record:
1608 // The interesting case.
1609 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001610 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001611
Chris Lattner1314b992007-04-22 06:23:29 +00001612 // Read a record.
1613 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001614 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001615 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001616 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001617 return error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +00001618 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1619 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1620 // type list. This allows us to reserve space.
1621 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001622 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001623 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001624 continue;
Chris Lattner1314b992007-04-22 06:23:29 +00001625 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +00001626 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001627 break;
Dan Gohman518cda42011-12-17 00:04:22 +00001628 case bitc::TYPE_CODE_HALF: // HALF
1629 ResultTy = Type::getHalfTy(Context);
1630 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001631 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +00001632 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001633 break;
1634 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +00001635 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001636 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001637 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +00001638 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001639 break;
1640 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001641 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001642 break;
1643 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001644 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001645 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001646 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +00001647 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001648 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001649 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +00001650 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001651 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +00001652 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1653 ResultTy = Type::getX86_MMXTy(Context);
1654 break;
David Majnemerb611e3f2015-08-14 05:09:07 +00001655 case bitc::TYPE_CODE_TOKEN: // TOKEN
1656 ResultTy = Type::getTokenTy(Context);
1657 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001658 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
Chris Lattner1314b992007-04-22 06:23:29 +00001659 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001660 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001661
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001662 uint64_t NumBits = Record[0];
1663 if (NumBits < IntegerType::MIN_INT_BITS ||
1664 NumBits > IntegerType::MAX_INT_BITS)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001665 return error("Bitwidth for integer type out of range");
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001666 ResultTy = IntegerType::get(Context, NumBits);
Chris Lattner1314b992007-04-22 06:23:29 +00001667 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001668 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001669 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001670 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +00001671 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001672 return error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001673 unsigned AddressSpace = 0;
1674 if (Record.size() == 2)
1675 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001676 ResultTy = getTypeByID(Record[0]);
Filipe Cabecinhasd8a1bcd2015-04-29 02:27:28 +00001677 if (!ResultTy ||
1678 !PointerType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001679 return error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001680 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +00001681 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001682 }
Nuno Lopes561dae02012-05-23 15:19:39 +00001683 case bitc::TYPE_CODE_FUNCTION_OLD: {
1684 // FIXME: attrid is dead, remove it in LLVM 4.0
1685 // FUNCTION: [vararg, attrid, retty, paramty x N]
1686 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001687 return error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +00001688 SmallVector<Type*, 8> ArgTys;
1689 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1690 if (Type *T = getTypeByID(Record[i]))
1691 ArgTys.push_back(T);
1692 else
1693 break;
1694 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001695
Nuno Lopes561dae02012-05-23 15:19:39 +00001696 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001697 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001698 return error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +00001699
1700 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1701 break;
1702 }
Chad Rosier95898722011-11-03 00:14:01 +00001703 case bitc::TYPE_CODE_FUNCTION: {
1704 // FUNCTION: [vararg, retty, paramty x N]
1705 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001706 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001707 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +00001708 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001709 if (Type *T = getTypeByID(Record[i])) {
1710 if (!FunctionType::isValidArgumentType(T))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001711 return error("Invalid function argument type");
Chad Rosier95898722011-11-03 00:14:01 +00001712 ArgTys.push_back(T);
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001713 }
Chad Rosier95898722011-11-03 00:14:01 +00001714 else
1715 break;
1716 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001717
Chad Rosier95898722011-11-03 00:14:01 +00001718 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001719 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001720 return error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +00001721
1722 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1723 break;
1724 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001725 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +00001726 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001727 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001728 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001729 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1730 if (Type *T = getTypeByID(Record[i]))
1731 EltTys.push_back(T);
1732 else
1733 break;
1734 }
1735 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001736 return error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001737 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001738 break;
1739 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001740 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001741 if (convertToString(Record, 0, TypeName))
1742 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001743 continue;
1744
1745 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1746 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001747 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001748
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001749 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001750 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001751
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001752 // Check to see if this was forward referenced, if so fill in the temp.
1753 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1754 if (Res) {
1755 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001756 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001757 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001758 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001759 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001760
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001761 SmallVector<Type*, 8> EltTys;
1762 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1763 if (Type *T = getTypeByID(Record[i]))
1764 EltTys.push_back(T);
1765 else
1766 break;
1767 }
1768 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001769 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001770 Res->setBody(EltTys, Record[0]);
1771 ResultTy = Res;
1772 break;
1773 }
1774 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1775 if (Record.size() != 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001776 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001777
1778 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001779 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001780
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001781 // Check to see if this was forward referenced, if so fill in the temp.
1782 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1783 if (Res) {
1784 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001785 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001786 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001787 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001788 TypeName.clear();
1789 ResultTy = Res;
1790 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001791 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001792 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1793 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001794 return error("Invalid record");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001795 ResultTy = getTypeByID(Record[1]);
1796 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001797 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001798 ResultTy = ArrayType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001799 break;
1800 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1801 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001802 return error("Invalid record");
Filipe Cabecinhas8e421902015-06-03 00:05:30 +00001803 if (Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001804 return error("Invalid vector length");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001805 ResultTy = getTypeByID(Record[1]);
1806 if (!ResultTy || !StructType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001807 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001808 ResultTy = VectorType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001809 break;
1810 }
1811
1812 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001813 return error("Invalid TYPE table");
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001814 if (TypeList[NumRecords])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001815 return error(
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001816 "Invalid TYPE table: Only named structs can be forward referenced");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001817 assert(ResultTy && "Didn't read a type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001818 TypeList[NumRecords++] = ResultTy;
1819 }
1820}
1821
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001822std::error_code BitcodeReader::parseOperandBundleTags() {
1823 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1824 return error("Invalid record");
1825
1826 if (!BundleTags.empty())
1827 return error("Invalid multiple blocks");
1828
1829 SmallVector<uint64_t, 64> Record;
1830
1831 while (1) {
1832 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1833
1834 switch (Entry.Kind) {
1835 case BitstreamEntry::SubBlock: // Handled for us already.
1836 case BitstreamEntry::Error:
1837 return error("Malformed block");
1838 case BitstreamEntry::EndBlock:
1839 return std::error_code();
1840 case BitstreamEntry::Record:
1841 // The interesting case.
1842 break;
1843 }
1844
1845 // Tags are implicitly mapped to integers by their order.
1846
1847 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1848 return error("Invalid record");
1849
1850 // OPERAND_BUNDLE_TAG: [strchr x N]
1851 BundleTags.emplace_back();
1852 if (convertToString(Record, 0, BundleTags.back()))
1853 return error("Invalid record");
1854 Record.clear();
1855 }
1856}
1857
Teresa Johnsonff642b92015-09-17 20:12:00 +00001858/// Associate a value with its name from the given index in the provided record.
1859ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1860 unsigned NameIndex, Triple &TT) {
1861 SmallString<128> ValueName;
1862 if (convertToString(Record, NameIndex, ValueName))
1863 return error("Invalid record");
1864 unsigned ValueID = Record[0];
1865 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1866 return error("Invalid record");
1867 Value *V = ValueList[ValueID];
1868
Filipe Cabecinhasa2b0ac42015-11-04 14:53:36 +00001869 StringRef NameStr(ValueName.data(), ValueName.size());
1870 if (NameStr.find_first_of(0) != StringRef::npos)
1871 return error("Invalid value name");
1872 V->setName(NameStr);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001873 auto *GO = dyn_cast<GlobalObject>(V);
1874 if (GO) {
1875 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1876 if (TT.isOSBinFormatMachO())
1877 GO->setComdat(nullptr);
1878 else
1879 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1880 }
1881 }
1882 return V;
1883}
1884
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001885/// Helper to note and return the current location, and jump to the given
1886/// offset.
1887static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1888 BitstreamCursor &Stream) {
1889 // Save the current parsing location so we can jump back at the end
1890 // of the VST read.
1891 uint64_t CurrentBit = Stream.GetCurrentBitNo();
1892 Stream.JumpToBit(Offset * 32);
1893#ifndef NDEBUG
1894 // Do some checking if we are in debug mode.
1895 BitstreamEntry Entry = Stream.advance();
1896 assert(Entry.Kind == BitstreamEntry::SubBlock);
1897 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1898#else
1899 // In NDEBUG mode ignore the output so we don't get an unused variable
1900 // warning.
1901 Stream.advance();
1902#endif
1903 return CurrentBit;
1904}
1905
Teresa Johnsonff642b92015-09-17 20:12:00 +00001906/// Parse the value symbol table at either the current parsing location or
1907/// at the given bit offset if provided.
Peter Collingbourne128a9762015-10-27 23:01:25 +00001908std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001909 uint64_t CurrentBit;
1910 // Pass in the Offset to distinguish between calling for the module-level
1911 // VST (where we want to jump to the VST offset) and the function-level
1912 // VST (where we don't).
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001913 if (Offset > 0)
1914 CurrentBit = jumpToValueSymbolTable(Offset, Stream);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001915
1916 // Compute the delta between the bitcode indices in the VST (the word offset
1917 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1918 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1919 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1920 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1921 // just before entering the VST subblock because: 1) the EnterSubBlock
1922 // changes the AbbrevID width; 2) the VST block is nested within the same
1923 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1924 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1925 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1926 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1927 unsigned FuncBitcodeOffsetDelta =
1928 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1929
Chris Lattner982ec1e2007-05-05 00:17:00 +00001930 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001931 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001932
1933 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001934
David Majnemer3087b222015-01-20 05:58:07 +00001935 Triple TT(TheModule->getTargetTriple());
1936
Chris Lattnerccaa4482007-04-23 21:26:05 +00001937 // Read all the records for this value table.
1938 SmallString<128> ValueName;
1939 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001940 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001941
Chris Lattner27d38752013-01-20 02:13:19 +00001942 switch (Entry.Kind) {
1943 case BitstreamEntry::SubBlock: // Handled for us already.
1944 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001945 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001946 case BitstreamEntry::EndBlock:
Teresa Johnsonff642b92015-09-17 20:12:00 +00001947 if (Offset > 0)
1948 Stream.JumpToBit(CurrentBit);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001949 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001950 case BitstreamEntry::Record:
1951 // The interesting case.
1952 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001953 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001954
Chris Lattnerccaa4482007-04-23 21:26:05 +00001955 // Read a record.
1956 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001957 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001958 default: // Default behavior: unknown type.
1959 break;
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001960 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
Teresa Johnsonff642b92015-09-17 20:12:00 +00001961 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1962 if (std::error_code EC = ValOrErr.getError())
1963 return EC;
1964 ValOrErr.get();
1965 break;
1966 }
1967 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001968 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonff642b92015-09-17 20:12:00 +00001969 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1970 if (std::error_code EC = ValOrErr.getError())
1971 return EC;
1972 Value *V = ValOrErr.get();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001973
Teresa Johnsonff642b92015-09-17 20:12:00 +00001974 auto *GO = dyn_cast<GlobalObject>(V);
1975 if (!GO) {
1976 // If this is an alias, need to get the actual Function object
1977 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1978 auto *GA = dyn_cast<GlobalAlias>(V);
1979 if (GA)
1980 GO = GA->getBaseObject();
1981 assert(GO);
Rafael Espindola12ca34f2015-01-19 15:16:06 +00001982 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001983
1984 uint64_t FuncWordOffset = Record[1];
1985 Function *F = dyn_cast<Function>(GO);
1986 assert(F);
1987 uint64_t FuncBitOffset = FuncWordOffset * 32;
1988 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
Teresa Johnson1493ad92015-10-10 14:18:36 +00001989 // Set the LastFunctionBlockBit to point to the last function block.
Teresa Johnsonff642b92015-09-17 20:12:00 +00001990 // Later when parsing is resumed after function materialization,
1991 // we can simply skip that last function block.
Teresa Johnson1493ad92015-10-10 14:18:36 +00001992 if (FuncBitOffset > LastFunctionBlockBit)
1993 LastFunctionBlockBit = FuncBitOffset;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001994 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00001995 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00001996 case bitc::VST_CODE_BBENTRY: {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001997 if (convertToString(Record, 1, ValueName))
1998 return error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00001999 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002000 if (!BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002001 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002002
Daniel Dunbard786b512009-07-26 00:34:27 +00002003 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00002004 ValueName.clear();
2005 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00002006 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00002007 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00002008 }
2009}
2010
Teresa Johnson12545072015-11-15 02:00:09 +00002011/// Parse a single METADATA_KIND record, inserting result in MDKindMap.
2012std::error_code
2013BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
2014 if (Record.size() < 2)
2015 return error("Invalid record");
2016
2017 unsigned Kind = Record[0];
2018 SmallString<8> Name(Record.begin() + 1, Record.end());
2019
2020 unsigned NewKind = TheModule->getMDKindID(Name.str());
2021 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2022 return error("Conflicting METADATA_KIND records");
2023 return std::error_code();
2024}
2025
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002026static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
2027
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002028std::error_code BitcodeReader::parseMetadataStrings(ArrayRef<uint64_t> Record,
2029 StringRef Blob,
2030 unsigned &NextMetadataNo) {
2031 // All the MDStrings in the block are emitted together in a single
2032 // record. The strings are concatenated and stored in a blob along with
2033 // their sizes.
2034 if (Record.size() != 2)
2035 return error("Invalid record: metadata strings layout");
2036
2037 unsigned NumStrings = Record[0];
2038 unsigned StringsOffset = Record[1];
2039 if (!NumStrings)
2040 return error("Invalid record: metadata strings with no strings");
Duncan P. N. Exon Smithbb7ce3b2016-03-29 05:25:17 +00002041 if (StringsOffset > Blob.size())
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002042 return error("Invalid record: metadata strings corrupt offset");
2043
2044 StringRef Lengths = Blob.slice(0, StringsOffset);
2045 SimpleBitstreamCursor R(*StreamFile);
2046 R.jumpToPointer(Lengths.begin());
2047
2048 // Ensure that Blob doesn't get invalidated, even if this is reading from
2049 // a StreamingMemoryObject with corrupt data.
2050 R.setArtificialByteLimit(R.getCurrentByteNo() + StringsOffset);
2051
2052 StringRef Strings = Blob.drop_front(StringsOffset);
2053 do {
2054 if (R.AtEndOfStream())
2055 return error("Invalid record: metadata strings bad length");
2056
2057 unsigned Size = R.ReadVBR(6);
2058 if (Strings.size() < Size)
2059 return error("Invalid record: metadata strings truncated chars");
2060
2061 MetadataList.assignValue(MDString::get(Context, Strings.slice(0, Size)),
2062 NextMetadataNo++);
2063 Strings = Strings.drop_front(Size);
2064 } while (--NumStrings);
2065
2066 return std::error_code();
2067}
2068
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002069namespace {
2070class PlaceholderQueue {
2071 // Placeholders would thrash around when moved, so store in a std::deque
2072 // instead of some sort of vector.
2073 std::deque<DistinctMDOperandPlaceholder> PHs;
2074
2075public:
2076 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
2077 void flush(BitcodeReaderMetadataList &MetadataList);
2078};
2079} // end namespace
2080
2081DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
2082 PHs.emplace_back(ID);
2083 return PHs.back();
2084}
2085
2086void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
2087 while (!PHs.empty()) {
2088 PHs.front().replaceUseWith(
2089 MetadataList.getMetadataFwdRef(PHs.front().getID()));
2090 PHs.pop_front();
2091 }
2092}
2093
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00002094/// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
2095/// module level metadata.
2096std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
Duncan P. N. Exon Smith03a04a52016-04-24 15:04:28 +00002097 assert((ModuleLevel || DeferredMetadataInfo.empty()) &&
2098 "Must read all module-level metadata before function-level");
2099
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002100 IsMetadataMaterialized = true;
Teresa Johnson61b406e2015-12-29 23:00:22 +00002101 unsigned NextMetadataNo = MetadataList.size();
Devang Patel7428d8a2009-07-22 17:43:22 +00002102
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00002103 if (!ModuleLevel && MetadataList.hasFwdRefs())
2104 return error("Invalid metadata: fwd refs into function blocks");
2105
Devang Patel7428d8a2009-07-22 17:43:22 +00002106 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002107 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002108
Adrian Prantl75819ae2016-04-15 15:57:41 +00002109 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
Devang Patel7428d8a2009-07-22 17:43:22 +00002110 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002111
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002112 PlaceholderQueue Placeholders;
2113 bool IsDistinct;
Duncan P. N. Exon Smith498b4972016-04-23 04:52:47 +00002114 auto getMD = [&](unsigned ID) -> Metadata * {
2115 if (!IsDistinct)
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002116 return MetadataList.getMetadataFwdRef(ID);
2117 if (auto *MD = MetadataList.getMetadataIfResolved(ID))
2118 return MD;
2119 return &Placeholders.getPlaceholderOp(ID);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002120 };
Duncan P. N. Exon Smith498b4972016-04-23 04:52:47 +00002121 auto getMDOrNull = [&](unsigned ID) -> Metadata * {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002122 if (ID)
Duncan P. N. Exon Smith498b4972016-04-23 04:52:47 +00002123 return getMD(ID - 1);
2124 return nullptr;
2125 };
2126 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
2127 if (ID)
2128 return MetadataList.getMetadataFwdRef(ID - 1);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002129 return nullptr;
2130 };
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002131 auto getMDString = [&](unsigned ID) -> MDString *{
2132 // This requires that the ID is not really a forward reference. In
2133 // particular, the MDString must already have been resolved.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002134 return cast_or_null<MDString>(getMDOrNull(ID));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002135 };
2136
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002137 // Support for old type refs.
2138 auto getDITypeRefOrNull = [&](unsigned ID) {
2139 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
2140 };
2141
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002142#define GET_OR_DISTINCT(CLASS, ARGS) \
2143 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002144
Devang Patel7428d8a2009-07-22 17:43:22 +00002145 // Read all the records.
2146 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002147 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002148
Chris Lattner27d38752013-01-20 02:13:19 +00002149 switch (Entry.Kind) {
2150 case BitstreamEntry::SubBlock: // Handled for us already.
2151 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002152 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002153 case BitstreamEntry::EndBlock:
Adrian Prantl75819ae2016-04-15 15:57:41 +00002154 // Upgrade old-style CU <-> SP pointers to point from SP to CU.
2155 for (auto CU_SP : CUSubprograms)
2156 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
2157 for (auto &Op : SPs->operands())
2158 if (auto *SP = dyn_cast_or_null<MDNode>(Op))
2159 SP->replaceOperandWith(7, CU_SP.first);
2160
Teresa Johnson61b406e2015-12-29 23:00:22 +00002161 MetadataList.tryToResolveCycles();
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002162 Placeholders.flush(MetadataList);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002163 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002164 case BitstreamEntry::Record:
2165 // The interesting case.
2166 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00002167 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002168
Devang Patel7428d8a2009-07-22 17:43:22 +00002169 // Read a record.
2170 Record.clear();
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002171 StringRef Blob;
2172 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002173 IsDistinct = false;
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00002174 switch (Code) {
Devang Patel7428d8a2009-07-22 17:43:22 +00002175 default: // Default behavior: ignore.
2176 break;
Devang Patel27c87ff2009-07-29 22:34:41 +00002177 case bitc::METADATA_NAME: {
Chris Lattner8d140532013-01-20 02:54:05 +00002178 // Read name of the named metadata.
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002179 SmallString<8> Name(Record.begin(), Record.end());
Devang Patel27c87ff2009-07-29 22:34:41 +00002180 Record.clear();
2181 Code = Stream.ReadCode();
2182
Chris Lattner27d38752013-01-20 02:13:19 +00002183 unsigned NextBitCode = Stream.readRecord(Code, Record);
Filipe Cabecinhas14e68672015-05-30 00:17:20 +00002184 if (NextBitCode != bitc::METADATA_NAMED_NODE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002185 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
Devang Patel27c87ff2009-07-29 22:34:41 +00002186
2187 // Read named metadata elements.
2188 unsigned Size = Record.size();
Dan Gohman2637cc12010-07-21 23:38:33 +00002189 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patel27c87ff2009-07-29 22:34:41 +00002190 for (unsigned i = 0; i != Size; ++i) {
Justin Bognerae341c62016-03-17 20:12:06 +00002191 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002192 if (!MD)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002193 return error("Invalid record");
Dan Gohman2637cc12010-07-21 23:38:33 +00002194 NMD->addOperand(MD);
Devang Patel27c87ff2009-07-29 22:34:41 +00002195 }
Devang Patel27c87ff2009-07-29 22:34:41 +00002196 break;
2197 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00002198 case bitc::METADATA_OLD_FN_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00002199 // FIXME: Remove in 4.0.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002200 // This is a LocalAsMetadata record, the only type of function-local
2201 // metadata.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002202 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002203 return error("Invalid record");
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002204
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002205 // If this isn't a LocalAsMetadata record, we're dropping it. This used
2206 // to be legal, but there's no upgrade path.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002207 auto dropRecord = [&] {
Teresa Johnson61b406e2015-12-29 23:00:22 +00002208 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002209 };
2210 if (Record.size() != 2) {
2211 dropRecord();
2212 break;
2213 }
2214
2215 Type *Ty = getTypeByID(Record[0]);
2216 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
2217 dropRecord();
2218 break;
2219 }
2220
Teresa Johnson61b406e2015-12-29 23:00:22 +00002221 MetadataList.assignValue(
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002222 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002223 NextMetadataNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002224 break;
2225 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00002226 case bitc::METADATA_OLD_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00002227 // FIXME: Remove in 4.0.
Dan Gohman1e0213a2010-07-13 19:33:27 +00002228 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002229 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002230
Devang Patele059ba6e2009-07-23 01:07:34 +00002231 unsigned Size = Record.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002232 SmallVector<Metadata *, 8> Elts;
Devang Patele059ba6e2009-07-23 01:07:34 +00002233 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00002234 Type *Ty = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002235 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002236 return error("Invalid record");
Chris Lattnerfdd87902009-10-05 05:54:46 +00002237 if (Ty->isMetadataTy())
Duncan P. N. Exon Smith004509d2016-04-23 03:55:14 +00002238 Elts.push_back(getMD(Record[i + 1]));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002239 else if (!Ty->isVoidTy()) {
2240 auto *MD =
2241 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2242 assert(isa<ConstantAsMetadata>(MD) &&
2243 "Expected non-function-local metadata");
2244 Elts.push_back(MD);
2245 } else
Craig Topper2617dcc2014-04-15 06:32:26 +00002246 Elts.push_back(nullptr);
Devang Patele059ba6e2009-07-23 01:07:34 +00002247 }
Teresa Johnson61b406e2015-12-29 23:00:22 +00002248 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++);
Devang Patele059ba6e2009-07-23 01:07:34 +00002249 break;
2250 }
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002251 case bitc::METADATA_VALUE: {
2252 if (Record.size() != 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002253 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002254
2255 Type *Ty = getTypeByID(Record[0]);
2256 if (Ty->isMetadataTy() || Ty->isVoidTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002257 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002258
Teresa Johnson61b406e2015-12-29 23:00:22 +00002259 MetadataList.assignValue(
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002260 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002261 NextMetadataNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002262 break;
2263 }
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00002264 case bitc::METADATA_DISTINCT_NODE:
2265 IsDistinct = true;
2266 // fallthrough...
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002267 case bitc::METADATA_NODE: {
2268 SmallVector<Metadata *, 8> Elts;
2269 Elts.reserve(Record.size());
2270 for (unsigned ID : Record)
Duncan P. N. Exon Smith004509d2016-04-23 03:55:14 +00002271 Elts.push_back(getMDOrNull(ID));
Teresa Johnson61b406e2015-12-29 23:00:22 +00002272 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2273 : MDNode::get(Context, Elts),
2274 NextMetadataNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002275 break;
2276 }
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002277 case bitc::METADATA_LOCATION: {
2278 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002279 return error("Invalid record");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002280
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002281 IsDistinct = Record[0];
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002282 unsigned Line = Record[1];
2283 unsigned Column = Record[2];
Duncan P. N. Exon Smith004509d2016-04-23 03:55:14 +00002284 Metadata *Scope = getMD(Record[3]);
2285 Metadata *InlinedAt = getMDOrNull(Record[4]);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002286 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002287 GET_OR_DISTINCT(DILocation,
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00002288 (Context, Line, Column, Scope, InlinedAt)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002289 NextMetadataNo++);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002290 break;
2291 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002292 case bitc::METADATA_GENERIC_DEBUG: {
2293 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002294 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002295
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002296 IsDistinct = Record[0];
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002297 unsigned Tag = Record[1];
2298 unsigned Version = Record[2];
2299
2300 if (Tag >= 1u << 16 || Version != 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002301 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002302
2303 auto *Header = getMDString(Record[3]);
2304 SmallVector<Metadata *, 8> DwarfOps;
2305 for (unsigned I = 4, E = Record.size(); I != E; ++I)
Duncan P. N. Exon Smith004509d2016-04-23 03:55:14 +00002306 DwarfOps.push_back(getMDOrNull(Record[I]));
Teresa Johnson61b406e2015-12-29 23:00:22 +00002307 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002308 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002309 NextMetadataNo++);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002310 break;
2311 }
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002312 case bitc::METADATA_SUBRANGE: {
2313 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002314 return error("Invalid record");
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002315
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002316 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002317 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002318 GET_OR_DISTINCT(DISubrange,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002319 (Context, Record[1], unrotateSign(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002320 NextMetadataNo++);
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002321 break;
2322 }
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002323 case bitc::METADATA_ENUMERATOR: {
2324 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002325 return error("Invalid record");
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002326
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002327 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002328 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002329 GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]),
2330 getMDString(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002331 NextMetadataNo++);
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002332 break;
2333 }
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002334 case bitc::METADATA_BASIC_TYPE: {
2335 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002336 return error("Invalid record");
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002337
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002338 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002339 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002340 GET_OR_DISTINCT(DIBasicType,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002341 (Context, Record[1], getMDString(Record[2]),
2342 Record[3], Record[4], Record[5])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002343 NextMetadataNo++);
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002344 break;
2345 }
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002346 case bitc::METADATA_DERIVED_TYPE: {
2347 if (Record.size() != 12)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002348 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002349
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002350 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002351 MetadataList.assignValue(
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00002352 GET_OR_DISTINCT(
2353 DIDerivedType,
2354 (Context, Record[1], getMDString(Record[2]),
2355 getMDOrNull(Record[3]), Record[4], getDITypeRefOrNull(Record[5]),
2356 getDITypeRefOrNull(Record[6]), Record[7], Record[8], Record[9],
2357 Record[10], getDITypeRefOrNull(Record[11]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002358 NextMetadataNo++);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002359 break;
2360 }
2361 case bitc::METADATA_COMPOSITE_TYPE: {
2362 if (Record.size() != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002363 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002364
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002365 // If we have a UUID and this is not a forward declaration, lookup the
2366 // mapping.
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002367 IsDistinct = Record[0] & 0x1;
2368 bool IsNotUsedInTypeRef = Record[0] >= 2;
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002369 unsigned Tag = Record[1];
2370 MDString *Name = getMDString(Record[2]);
2371 Metadata *File = getMDOrNull(Record[3]);
2372 unsigned Line = Record[4];
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002373 Metadata *Scope = getDITypeRefOrNull(Record[5]);
2374 Metadata *BaseType = getDITypeRefOrNull(Record[6]);
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002375 uint64_t SizeInBits = Record[7];
2376 uint64_t AlignInBits = Record[8];
2377 uint64_t OffsetInBits = Record[9];
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002378 unsigned Flags = Record[10];
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002379 Metadata *Elements = getMDOrNull(Record[11]);
2380 unsigned RuntimeLang = Record[12];
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002381 Metadata *VTableHolder = getDITypeRefOrNull(Record[13]);
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002382 Metadata *TemplateParams = getMDOrNull(Record[14]);
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002383 auto *Identifier = getMDString(Record[15]);
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002384 DICompositeType *CT = nullptr;
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00002385 if (Identifier)
2386 CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002387 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
2388 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
2389 VTableHolder, TemplateParams);
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002390
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002391 // Create a node if we didn't get a lazy ODR type.
2392 if (!CT)
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002393 CT = GET_OR_DISTINCT(DICompositeType,
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002394 (Context, Tag, Name, File, Line, Scope, BaseType,
2395 SizeInBits, AlignInBits, OffsetInBits, Flags,
2396 Elements, RuntimeLang, VTableHolder,
2397 TemplateParams, Identifier));
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002398 if (!IsNotUsedInTypeRef && Identifier)
2399 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002400
2401 MetadataList.assignValue(CT, NextMetadataNo++);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002402 break;
2403 }
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002404 case bitc::METADATA_SUBROUTINE_TYPE: {
Reid Klecknerde3d8b52016-06-08 20:34:29 +00002405 if (Record.size() < 3 || Record.size() > 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002406 return error("Invalid record");
Reid Klecknerde3d8b52016-06-08 20:34:29 +00002407 bool IsOldTypeRefArray = Record[0] < 2;
2408 unsigned CC = (Record.size() > 3) ? Record[3] : 0;
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002409
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002410 IsDistinct = Record[0] & 0x1;
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002411 Metadata *Types = getMDOrNull(Record[2]);
2412 if (LLVM_UNLIKELY(IsOldTypeRefArray))
2413 Types = MetadataList.upgradeTypeRefArray(Types);
2414
Teresa Johnson61b406e2015-12-29 23:00:22 +00002415 MetadataList.assignValue(
Reid Klecknerde3d8b52016-06-08 20:34:29 +00002416 GET_OR_DISTINCT(DISubroutineType, (Context, Record[1], CC, Types)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002417 NextMetadataNo++);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002418 break;
2419 }
Adrian Prantlab1243f2015-06-29 23:03:47 +00002420
2421 case bitc::METADATA_MODULE: {
2422 if (Record.size() != 6)
2423 return error("Invalid record");
2424
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002425 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002426 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002427 GET_OR_DISTINCT(DIModule,
Adrian Prantlab1243f2015-06-29 23:03:47 +00002428 (Context, getMDOrNull(Record[1]),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002429 getMDString(Record[2]), getMDString(Record[3]),
2430 getMDString(Record[4]), getMDString(Record[5]))),
2431 NextMetadataNo++);
Adrian Prantlab1243f2015-06-29 23:03:47 +00002432 break;
2433 }
2434
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002435 case bitc::METADATA_FILE: {
2436 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002437 return error("Invalid record");
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002438
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002439 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002440 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002441 GET_OR_DISTINCT(DIFile, (Context, getMDString(Record[1]),
2442 getMDString(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002443 NextMetadataNo++);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002444 break;
2445 }
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002446 case bitc::METADATA_COMPILE_UNIT: {
Amjad Abouda9bcf162015-12-10 12:56:35 +00002447 if (Record.size() < 14 || Record.size() > 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002448 return error("Invalid record");
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002449
Amjad Abouda9bcf162015-12-10 12:56:35 +00002450 // Ignore Record[0], which indicates whether this compile unit is
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00002451 // distinct. It's always distinct.
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002452 IsDistinct = true;
Adrian Prantl75819ae2016-04-15 15:57:41 +00002453 auto *CU = DICompileUnit::getDistinct(
2454 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
2455 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
2456 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2457 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
2458 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
2459 Record.size() <= 14 ? 0 : Record[14]);
2460
2461 MetadataList.assignValue(CU, NextMetadataNo++);
2462
2463 // Move the Upgrade the list of subprograms.
Duncan P. N. Exon Smith498b4972016-04-23 04:52:47 +00002464 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
Adrian Prantl75819ae2016-04-15 15:57:41 +00002465 CUSubprograms.push_back({CU, SPs});
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002466 break;
2467 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002468 case bitc::METADATA_SUBPROGRAM: {
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002469 if (Record.size() < 18 || Record.size() > 20)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002470 return error("Invalid record");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002471
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002472 IsDistinct =
Adrian Prantl85338cb2016-05-06 22:53:06 +00002473 (Record[0] & 1) || Record[8]; // All definitions should be distinct.
Adrian Prantl75819ae2016-04-15 15:57:41 +00002474 // Version 1 has a Function as Record[15].
2475 // Version 2 has removed Record[15].
2476 // Version 3 has the Unit as Record[15].
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002477 // Version 4 added thisAdjustment.
Adrian Prantl85338cb2016-05-06 22:53:06 +00002478 bool HasUnit = Record[0] >= 2;
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002479 if (HasUnit && Record.size() < 19)
Adrian Prantl85338cb2016-05-06 22:53:06 +00002480 return error("Invalid record");
Adrian Prantl75819ae2016-04-15 15:57:41 +00002481 Metadata *CUorFn = getMDOrNull(Record[15]);
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002482 unsigned Offset = Record.size() >= 19 ? 1 : 0;
Adrian Prantl85338cb2016-05-06 22:53:06 +00002483 bool HasFn = Offset && !HasUnit;
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002484 bool HasThisAdj = Record.size() >= 20;
Peter Collingbourned4bff302015-11-05 22:03:56 +00002485 DISubprogram *SP = GET_OR_DISTINCT(
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002486 DISubprogram, (Context,
2487 getDITypeRefOrNull(Record[1]), // scope
2488 getMDString(Record[2]), // name
2489 getMDString(Record[3]), // linkageName
2490 getMDOrNull(Record[4]), // file
2491 Record[5], // line
2492 getMDOrNull(Record[6]), // type
2493 Record[7], // isLocal
2494 Record[8], // isDefinition
2495 Record[9], // scopeLine
2496 getDITypeRefOrNull(Record[10]), // containingType
2497 Record[11], // virtuality
2498 Record[12], // virtualIndex
2499 HasThisAdj ? Record[19] : 0, // thisAdjustment
2500 Record[13], // flags
2501 Record[14], // isOptimized
2502 HasUnit ? CUorFn : nullptr, // unit
2503 getMDOrNull(Record[15 + Offset]), // templateParams
2504 getMDOrNull(Record[16 + Offset]), // declaration
2505 getMDOrNull(Record[17 + Offset]) // variables
2506 ));
Teresa Johnson61b406e2015-12-29 23:00:22 +00002507 MetadataList.assignValue(SP, NextMetadataNo++);
Peter Collingbourned4bff302015-11-05 22:03:56 +00002508
2509 // Upgrade sp->function mapping to function->sp mapping.
Adrian Prantl75819ae2016-04-15 15:57:41 +00002510 if (HasFn) {
Adrian Prantl85338cb2016-05-06 22:53:06 +00002511 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
Peter Collingbourned4bff302015-11-05 22:03:56 +00002512 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2513 if (F->isMaterializable())
2514 // Defer until materialized; unmaterialized functions may not have
2515 // metadata.
2516 FunctionsWithSPs[F] = SP;
2517 else if (!F->empty())
2518 F->setSubprogram(SP);
2519 }
2520 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002521 break;
2522 }
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002523 case bitc::METADATA_LEXICAL_BLOCK: {
2524 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002525 return error("Invalid record");
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002526
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002527 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002528 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002529 GET_OR_DISTINCT(DILexicalBlock,
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002530 (Context, getMDOrNull(Record[1]),
2531 getMDOrNull(Record[2]), Record[3], Record[4])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002532 NextMetadataNo++);
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002533 break;
2534 }
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002535 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2536 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002537 return error("Invalid record");
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002538
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002539 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002540 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002541 GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002542 (Context, getMDOrNull(Record[1]),
2543 getMDOrNull(Record[2]), Record[3])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002544 NextMetadataNo++);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002545 break;
2546 }
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002547 case bitc::METADATA_NAMESPACE: {
2548 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002549 return error("Invalid record");
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002550
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002551 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002552 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002553 GET_OR_DISTINCT(DINamespace, (Context, getMDOrNull(Record[1]),
2554 getMDOrNull(Record[2]),
2555 getMDString(Record[3]), Record[4])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002556 NextMetadataNo++);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002557 break;
2558 }
Amjad Abouda9bcf162015-12-10 12:56:35 +00002559 case bitc::METADATA_MACRO: {
2560 if (Record.size() != 5)
2561 return error("Invalid record");
2562
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002563 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002564 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002565 GET_OR_DISTINCT(DIMacro,
Amjad Abouda9bcf162015-12-10 12:56:35 +00002566 (Context, Record[1], Record[2],
2567 getMDString(Record[3]), getMDString(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002568 NextMetadataNo++);
Amjad Abouda9bcf162015-12-10 12:56:35 +00002569 break;
2570 }
2571 case bitc::METADATA_MACRO_FILE: {
2572 if (Record.size() != 5)
2573 return error("Invalid record");
2574
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002575 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002576 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002577 GET_OR_DISTINCT(DIMacroFile,
Amjad Abouda9bcf162015-12-10 12:56:35 +00002578 (Context, Record[1], Record[2],
2579 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002580 NextMetadataNo++);
Amjad Abouda9bcf162015-12-10 12:56:35 +00002581 break;
2582 }
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002583 case bitc::METADATA_TEMPLATE_TYPE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002584 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002585 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002586
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002587 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002588 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
Teresa Johnson61b406e2015-12-29 23:00:22 +00002589 (Context, getMDString(Record[1]),
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002590 getDITypeRefOrNull(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002591 NextMetadataNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002592 break;
2593 }
2594 case bitc::METADATA_TEMPLATE_VALUE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002595 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002596 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002597
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002598 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002599 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002600 GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002601 (Context, Record[1], getMDString(Record[2]),
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002602 getDITypeRefOrNull(Record[3]),
2603 getMDOrNull(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002604 NextMetadataNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002605 break;
2606 }
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002607 case bitc::METADATA_GLOBAL_VAR: {
2608 if (Record.size() != 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002609 return error("Invalid record");
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002610
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002611 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002612 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002613 GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002614 (Context, getMDOrNull(Record[1]),
2615 getMDString(Record[2]), getMDString(Record[3]),
2616 getMDOrNull(Record[4]), Record[5],
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002617 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002618 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002619 NextMetadataNo++);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002620 break;
2621 }
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002622 case bitc::METADATA_LOCAL_VAR: {
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00002623 // 10th field is for the obseleted 'inlinedAt:' field.
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002624 if (Record.size() < 8 || Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002625 return error("Invalid record");
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002626
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002627 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2628 // DW_TAG_arg_variable.
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002629 IsDistinct = Record[0];
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002630 bool HasTag = Record.size() > 8;
Teresa Johnson61b406e2015-12-29 23:00:22 +00002631 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002632 GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002633 (Context, getMDOrNull(Record[1 + HasTag]),
2634 getMDString(Record[2 + HasTag]),
2635 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002636 getDITypeRefOrNull(Record[5 + HasTag]),
2637 Record[6 + HasTag], Record[7 + HasTag])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002638 NextMetadataNo++);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002639 break;
2640 }
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002641 case bitc::METADATA_EXPRESSION: {
2642 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002643 return error("Invalid record");
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002644
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002645 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002646 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002647 GET_OR_DISTINCT(DIExpression,
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002648 (Context, makeArrayRef(Record).slice(1))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002649 NextMetadataNo++);
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002650 break;
2651 }
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002652 case bitc::METADATA_OBJC_PROPERTY: {
2653 if (Record.size() != 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002654 return error("Invalid record");
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002655
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002656 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002657 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002658 GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002659 (Context, getMDString(Record[1]),
2660 getMDOrNull(Record[2]), Record[3],
2661 getMDString(Record[4]), getMDString(Record[5]),
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002662 Record[6], getDITypeRefOrNull(Record[7]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002663 NextMetadataNo++);
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002664 break;
2665 }
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002666 case bitc::METADATA_IMPORTED_ENTITY: {
2667 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002668 return error("Invalid record");
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002669
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002670 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002671 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002672 GET_OR_DISTINCT(DIImportedEntity,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002673 (Context, Record[1], getMDOrNull(Record[2]),
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002674 getDITypeRefOrNull(Record[3]), Record[4],
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002675 getMDString(Record[5]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002676 NextMetadataNo++);
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002677 break;
2678 }
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002679 case bitc::METADATA_STRING_OLD: {
Eli Bendersky5d5e18d2014-06-25 15:41:00 +00002680 std::string String(Record.begin(), Record.end());
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00002681
2682 // Test for upgrading !llvm.loop.
2683 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2684
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002685 Metadata *MD = MDString::get(Context, String);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002686 MetadataList.assignValue(MD, NextMetadataNo++);
Devang Patel7428d8a2009-07-22 17:43:22 +00002687 break;
2688 }
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002689 case bitc::METADATA_STRINGS:
2690 if (std::error_code EC =
2691 parseMetadataStrings(Record, Blob, NextMetadataNo))
2692 return EC;
2693 break;
Peter Collingbourne21521892016-06-21 23:42:48 +00002694 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
2695 if (Record.size() % 2 == 0)
2696 return error("Invalid record");
2697 unsigned ValueID = Record[0];
2698 if (ValueID >= ValueList.size())
2699 return error("Invalid record");
2700 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
2701 parseGlobalObjectAttachment(*GO, ArrayRef<uint64_t>(Record).slice(1));
2702 break;
2703 }
Devang Patelaf206b82009-09-18 19:26:43 +00002704 case bitc::METADATA_KIND: {
Teresa Johnson12545072015-11-15 02:00:09 +00002705 // Support older bitcode files that had METADATA_KIND records in a
2706 // block with METADATA_BLOCK_ID.
2707 if (std::error_code EC = parseMetadataKindRecord(Record))
2708 return EC;
Devang Patelaf206b82009-09-18 19:26:43 +00002709 break;
2710 }
Devang Patel7428d8a2009-07-22 17:43:22 +00002711 }
2712 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002713#undef GET_OR_DISTINCT
Devang Patel7428d8a2009-07-22 17:43:22 +00002714}
2715
Teresa Johnson12545072015-11-15 02:00:09 +00002716/// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2717std::error_code BitcodeReader::parseMetadataKinds() {
2718 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2719 return error("Invalid record");
2720
2721 SmallVector<uint64_t, 64> Record;
2722
2723 // Read all the records.
2724 while (1) {
2725 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2726
2727 switch (Entry.Kind) {
2728 case BitstreamEntry::SubBlock: // Handled for us already.
2729 case BitstreamEntry::Error:
2730 return error("Malformed block");
2731 case BitstreamEntry::EndBlock:
2732 return std::error_code();
2733 case BitstreamEntry::Record:
2734 // The interesting case.
2735 break;
2736 }
2737
2738 // Read a record.
2739 Record.clear();
2740 unsigned Code = Stream.readRecord(Entry.ID, Record);
2741 switch (Code) {
2742 default: // Default behavior: ignore.
2743 break;
2744 case bitc::METADATA_KIND: {
2745 if (std::error_code EC = parseMetadataKindRecord(Record))
2746 return EC;
2747 break;
2748 }
2749 }
2750 }
2751}
2752
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002753/// Decode a signed value stored with the sign bit in the LSB for dense VBR
2754/// encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002755uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00002756 if ((V & 1) == 0)
2757 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002758 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00002759 return -(V >> 1);
2760 // There is no such thing as -0 with integers. "-0" really means MININT.
2761 return 1ULL << 63;
2762}
2763
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002764/// Resolve all of the initializers for global values and aliases that we can.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002765std::error_code BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00002766 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002767 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
2768 IndirectSymbolInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002769 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002770 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
David Majnemer7fddecc2015-06-17 20:52:32 +00002771 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002772
Chris Lattner44c17072007-04-26 02:46:40 +00002773 GlobalInitWorklist.swap(GlobalInits);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002774 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002775 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002776 FunctionPrologueWorklist.swap(FunctionPrologues);
David Majnemer7fddecc2015-06-17 20:52:32 +00002777 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
Chris Lattner44c17072007-04-26 02:46:40 +00002778
2779 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00002780 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002781 if (ValID >= ValueList.size()) {
2782 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00002783 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002784 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002785 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00002786 GlobalInitWorklist.back().first->setInitializer(C);
2787 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002788 return error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00002789 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002790 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002791 }
2792
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002793 while (!IndirectSymbolInitWorklist.empty()) {
2794 unsigned ValID = IndirectSymbolInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002795 if (ValID >= ValueList.size()) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002796 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002797 } else {
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002798 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2799 if (!C)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002800 return error("Expected a constant");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002801 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2802 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002803 return error("Alias and aliasee types don't match");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002804 GIS->setIndirectSymbol(C);
Chris Lattner44c17072007-04-26 02:46:40 +00002805 }
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002806 IndirectSymbolInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002807 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002808
2809 while (!FunctionPrefixWorklist.empty()) {
2810 unsigned ValID = FunctionPrefixWorklist.back().second;
2811 if (ValID >= ValueList.size()) {
2812 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2813 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002814 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002815 FunctionPrefixWorklist.back().first->setPrefixData(C);
2816 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002817 return error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002818 }
2819 FunctionPrefixWorklist.pop_back();
2820 }
2821
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002822 while (!FunctionPrologueWorklist.empty()) {
2823 unsigned ValID = FunctionPrologueWorklist.back().second;
2824 if (ValID >= ValueList.size()) {
2825 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2826 } else {
2827 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2828 FunctionPrologueWorklist.back().first->setPrologueData(C);
2829 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002830 return error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002831 }
2832 FunctionPrologueWorklist.pop_back();
2833 }
2834
David Majnemer7fddecc2015-06-17 20:52:32 +00002835 while (!FunctionPersonalityFnWorklist.empty()) {
2836 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2837 if (ValID >= ValueList.size()) {
2838 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2839 } else {
2840 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2841 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2842 else
2843 return error("Expected a constant");
2844 }
2845 FunctionPersonalityFnWorklist.pop_back();
2846 }
2847
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002848 return std::error_code();
Chris Lattner44c17072007-04-26 02:46:40 +00002849}
2850
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002851static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002852 SmallVector<uint64_t, 8> Words(Vals.size());
2853 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00002854 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002855
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002856 return APInt(TypeBits, Words);
2857}
2858
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002859std::error_code BitcodeReader::parseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002860 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002861 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002862
2863 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002864
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002865 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00002866 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00002867 unsigned NextCstNo = ValueList.size();
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002868 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002869 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002870
Chris Lattner27d38752013-01-20 02:13:19 +00002871 switch (Entry.Kind) {
2872 case BitstreamEntry::SubBlock: // Handled for us already.
2873 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002874 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002875 case BitstreamEntry::EndBlock:
2876 if (NextCstNo != ValueList.size())
George Burgess IV1030d682016-01-20 22:15:23 +00002877 return error("Invalid constant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00002878
Chris Lattner27d38752013-01-20 02:13:19 +00002879 // Once all the constants have been read, go through and resolve forward
2880 // references.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002881 ValueList.resolveConstantForwardRefs();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002882 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002883 case BitstreamEntry::Record:
2884 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00002885 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002886 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002887
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002888 // Read a record.
2889 Record.clear();
Filipe Cabecinhas2849b482016-06-05 18:43:17 +00002890 Type *VoidType = Type::getVoidTy(Context);
Craig Topper2617dcc2014-04-15 06:32:26 +00002891 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002892 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002893 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002894 default: // Default behavior: unknown constant
2895 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00002896 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002897 break;
2898 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2899 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002900 return error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00002901 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002902 return error("Invalid record");
Filipe Cabecinhas2849b482016-06-05 18:43:17 +00002903 if (TypeList[Record[0]] == VoidType)
2904 return error("Invalid constant type");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002905 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00002906 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002907 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00002908 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002909 break;
2910 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002911 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002912 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002913 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00002914 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00002915 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002916 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002917 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002918
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002919 APInt VInt =
2920 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002921 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002922
Chris Lattner08feb1e2007-04-24 04:04:35 +00002923 break;
2924 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002925 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00002926 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002927 return error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00002928 if (CurTy->isHalfTy())
Tim Northover29178a32013-01-22 09:46:31 +00002929 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2930 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00002931 else if (CurTy->isFloatTy())
Tim Northover29178a32013-01-22 09:46:31 +00002932 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2933 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002934 else if (CurTy->isDoubleTy())
Tim Northover29178a32013-01-22 09:46:31 +00002935 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2936 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002937 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00002938 // Bits are not stored the same way as a normal i80 APInt, compensate.
2939 uint64_t Rearrange[2];
2940 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2941 Rearrange[1] = Record[0] >> 48;
Tim Northover29178a32013-01-22 09:46:31 +00002942 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2943 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002944 } else if (CurTy->isFP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002945 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2946 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002947 else if (CurTy->isPPC_FP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002948 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2949 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002950 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00002951 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002952 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00002953 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002954
Chris Lattnere14cb882007-05-04 19:11:41 +00002955 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2956 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002957 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002958
Chris Lattnere14cb882007-05-04 19:11:41 +00002959 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00002960 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002961
Chris Lattner229907c2011-07-18 04:54:35 +00002962 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00002963 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002964 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00002965 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00002966 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002967 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2968 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002969 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002970 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00002971 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002972 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2973 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002974 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002975 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00002976 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00002977 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002978 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00002979 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002980 break;
2981 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002982 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00002983 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2984 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002985 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002986
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002987 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002988 V = ConstantDataArray::getString(Context, Elts,
2989 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00002990 break;
2991 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002992 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2993 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002994 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002995
Chris Lattner372dd1e2012-01-30 00:51:16 +00002996 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
Chris Lattner372dd1e2012-01-30 00:51:16 +00002997 if (EltTy->isIntegerTy(8)) {
2998 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2999 if (isa<VectorType>(CurTy))
3000 V = ConstantDataVector::get(Context, Elts);
3001 else
3002 V = ConstantDataArray::get(Context, Elts);
3003 } else if (EltTy->isIntegerTy(16)) {
3004 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3005 if (isa<VectorType>(CurTy))
3006 V = ConstantDataVector::get(Context, Elts);
3007 else
3008 V = ConstantDataArray::get(Context, Elts);
3009 } else if (EltTy->isIntegerTy(32)) {
3010 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3011 if (isa<VectorType>(CurTy))
3012 V = ConstantDataVector::get(Context, Elts);
3013 else
3014 V = ConstantDataArray::get(Context, Elts);
3015 } else if (EltTy->isIntegerTy(64)) {
3016 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3017 if (isa<VectorType>(CurTy))
3018 V = ConstantDataVector::get(Context, Elts);
3019 else
3020 V = ConstantDataArray::get(Context, Elts);
Justin Bognera43eacb2016-01-06 22:31:32 +00003021 } else if (EltTy->isHalfTy()) {
3022 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3023 if (isa<VectorType>(CurTy))
3024 V = ConstantDataVector::getFP(Context, Elts);
3025 else
3026 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00003027 } else if (EltTy->isFloatTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00003028 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00003029 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00003030 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00003031 else
Justin Bognera43eacb2016-01-06 22:31:32 +00003032 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00003033 } else if (EltTy->isDoubleTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00003034 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00003035 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00003036 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00003037 else
Justin Bognera43eacb2016-01-06 22:31:32 +00003038 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00003039 } else {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003040 return error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00003041 }
3042 break;
3043 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003044 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003045 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003046 return error("Invalid record");
3047 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00003048 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00003049 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00003050 } else {
3051 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
3052 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00003053 unsigned Flags = 0;
3054 if (Record.size() >= 4) {
3055 if (Opc == Instruction::Add ||
3056 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003057 Opc == Instruction::Mul ||
3058 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00003059 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3060 Flags |= OverflowingBinaryOperator::NoSignedWrap;
3061 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3062 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003063 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003064 Opc == Instruction::UDiv ||
3065 Opc == Instruction::LShr ||
3066 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00003067 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00003068 Flags |= SDivOperator::IsExact;
3069 }
3070 }
3071 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00003072 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003073 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003074 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003075 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003076 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003077 return error("Invalid record");
3078 int Opc = getDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00003079 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00003080 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00003081 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00003082 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003083 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003084 return error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00003085 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003086 V = UpgradeBitCastExpr(Opc, Op, CurTy);
3087 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00003088 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003089 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003090 }
Dan Gohman1639c392009-07-27 21:53:46 +00003091 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003092 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
David Blaikieb9263572015-03-13 21:03:36 +00003093 unsigned OpNum = 0;
3094 Type *PointeeType = nullptr;
3095 if (Record.size() % 2)
3096 PointeeType = getTypeByID(Record[OpNum++]);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003097 SmallVector<Constant*, 16> Elts;
David Blaikieb9263572015-03-13 21:03:36 +00003098 while (OpNum != Record.size()) {
3099 Type *ElTy = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003100 if (!ElTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003101 return error("Invalid record");
David Blaikieb9263572015-03-13 21:03:36 +00003102 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003103 }
David Blaikieb9263572015-03-13 21:03:36 +00003104
David Blaikieb9263572015-03-13 21:03:36 +00003105 if (PointeeType &&
David Blaikie4a2e73b2015-04-02 18:55:32 +00003106 PointeeType !=
3107 cast<SequentialType>(Elts[0]->getType()->getScalarType())
3108 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003109 return error("Explicit gep operator type does not match pointee type "
David Blaikie12cf5d702015-03-16 22:03:50 +00003110 "of pointer operand");
David Blaikie4a2e73b2015-04-02 18:55:32 +00003111
Filipe Cabecinhasfc2a3c92016-06-05 18:43:26 +00003112 if (Elts.size() < 1)
3113 return error("Invalid gep with no operands");
3114
David Blaikie4a2e73b2015-04-02 18:55:32 +00003115 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3116 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
3117 BitCode ==
3118 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattner890683d2007-04-24 18:15:21 +00003119 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003120 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00003121 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003122 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003123 return error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00003124
3125 Type *SelectorTy = Type::getInt1Ty(Context);
3126
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00003127 // The selector might be an i1 or an <n x i1>
3128 // Get the type from the ValueList before getting a forward ref.
Joe Abbey1a6e7702013-09-12 22:02:31 +00003129 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00003130 if (Value *V = ValueList[Record[0]])
3131 if (SelectorTy != V->getType())
3132 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
Joe Abbey1a6e7702013-09-12 22:02:31 +00003133
3134 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
3135 SelectorTy),
3136 ValueList.getConstantFwdRef(Record[1],CurTy),
3137 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003138 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00003139 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003140 case bitc::CST_CODE_CE_EXTRACTELT
3141 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003142 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003143 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003144 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003145 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00003146 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003147 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003148 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003149 Constant *Op1 = nullptr;
3150 if (Record.size() == 4) {
3151 Type *IdxTy = getTypeByID(Record[2]);
3152 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003153 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003154 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
3155 } else // TODO: Remove with llvm 4.0
3156 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
3157 if (!Op1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003158 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00003159 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003160 break;
3161 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003162 case bitc::CST_CODE_CE_INSERTELT
3163 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00003164 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00003165 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003166 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003167 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
3168 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
3169 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003170 Constant *Op2 = nullptr;
3171 if (Record.size() == 4) {
3172 Type *IdxTy = getTypeByID(Record[2]);
3173 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003174 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003175 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
3176 } else // TODO: Remove with llvm 4.0
3177 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
3178 if (!Op2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003179 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00003180 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003181 break;
3182 }
3183 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00003184 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00003185 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003186 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003187 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
3188 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00003189 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00003190 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003191 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00003192 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003193 break;
3194 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00003195 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00003196 VectorType *RTy = dyn_cast<VectorType>(CurTy);
3197 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00003198 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00003199 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003200 return error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00003201 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3202 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00003203 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00003204 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00003205 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00003206 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00003207 break;
3208 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003209 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003210 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003211 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003212 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003213 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003214 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003215 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3216 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
3217
Duncan Sands9dff9be2010-02-15 16:12:20 +00003218 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00003219 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00003220 else
Owen Anderson487375e2009-07-29 18:55:55 +00003221 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003222 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00003223 }
Chad Rosierd8c76102012-09-05 19:00:49 +00003224 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00003225 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003226 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003227 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003228 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003229 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00003230 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00003231 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003232 unsigned AsmStrSize = Record[1];
3233 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003234 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003235 unsigned ConstStrSize = Record[2+AsmStrSize];
3236 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003237 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003238
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003239 for (unsigned i = 0; i != AsmStrSize; ++i)
3240 AsmStr += (char)Record[2+i];
3241 for (unsigned i = 0; i != ConstStrSize; ++i)
3242 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00003243 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003244 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00003245 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003246 break;
3247 }
Chad Rosierd8c76102012-09-05 19:00:49 +00003248 // This version adds support for the asm dialect keywords (e.g.,
3249 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003250 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003251 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003252 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003253 std::string AsmStr, ConstrStr;
3254 bool HasSideEffects = Record[0] & 1;
3255 bool IsAlignStack = (Record[0] >> 1) & 1;
3256 unsigned AsmDialect = Record[0] >> 2;
3257 unsigned AsmStrSize = Record[1];
3258 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003259 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003260 unsigned ConstStrSize = Record[2+AsmStrSize];
3261 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003262 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003263
3264 for (unsigned i = 0; i != AsmStrSize; ++i)
3265 AsmStr += (char)Record[2+i];
3266 for (unsigned i = 0; i != ConstStrSize; ++i)
3267 ConstrStr += (char)Record[3+AsmStrSize+i];
3268 PointerType *PTy = cast<PointerType>(CurTy);
3269 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
3270 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00003271 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003272 break;
3273 }
Chris Lattner5956dc82009-10-28 05:53:48 +00003274 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00003275 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003276 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003277 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003278 if (!FnTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003279 return error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00003280 Function *Fn =
3281 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00003282 if (!Fn)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003283 return error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003284
3285 // If the function is already parsed we can insert the block address right
3286 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003287 BasicBlock *BB;
3288 unsigned BBID = Record[2];
3289 if (!BBID)
3290 // Invalid reference to entry block.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003291 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003292 if (!Fn->empty()) {
3293 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003294 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003295 if (BBI == BBE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003296 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003297 ++BBI;
3298 }
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00003299 BB = &*BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003300 } else {
3301 // Otherwise insert a placeholder and remember it so it can be inserted
3302 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00003303 auto &FwdBBs = BasicBlockFwdRefs[Fn];
3304 if (FwdBBs.empty())
3305 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003306 if (FwdBBs.size() < BBID + 1)
3307 FwdBBs.resize(BBID + 1);
3308 if (!FwdBBs[BBID])
3309 FwdBBs[BBID] = BasicBlock::Create(Context);
3310 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003311 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003312 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00003313 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003314 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003315 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003316
David Majnemer8a1c45d2015-12-12 05:38:55 +00003317 ValueList.assignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00003318 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003319 }
3320}
Chris Lattner1314b992007-04-22 06:23:29 +00003321
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003322std::error_code BitcodeReader::parseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00003323 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003324 return error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00003325
Chad Rosierca2567b2011-12-07 21:44:12 +00003326 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003327 SmallVector<uint64_t, 64> Record;
Chad Rosierca2567b2011-12-07 21:44:12 +00003328 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00003329 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003330
Chris Lattner27d38752013-01-20 02:13:19 +00003331 switch (Entry.Kind) {
3332 case BitstreamEntry::SubBlock: // Handled for us already.
3333 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003334 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003335 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003336 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003337 case BitstreamEntry::Record:
3338 // The interesting case.
3339 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003340 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003341
Chad Rosierca2567b2011-12-07 21:44:12 +00003342 // Read a use list record.
3343 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003344 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00003345 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00003346 default: // Default behavior: unknown type.
3347 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003348 case bitc::USELIST_CODE_BB:
3349 IsBB = true;
3350 // fallthrough
3351 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00003352 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003353 if (RecordLength < 3)
3354 // Records should have at least an ID and two indexes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003355 return error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003356 unsigned ID = Record.back();
3357 Record.pop_back();
3358
3359 Value *V;
3360 if (IsBB) {
3361 assert(ID < FunctionBBs.size() && "Basic block not found");
3362 V = FunctionBBs[ID];
3363 } else
3364 V = ValueList[ID];
3365 unsigned NumUses = 0;
3366 SmallDenseMap<const Use *, unsigned, 16> Order;
Rafael Espindola257a3532016-01-15 19:00:20 +00003367 for (const Use &U : V->materialized_uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00003368 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003369 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00003370 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003371 }
3372 if (Order.size() != Record.size() || NumUses > Record.size())
3373 // Mismatches can happen if the functions are being materialized lazily
3374 // (out-of-order), or a value has been upgraded.
3375 break;
3376
3377 V->sortUseList([&](const Use &L, const Use &R) {
3378 return Order.lookup(&L) < Order.lookup(&R);
3379 });
Chad Rosierca2567b2011-12-07 21:44:12 +00003380 break;
3381 }
3382 }
3383 }
3384}
3385
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003386/// When we see the block for metadata, remember where it is and then skip it.
3387/// This lets us lazily deserialize the metadata.
3388std::error_code BitcodeReader::rememberAndSkipMetadata() {
3389 // Save the current stream state.
3390 uint64_t CurBit = Stream.GetCurrentBitNo();
3391 DeferredMetadataInfo.push_back(CurBit);
3392
3393 // Skip over the block for now.
3394 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003395 return error("Invalid record");
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003396 return std::error_code();
3397}
3398
3399std::error_code BitcodeReader::materializeMetadata() {
3400 for (uint64_t BitPos : DeferredMetadataInfo) {
3401 // Move the bit stream to the saved position.
3402 Stream.JumpToBit(BitPos);
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003403 if (std::error_code EC = parseMetadata(true))
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003404 return EC;
3405 }
3406 DeferredMetadataInfo.clear();
3407 return std::error_code();
3408}
3409
Rafael Espindola468b8682015-04-01 14:44:59 +00003410void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00003411
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003412/// When we see the block for a function body, remember where it is and then
3413/// skip it. This lets us lazily deserialize the functions.
3414std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003415 // Get the function we are talking about.
3416 if (FunctionsWithBodies.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003417 return error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003418
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003419 Function *Fn = FunctionsWithBodies.back();
3420 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003421
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003422 // Save the current stream state.
3423 uint64_t CurBit = Stream.GetCurrentBitNo();
Teresa Johnson1493ad92015-10-10 14:18:36 +00003424 assert(
3425 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3426 "Mismatch between VST and scanned function offsets");
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003427 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003428
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003429 // Skip over the function block for now.
3430 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003431 return error("Invalid record");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003432 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003433}
3434
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003435std::error_code BitcodeReader::globalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003436 // Patch the initializers for globals and aliases up.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003437 resolveGlobalAndIndirectSymbolInits();
3438 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003439 return error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003440
3441 // Look for intrinsic functions which need to be upgraded at some point
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003442 for (Function &F : *TheModule) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003443 Function *NewFn;
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003444 if (UpgradeIntrinsicFunction(&F, NewFn))
Rafael Espindola4e721212015-07-02 16:22:40 +00003445 UpgradedIntrinsics[&F] = NewFn;
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00003446 else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
3447 // Some types could be renamed during loading if several modules are
3448 // loaded in the same LLVMContext (LTO scenario). In this case we should
3449 // remangle intrinsics names as well.
3450 RemangledIntrinsics[&F] = Remangled.getValue();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003451 }
3452
3453 // Look for global variables which need to be renamed.
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003454 for (GlobalVariable &GV : TheModule->globals())
3455 UpgradeGlobalVariable(&GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00003456
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003457 // Force deallocation of memory for these vectors to favor the client that
3458 // want lazy deserialization.
3459 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003460 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap(
3461 IndirectSymbolInits);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003462 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003463}
3464
Teresa Johnson1493ad92015-10-10 14:18:36 +00003465/// Support for lazy parsing of function bodies. This is required if we
3466/// either have an old bitcode file without a VST forward declaration record,
3467/// or if we have an anonymous function being materialized, since anonymous
3468/// functions do not have a name and are therefore not in the VST.
3469std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3470 Stream.JumpToBit(NextUnreadBit);
3471
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003472 if (Stream.AtEndOfStream())
3473 return error("Could not find function in stream");
Teresa Johnson1493ad92015-10-10 14:18:36 +00003474
Filipe Cabecinhas7aae2f22015-11-03 13:48:26 +00003475 if (!SeenFirstFunctionBody)
3476 return error("Trying to materialize functions before seeing function blocks");
3477
Teresa Johnson1493ad92015-10-10 14:18:36 +00003478 // An old bitcode file with the symbol table at the end would have
3479 // finished the parse greedily.
3480 assert(SeenValueSymbolTable);
3481
3482 SmallVector<uint64_t, 64> Record;
3483
3484 while (1) {
3485 BitstreamEntry Entry = Stream.advance();
3486 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003487 default:
3488 return error("Expect SubBlock");
3489 case BitstreamEntry::SubBlock:
3490 switch (Entry.ID) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003491 default:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003492 return error("Expect function block");
3493 case bitc::FUNCTION_BLOCK_ID:
3494 if (std::error_code EC = rememberAndSkipFunctionBody())
3495 return EC;
3496 NextUnreadBit = Stream.GetCurrentBitNo();
3497 return std::error_code();
3498 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00003499 }
3500 }
3501}
3502
Mehdi Amini5d303282015-10-26 18:37:00 +00003503std::error_code BitcodeReader::parseBitcodeVersion() {
3504 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3505 return error("Invalid record");
3506
3507 // Read all the records.
3508 SmallVector<uint64_t, 64> Record;
3509 while (1) {
3510 BitstreamEntry Entry = Stream.advance();
3511
3512 switch (Entry.Kind) {
3513 default:
3514 case BitstreamEntry::Error:
3515 return error("Malformed block");
3516 case BitstreamEntry::EndBlock:
3517 return std::error_code();
3518 case BitstreamEntry::Record:
3519 // The interesting case.
3520 break;
3521 }
3522
3523 // Read a record.
3524 Record.clear();
3525 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3526 switch (BitCode) {
3527 default: // Default behavior: reject
3528 return error("Invalid value");
3529 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3530 // N]
3531 convertToString(Record, 0, ProducerIdentification);
3532 break;
3533 }
3534 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3535 unsigned epoch = (unsigned)Record[0];
3536 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
Oleksiy Vyalov6c2403f2015-10-26 22:37:36 +00003537 return error(
3538 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3539 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
Mehdi Amini5d303282015-10-26 18:37:00 +00003540 }
3541 }
3542 }
3543 }
3544}
3545
Teresa Johnson1493ad92015-10-10 14:18:36 +00003546std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003547 bool ShouldLazyLoadMetadata) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003548 if (ResumeBit)
3549 Stream.JumpToBit(ResumeBit);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003550 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003551 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003552
Chris Lattner1314b992007-04-22 06:23:29 +00003553 SmallVector<uint64_t, 64> Record;
3554 std::vector<std::string> SectionTable;
Gordon Henriksend930f912008-08-17 18:44:35 +00003555 std::vector<std::string> GCTable;
Chris Lattner1314b992007-04-22 06:23:29 +00003556
3557 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00003558 while (1) {
3559 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003560
Chris Lattner27d38752013-01-20 02:13:19 +00003561 switch (Entry.Kind) {
3562 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003563 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003564 case BitstreamEntry::EndBlock:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003565 return globalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00003566
Chris Lattner27d38752013-01-20 02:13:19 +00003567 case BitstreamEntry::SubBlock:
3568 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00003569 default: // Skip unknown content.
3570 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003571 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003572 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003573 case bitc::BLOCKINFO_BLOCK_ID:
3574 if (Stream.ReadBlockInfoBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003575 return error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003576 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003577 case bitc::PARAMATTR_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003578 if (std::error_code EC = parseAttributeBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003579 return EC;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003580 break;
Bill Wendlingba629332013-02-10 23:24:25 +00003581 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003582 if (std::error_code EC = parseAttributeGroupBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003583 return EC;
Bill Wendlingba629332013-02-10 23:24:25 +00003584 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003585 case bitc::TYPE_BLOCK_ID_NEW:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003586 if (std::error_code EC = parseTypeTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003587 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00003588 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00003589 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnsonff642b92015-09-17 20:12:00 +00003590 if (!SeenValueSymbolTable) {
3591 // Either this is an old form VST without function index and an
3592 // associated VST forward declaration record (which would have caused
3593 // the VST to be jumped to and parsed before it was encountered
3594 // normally in the stream), or there were no function blocks to
3595 // trigger an earlier parsing of the VST.
3596 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3597 if (std::error_code EC = parseValueSymbolTable())
3598 return EC;
3599 SeenValueSymbolTable = true;
3600 } else {
3601 // We must have had a VST forward declaration record, which caused
3602 // the parser to jump to and parse the VST earlier.
3603 assert(VSTOffset > 0);
3604 if (Stream.SkipBlock())
3605 return error("Invalid record");
3606 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00003607 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003608 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003609 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003610 return EC;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003611 if (std::error_code EC = resolveGlobalAndIndirectSymbolInits())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003612 return EC;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003613 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00003614 case bitc::METADATA_BLOCK_ID:
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003615 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3616 if (std::error_code EC = rememberAndSkipMetadata())
3617 return EC;
3618 break;
3619 }
3620 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003621 if (std::error_code EC = parseMetadata(true))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003622 return EC;
Devang Patel7428d8a2009-07-22 17:43:22 +00003623 break;
Teresa Johnson12545072015-11-15 02:00:09 +00003624 case bitc::METADATA_KIND_BLOCK_ID:
3625 if (std::error_code EC = parseMetadataKinds())
3626 return EC;
3627 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003628 case bitc::FUNCTION_BLOCK_ID:
3629 // If this is the first function body we've seen, reverse the
3630 // FunctionsWithBodies list.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003631 if (!SeenFirstFunctionBody) {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003632 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003633 if (std::error_code EC = globalCleanup())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003634 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003635 SeenFirstFunctionBody = true;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003636 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003637
Teresa Johnsonff642b92015-09-17 20:12:00 +00003638 if (VSTOffset > 0) {
3639 // If we have a VST forward declaration record, make sure we
3640 // parse the VST now if we haven't already. It is needed to
3641 // set up the DeferredFunctionInfo vector for lazy reading.
3642 if (!SeenValueSymbolTable) {
3643 if (std::error_code EC =
3644 BitcodeReader::parseValueSymbolTable(VSTOffset))
3645 return EC;
3646 SeenValueSymbolTable = true;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003647 // Fall through so that we record the NextUnreadBit below.
3648 // This is necessary in case we have an anonymous function that
3649 // is later materialized. Since it will not have a VST entry we
3650 // need to fall back to the lazy parse to find its offset.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003651 } else {
3652 // If we have a VST forward declaration record, but have already
3653 // parsed the VST (just above, when the first function body was
3654 // encountered here), then we are resuming the parse after
Teresa Johnson1493ad92015-10-10 14:18:36 +00003655 // materializing functions. The ResumeBit points to the
3656 // start of the last function block recorded in the
3657 // DeferredFunctionInfo map. Skip it.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003658 if (Stream.SkipBlock())
3659 return error("Invalid record");
3660 continue;
3661 }
3662 }
3663
3664 // Support older bitcode files that did not have the function
Teresa Johnson1493ad92015-10-10 14:18:36 +00003665 // index in the VST, nor a VST forward declaration record, as
3666 // well as anonymous functions that do not have VST entries.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003667 // Build the DeferredFunctionInfo vector on the fly.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003668 if (std::error_code EC = rememberAndSkipFunctionBody())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003669 return EC;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003670
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003671 // Suspend parsing when we reach the function bodies. Subsequent
3672 // materialization calls will resume it when necessary. If the bitcode
3673 // file is old, the symbol table will be at the end instead and will not
3674 // have been seen yet. In this case, just finish the parse now.
3675 if (SeenValueSymbolTable) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003676 NextUnreadBit = Stream.GetCurrentBitNo();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003677 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003678 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003679 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003680 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003681 if (std::error_code EC = parseUseLists())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003682 return EC;
Chad Rosierca2567b2011-12-07 21:44:12 +00003683 break;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003684 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3685 if (std::error_code EC = parseOperandBundleTags())
3686 return EC;
3687 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003688 }
3689 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003690
Chris Lattner27d38752013-01-20 02:13:19 +00003691 case BitstreamEntry::Record:
3692 // The interesting case.
3693 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003694 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003695
Chris Lattner1314b992007-04-22 06:23:29 +00003696 // Read a record.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003697 auto BitCode = Stream.readRecord(Entry.ID, Record);
3698 switch (BitCode) {
Chris Lattner1314b992007-04-22 06:23:29 +00003699 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungafaced02012-10-11 20:20:40 +00003700 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattner1314b992007-04-22 06:23:29 +00003701 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003702 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00003703 // Only version #0 and #1 are supported so far.
3704 unsigned module_version = Record[0];
3705 switch (module_version) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003706 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003707 return error("Invalid value");
Jan Wen Voungafaced02012-10-11 20:20:40 +00003708 case 0:
3709 UseRelativeIDs = false;
3710 break;
3711 case 1:
3712 UseRelativeIDs = true;
3713 break;
3714 }
Chris Lattner1314b992007-04-22 06:23:29 +00003715 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00003716 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003717 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003718 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003719 if (convertToString(Record, 0, S))
3720 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003721 TheModule->setTargetTriple(S);
3722 break;
3723 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003724 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003725 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003726 if (convertToString(Record, 0, S))
3727 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003728 TheModule->setDataLayout(S);
3729 break;
3730 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003731 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003732 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003733 if (convertToString(Record, 0, S))
3734 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003735 TheModule->setModuleInlineAsm(S);
3736 break;
3737 }
Bill Wendling706d3d62012-11-28 08:41:48 +00003738 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3739 // FIXME: Remove in 4.0.
3740 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003741 if (convertToString(Record, 0, S))
3742 return error("Invalid record");
Bill Wendling706d3d62012-11-28 08:41:48 +00003743 // Ignore value.
3744 break;
3745 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003746 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003747 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003748 if (convertToString(Record, 0, S))
3749 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003750 SectionTable.push_back(S);
3751 break;
3752 }
Gordon Henriksend930f912008-08-17 18:44:35 +00003753 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00003754 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003755 if (convertToString(Record, 0, S))
3756 return error("Invalid record");
Gordon Henriksend930f912008-08-17 18:44:35 +00003757 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00003758 break;
3759 }
David Majnemerdad0a642014-06-27 18:19:56 +00003760 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3761 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003762 return error("Invalid record");
David Majnemerdad0a642014-06-27 18:19:56 +00003763 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3764 unsigned ComdatNameSize = Record[1];
3765 std::string ComdatName;
3766 ComdatName.reserve(ComdatNameSize);
3767 for (unsigned i = 0; i != ComdatNameSize; ++i)
3768 ComdatName += (char)Record[2 + i];
3769 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3770 C->setSelectionKind(SK);
3771 ComdatList.push_back(C);
3772 break;
3773 }
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003774 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00003775 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00003776 // unnamed_addr, externally_initialized, dllstorageclass,
3777 // comdat]
Chris Lattner1314b992007-04-22 06:23:29 +00003778 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner4b00d922007-04-23 16:04:05 +00003779 if (Record.size() < 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003780 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003781 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003782 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003783 return error("Invalid record");
David Blaikie1a848da2015-04-27 19:58:56 +00003784 bool isConstant = Record[1] & 1;
3785 bool explicitType = Record[1] & 2;
3786 unsigned AddressSpace;
3787 if (explicitType) {
3788 AddressSpace = Record[1] >> 2;
3789 } else {
3790 if (!Ty->isPointerTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003791 return error("Invalid type for value");
David Blaikie1a848da2015-04-27 19:58:56 +00003792 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3793 Ty = cast<PointerType>(Ty)->getElementType();
3794 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003795
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003796 uint64_t RawLinkage = Record[3];
3797 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
JF Bastien30bf96b2015-02-22 19:32:03 +00003798 unsigned Alignment;
3799 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3800 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00003801 std::string Section;
3802 if (Record[5]) {
3803 if (Record[5]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003804 return error("Invalid ID");
Chris Lattner1314b992007-04-22 06:23:29 +00003805 Section = SectionTable[Record[5]-1];
3806 }
Chris Lattner4b00d922007-04-23 16:04:05 +00003807 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003808 // Local linkage must have default visibility.
3809 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3810 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003811 Visibility = getDecodedVisibility(Record[6]);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00003812
3813 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner53862f72007-05-06 19:27:46 +00003814 if (Record.size() > 7)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003815 TLM = getDecodedThreadLocalMode(Record[7]);
Chris Lattner1314b992007-04-22 06:23:29 +00003816
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003817 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola45e6c192011-01-08 16:42:36 +00003818 if (Record.size() > 8)
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003819 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003820
Michael Gottesman27e7ef32013-02-05 05:57:38 +00003821 bool ExternallyInitialized = false;
3822 if (Record.size() > 9)
3823 ExternallyInitialized = Record[9];
3824
Chris Lattner1314b992007-04-22 06:23:29 +00003825 GlobalVariable *NewGV =
Craig Topper2617dcc2014-04-15 06:32:26 +00003826 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
Michael Gottesman27e7ef32013-02-05 05:57:38 +00003827 TLM, AddressSpace, ExternallyInitialized);
Chris Lattner1314b992007-04-22 06:23:29 +00003828 NewGV->setAlignment(Alignment);
3829 if (!Section.empty())
3830 NewGV->setSection(Section);
3831 NewGV->setVisibility(Visibility);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003832 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003833
Nico Rieck7157bb72014-01-14 15:22:47 +00003834 if (Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003835 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003836 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003837 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00003838
Chris Lattnerccaa4482007-04-23 21:26:05 +00003839 ValueList.push_back(NewGV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003840
Chris Lattner47d131b2007-04-24 00:18:21 +00003841 // Remember which value to use for the global initializer.
3842 if (unsigned InitID = Record[2])
3843 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
David Majnemerdad0a642014-06-27 18:19:56 +00003844
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003845 if (Record.size() > 11) {
David Majnemerdad0a642014-06-27 18:19:56 +00003846 if (unsigned ComdatID = Record[11]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00003847 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003848 return error("Invalid global variable comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00003849 NewGV->setComdat(ComdatList[ComdatID - 1]);
3850 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003851 } else if (hasImplicitComdat(RawLinkage)) {
3852 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3853 }
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003854
Chris Lattner1314b992007-04-22 06:23:29 +00003855 break;
3856 }
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003857 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Nico Rieck7157bb72014-01-14 15:22:47 +00003858 // alignment, section, visibility, gc, unnamed_addr,
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003859 // prologuedata, dllstorageclass, comdat, prefixdata]
Chris Lattner1314b992007-04-22 06:23:29 +00003860 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003861 if (Record.size() < 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003862 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003863 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003864 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003865 return error("Invalid record");
David Blaikie561a1572015-04-17 16:28:26 +00003866 if (auto *PTy = dyn_cast<PointerType>(Ty))
3867 Ty = PTy->getElementType();
3868 auto *FTy = dyn_cast<FunctionType>(Ty);
Chris Lattner1314b992007-04-22 06:23:29 +00003869 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003870 return error("Invalid type for value");
Vedant Kumarad6d6e72015-10-27 21:17:06 +00003871 auto CC = static_cast<CallingConv::ID>(Record[1]);
3872 if (CC & ~CallingConv::MaxID)
3873 return error("Invalid calling convention ID");
Chris Lattner1314b992007-04-22 06:23:29 +00003874
Gabor Greife9ecc682008-04-06 20:25:17 +00003875 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3876 "", TheModule);
Chris Lattner1314b992007-04-22 06:23:29 +00003877
Vedant Kumarad6d6e72015-10-27 21:17:06 +00003878 Func->setCallingConv(CC);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003879 bool isProto = Record[2];
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003880 uint64_t RawLinkage = Record[3];
3881 Func->setLinkage(getDecodedLinkage(RawLinkage));
Devang Patel4c758ea2008-09-25 21:00:45 +00003882 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003883
JF Bastien30bf96b2015-02-22 19:32:03 +00003884 unsigned Alignment;
3885 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3886 return EC;
3887 Func->setAlignment(Alignment);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003888 if (Record[6]) {
3889 if (Record[6]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003890 return error("Invalid ID");
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003891 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattner1314b992007-04-22 06:23:29 +00003892 }
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003893 // Local linkage must have default visibility.
3894 if (!Func->hasLocalLinkage())
3895 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003896 Func->setVisibility(getDecodedVisibility(Record[7]));
Gordon Henriksen71183b62007-12-10 03:18:06 +00003897 if (Record.size() > 8 && Record[8]) {
Filipe Cabecinhasf8a16a92015-04-30 04:09:41 +00003898 if (Record[8]-1 >= GCTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003899 return error("Invalid ID");
Benjamin Kramer728f4442016-05-29 10:46:35 +00003900 Func->setGC(GCTable[Record[8] - 1]);
Gordon Henriksen71183b62007-12-10 03:18:06 +00003901 }
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003902 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola45e6c192011-01-08 16:42:36 +00003903 if (Record.size() > 9)
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003904 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003905 Func->setUnnamedAddr(UnnamedAddr);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003906 if (Record.size() > 10 && Record[10] != 0)
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003907 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
Nico Rieck7157bb72014-01-14 15:22:47 +00003908
3909 if (Record.size() > 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003910 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003911 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003912 upgradeDLLImportExportLinkage(Func, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00003913
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003914 if (Record.size() > 12) {
David Majnemerdad0a642014-06-27 18:19:56 +00003915 if (unsigned ComdatID = Record[12]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00003916 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003917 return error("Invalid function comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00003918 Func->setComdat(ComdatList[ComdatID - 1]);
3919 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003920 } else if (hasImplicitComdat(RawLinkage)) {
3921 Func->setComdat(reinterpret_cast<Comdat *>(1));
3922 }
David Majnemerdad0a642014-06-27 18:19:56 +00003923
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003924 if (Record.size() > 13 && Record[13] != 0)
3925 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3926
David Majnemer7fddecc2015-06-17 20:52:32 +00003927 if (Record.size() > 14 && Record[14] != 0)
3928 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3929
Chris Lattnerccaa4482007-04-23 21:26:05 +00003930 ValueList.push_back(Func);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003931
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003932 // If this is a function with a body, remember the prototype we are
3933 // creating now, so that we can match up the body with them later.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003934 if (!isProto) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00003935 Func->setIsMaterializable(true);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003936 FunctionsWithBodies.push_back(Func);
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003937 DeferredFunctionInfo[Func] = 0;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003938 }
Chris Lattner1314b992007-04-22 06:23:29 +00003939 break;
3940 }
David Blaikie6a51dbd2015-09-17 22:18:59 +00003941 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3942 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003943 // IFUNC: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3944 case bitc::MODULE_CODE_IFUNC:
David Blaikie6a51dbd2015-09-17 22:18:59 +00003945 case bitc::MODULE_CODE_ALIAS:
3946 case bitc::MODULE_CODE_ALIAS_OLD: {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003947 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
Aaron Ballman2d0f38c2015-09-18 13:31:42 +00003948 if (Record.size() < (3 + (unsigned)NewRecord))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003949 return error("Invalid record");
David Blaikie6a51dbd2015-09-17 22:18:59 +00003950 unsigned OpNum = 0;
3951 Type *Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003952 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003953 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003954
David Blaikie6a51dbd2015-09-17 22:18:59 +00003955 unsigned AddrSpace;
3956 if (!NewRecord) {
3957 auto *PTy = dyn_cast<PointerType>(Ty);
3958 if (!PTy)
3959 return error("Invalid type for value");
3960 Ty = PTy->getElementType();
3961 AddrSpace = PTy->getAddressSpace();
3962 } else {
3963 AddrSpace = Record[OpNum++];
3964 }
3965
3966 auto Val = Record[OpNum++];
3967 auto Linkage = Record[OpNum++];
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003968 GlobalIndirectSymbol *NewGA;
3969 if (BitCode == bitc::MODULE_CODE_ALIAS ||
3970 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003971 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
3972 "", TheModule);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003973 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003974 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
3975 "", nullptr, TheModule);
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00003976 // Old bitcode files didn't have visibility field.
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003977 // Local linkage must have default visibility.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003978 if (OpNum != Record.size()) {
3979 auto VisInd = OpNum++;
3980 if (!NewGA->hasLocalLinkage())
3981 // FIXME: Change to an error if non-default in 4.0.
3982 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3983 }
3984 if (OpNum != Record.size())
3985 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003986 else
David Blaikie6a51dbd2015-09-17 22:18:59 +00003987 upgradeDLLImportExportLinkage(NewGA, Linkage);
3988 if (OpNum != Record.size())
3989 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3990 if (OpNum != Record.size())
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003991 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
Chris Lattner44c17072007-04-26 02:46:40 +00003992 ValueList.push_back(NewGA);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003993 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
Chris Lattner44c17072007-04-26 02:46:40 +00003994 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003995 }
Chris Lattner831d4202007-04-26 03:27:58 +00003996 /// MODULE_CODE_PURGEVALS: [numvals]
3997 case bitc::MODULE_CODE_PURGEVALS:
3998 // Trim down the value list to the specified size.
3999 if (Record.size() < 1 || Record[0] > ValueList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004000 return error("Invalid record");
Chris Lattner831d4202007-04-26 03:27:58 +00004001 ValueList.shrinkTo(Record[0]);
4002 break;
Teresa Johnsonff642b92015-09-17 20:12:00 +00004003 /// MODULE_CODE_VSTOFFSET: [offset]
4004 case bitc::MODULE_CODE_VSTOFFSET:
4005 if (Record.size() < 1)
4006 return error("Invalid record");
4007 VSTOffset = Record[0];
4008 break;
Teresa Johnsone1164de2016-02-10 21:55:02 +00004009 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4010 case bitc::MODULE_CODE_SOURCE_FILENAME:
4011 SmallString<128> ValueName;
4012 if (convertToString(Record, 0, ValueName))
4013 return error("Invalid record");
4014 TheModule->setSourceFileName(ValueName);
4015 break;
Chris Lattner831d4202007-04-26 03:27:58 +00004016 }
Chris Lattner1314b992007-04-22 06:23:29 +00004017 Record.clear();
4018 }
Chris Lattner1314b992007-04-22 06:23:29 +00004019}
4020
Teresa Johnson403a7872015-10-04 14:33:43 +00004021/// Helper to read the header common to all bitcode files.
4022static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
4023 // Sniff for the signature.
4024 if (Stream.Read(8) != 'B' ||
4025 Stream.Read(8) != 'C' ||
4026 Stream.Read(4) != 0x0 ||
4027 Stream.Read(4) != 0xC ||
4028 Stream.Read(4) != 0xE ||
4029 Stream.Read(4) != 0xD)
4030 return false;
4031 return true;
4032}
4033
Rafael Espindola1aabf982015-06-16 23:29:49 +00004034std::error_code
4035BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
4036 Module *M, bool ShouldLazyLoadMetadata) {
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00004037 TheModule = M;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004038
Rafael Espindola1aabf982015-06-16 23:29:49 +00004039 if (std::error_code EC = initStream(std::move(Streamer)))
Rafael Espindola48da4f42013-11-04 16:16:24 +00004040 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004041
Chris Lattner1314b992007-04-22 06:23:29 +00004042 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004043 if (!hasValidBitcodeHeader(Stream))
4044 return error("Invalid bitcode signature");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004045
Chris Lattner1314b992007-04-22 06:23:29 +00004046 // We expect a number of well-defined blocks, though we don't necessarily
4047 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00004048 while (1) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00004049 if (Stream.AtEndOfStream()) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00004050 // We didn't really read a proper Module.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004051 return error("Malformed IR file");
Filipe Cabecinhas22554272015-04-14 14:07:15 +00004052 }
Joe Abbey97b7a172013-02-06 22:14:06 +00004053
Chris Lattner27d38752013-01-20 02:13:19 +00004054 BitstreamEntry Entry =
4055 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbey97b7a172013-02-06 22:14:06 +00004056
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00004057 if (Entry.Kind != BitstreamEntry::SubBlock)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004058 return error("Malformed block");
Joe Abbey97b7a172013-02-06 22:14:06 +00004059
Mehdi Amini5d303282015-10-26 18:37:00 +00004060 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
4061 parseBitcodeVersion();
4062 continue;
4063 }
4064
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00004065 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Teresa Johnson1493ad92015-10-10 14:18:36 +00004066 return parseModule(0, ShouldLazyLoadMetadata);
Joe Abbey97b7a172013-02-06 22:14:06 +00004067
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00004068 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004069 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00004070 }
Chris Lattner1314b992007-04-22 06:23:29 +00004071}
Chris Lattner6694f602007-04-29 07:54:31 +00004072
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004073ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
Bill Wendling0198ce02010-10-06 01:22:42 +00004074 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004075 return error("Invalid record");
Bill Wendling0198ce02010-10-06 01:22:42 +00004076
4077 SmallVector<uint64_t, 64> Record;
4078
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004079 std::string Triple;
Bill Wendling0198ce02010-10-06 01:22:42 +00004080 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00004081 while (1) {
4082 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00004083
Chris Lattner27d38752013-01-20 02:13:19 +00004084 switch (Entry.Kind) {
4085 case BitstreamEntry::SubBlock: // Handled for us already.
4086 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004087 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004088 case BitstreamEntry::EndBlock:
Rafael Espindolae6107792014-07-04 20:05:56 +00004089 return Triple;
Chris Lattner27d38752013-01-20 02:13:19 +00004090 case BitstreamEntry::Record:
4091 // The interesting case.
4092 break;
Bill Wendling0198ce02010-10-06 01:22:42 +00004093 }
4094
4095 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00004096 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling0198ce02010-10-06 01:22:42 +00004097 default: break; // Default behavior, ignore unknown content.
Bill Wendling0198ce02010-10-06 01:22:42 +00004098 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004099 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004100 if (convertToString(Record, 0, S))
4101 return error("Invalid record");
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004102 Triple = S;
Bill Wendling0198ce02010-10-06 01:22:42 +00004103 break;
4104 }
4105 }
4106 Record.clear();
4107 }
Rafael Espindolae6107792014-07-04 20:05:56 +00004108 llvm_unreachable("Exit infinite loop");
Bill Wendling0198ce02010-10-06 01:22:42 +00004109}
4110
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004111ErrorOr<std::string> BitcodeReader::parseTriple() {
Rafael Espindola1aabf982015-06-16 23:29:49 +00004112 if (std::error_code EC = initStream(nullptr))
Rafael Espindola48da4f42013-11-04 16:16:24 +00004113 return EC;
Bill Wendling0198ce02010-10-06 01:22:42 +00004114
4115 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004116 if (!hasValidBitcodeHeader(Stream))
4117 return error("Invalid bitcode signature");
Bill Wendling0198ce02010-10-06 01:22:42 +00004118
4119 // We expect a number of well-defined blocks, though we don't necessarily
4120 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00004121 while (1) {
4122 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00004123
Chris Lattner27d38752013-01-20 02:13:19 +00004124 switch (Entry.Kind) {
4125 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004126 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004127 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004128 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00004129
Chris Lattner27d38752013-01-20 02:13:19 +00004130 case BitstreamEntry::SubBlock:
4131 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Rafael Espindolad346cc82014-07-04 13:52:01 +00004132 return parseModuleTriple();
Joe Abbey97b7a172013-02-06 22:14:06 +00004133
Chris Lattner27d38752013-01-20 02:13:19 +00004134 // Ignore other sub-blocks.
Rafael Espindola48da4f42013-11-04 16:16:24 +00004135 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004136 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004137 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00004138
Chris Lattner27d38752013-01-20 02:13:19 +00004139 case BitstreamEntry::Record:
4140 Stream.skipRecord(Entry.ID);
4141 continue;
Bill Wendling0198ce02010-10-06 01:22:42 +00004142 }
4143 }
Bill Wendling0198ce02010-10-06 01:22:42 +00004144}
4145
Mehdi Amini3383ccc2015-11-09 02:46:41 +00004146ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
4147 if (std::error_code EC = initStream(nullptr))
4148 return EC;
4149
4150 // Sniff for the signature.
4151 if (!hasValidBitcodeHeader(Stream))
4152 return error("Invalid bitcode signature");
4153
4154 // We expect a number of well-defined blocks, though we don't necessarily
4155 // need to understand them all.
4156 while (1) {
4157 BitstreamEntry Entry = Stream.advance();
4158 switch (Entry.Kind) {
4159 case BitstreamEntry::Error:
4160 return error("Malformed block");
4161 case BitstreamEntry::EndBlock:
4162 return std::error_code();
4163
4164 case BitstreamEntry::SubBlock:
4165 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
4166 if (std::error_code EC = parseBitcodeVersion())
4167 return EC;
4168 return ProducerIdentification;
4169 }
4170 // Ignore other sub-blocks.
4171 if (Stream.SkipBlock())
4172 return error("Malformed block");
4173 continue;
4174 case BitstreamEntry::Record:
4175 Stream.skipRecord(Entry.ID);
4176 continue;
4177 }
4178 }
4179}
4180
Peter Collingbournecceae7f2016-05-31 23:01:54 +00004181std::error_code BitcodeReader::parseGlobalObjectAttachment(
4182 GlobalObject &GO, ArrayRef<uint64_t> Record) {
4183 assert(Record.size() % 2 == 0);
4184 for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
4185 auto K = MDKindMap.find(Record[I]);
4186 if (K == MDKindMap.end())
4187 return error("Invalid ID");
4188 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
4189 if (!MD)
4190 return error("Invalid metadata attachment");
Peter Collingbourne382d81c2016-06-01 01:17:57 +00004191 GO.addMetadata(K->second, *MD);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00004192 }
4193 return std::error_code();
4194}
4195
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004196/// Parse metadata attachments.
4197std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
Devang Patelaf206b82009-09-18 19:26:43 +00004198 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004199 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004200
Devang Patelaf206b82009-09-18 19:26:43 +00004201 SmallVector<uint64_t, 64> Record;
Chris Lattner27d38752013-01-20 02:13:19 +00004202 while (1) {
4203 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00004204
Chris Lattner27d38752013-01-20 02:13:19 +00004205 switch (Entry.Kind) {
4206 case BitstreamEntry::SubBlock: // Handled for us already.
4207 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004208 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004209 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004210 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00004211 case BitstreamEntry::Record:
4212 // The interesting case.
Devang Patelaf206b82009-09-18 19:26:43 +00004213 break;
4214 }
Chris Lattner27d38752013-01-20 02:13:19 +00004215
Devang Patelaf206b82009-09-18 19:26:43 +00004216 // Read a metadata attachment record.
4217 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00004218 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patelaf206b82009-09-18 19:26:43 +00004219 default: // Default behavior: ignore.
4220 break;
Chris Lattnerb8778552011-06-17 17:50:30 +00004221 case bitc::METADATA_ATTACHMENT: {
Devang Patelaf206b82009-09-18 19:26:43 +00004222 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00004223 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004224 return error("Invalid record");
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00004225 if (RecordLength % 2 == 0) {
4226 // A function attachment.
Peter Collingbournecceae7f2016-05-31 23:01:54 +00004227 if (std::error_code EC = parseGlobalObjectAttachment(F, Record))
4228 return EC;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00004229 continue;
4230 }
4231
4232 // An instruction attachment.
Devang Patelaf206b82009-09-18 19:26:43 +00004233 Instruction *Inst = InstructionList[Record[0]];
4234 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patelb1a44772009-09-28 21:14:55 +00004235 unsigned Kind = Record[i];
Dan Gohman43aa8f02010-07-20 21:42:28 +00004236 DenseMap<unsigned, unsigned>::iterator I =
4237 MDKindMap.find(Kind);
4238 if (I == MDKindMap.end())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004239 return error("Invalid ID");
Justin Bognerae341c62016-03-17 20:12:06 +00004240 Metadata *Node = MetadataList.getMetadataFwdRef(Record[i + 1]);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004241 if (isa<LocalAsMetadata>(Node))
Duncan P. N. Exon Smith35303fd2014-12-06 02:29:44 +00004242 // Drop the attachment. This used to be legal, but there's no
4243 // upgrade path.
4244 break;
Justin Bognerae341c62016-03-17 20:12:06 +00004245 MDNode *MD = dyn_cast_or_null<MDNode>(Node);
4246 if (!MD)
4247 return error("Invalid metadata attachment");
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00004248
4249 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
4250 MD = upgradeInstructionLoopAttachment(*MD);
4251
Justin Bognerae341c62016-03-17 20:12:06 +00004252 Inst->setMetadata(I->second, MD);
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00004253 if (I->second == LLVMContext::MD_tbaa) {
Manman Ren209b17c2013-09-28 00:22:27 +00004254 InstsWithTBAATag.push_back(Inst);
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00004255 continue;
4256 }
Devang Patelaf206b82009-09-18 19:26:43 +00004257 }
4258 break;
4259 }
4260 }
4261 }
Devang Patelaf206b82009-09-18 19:26:43 +00004262}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004263
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004264static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
4265 LLVMContext &Context = PtrType->getContext();
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004266 if (!isa<PointerType>(PtrType))
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004267 return error(Context, "Load/Store operand is not a pointer type");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004268 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
4269
4270 if (ValType && ValType != ElemType)
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004271 return error(Context, "Explicit load/store type does not match pointee "
4272 "type of pointer operand");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004273 if (!PointerType::isLoadableOrStorableType(ElemType))
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004274 return error(Context, "Cannot load/store from pointer");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004275 return std::error_code();
4276}
4277
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004278/// Lazily parse the specified function body block.
4279std::error_code BitcodeReader::parseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00004280 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004281 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004282
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00004283 // Unexpected unresolved metadata when parsing function.
4284 if (MetadataList.hasFwdRefs())
4285 return error("Invalid function metadata: incoming forward references");
4286
Nick Lewyckya72e1af2010-02-25 08:30:17 +00004287 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00004288 unsigned ModuleValueListSize = ValueList.size();
Teresa Johnson61b406e2015-12-29 23:00:22 +00004289 unsigned ModuleMetadataListSize = MetadataList.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004290
Chris Lattner85b7b402007-05-01 05:52:21 +00004291 // Add all the function arguments to the value table.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00004292 for (Argument &I : F->args())
4293 ValueList.push_back(&I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004294
Chris Lattner83930552007-05-01 07:01:57 +00004295 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00004296 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00004297 unsigned CurBBNo = 0;
4298
Chris Lattner07d09ed2010-04-03 02:17:50 +00004299 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004300 auto getLastInstruction = [&]() -> Instruction * {
4301 if (CurBB && !CurBB->empty())
4302 return &CurBB->back();
4303 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4304 !FunctionBBs[CurBBNo - 1]->empty())
4305 return &FunctionBBs[CurBBNo - 1]->back();
4306 return nullptr;
4307 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004308
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004309 std::vector<OperandBundleDef> OperandBundles;
4310
Chris Lattner85b7b402007-05-01 05:52:21 +00004311 // Read all the records.
4312 SmallVector<uint64_t, 64> Record;
4313 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00004314 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00004315
Chris Lattner27d38752013-01-20 02:13:19 +00004316 switch (Entry.Kind) {
4317 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004318 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004319 case BitstreamEntry::EndBlock:
4320 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00004321
Chris Lattner27d38752013-01-20 02:13:19 +00004322 case BitstreamEntry::SubBlock:
4323 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00004324 default: // Skip unknown content.
4325 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004326 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00004327 break;
4328 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004329 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004330 return EC;
Chris Lattner83930552007-05-01 07:01:57 +00004331 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00004332 break;
4333 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004334 if (std::error_code EC = parseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004335 return EC;
Chris Lattner85b7b402007-05-01 05:52:21 +00004336 break;
Devang Patelaf206b82009-09-18 19:26:43 +00004337 case bitc::METADATA_ATTACHMENT_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004338 if (std::error_code EC = parseMetadataAttachment(*F))
Rafael Espindola48da4f42013-11-04 16:16:24 +00004339 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004340 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00004341 case bitc::METADATA_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004342 if (std::error_code EC = parseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004343 return EC;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00004344 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004345 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004346 if (std::error_code EC = parseUseLists())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004347 return EC;
4348 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00004349 }
4350 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00004351
Chris Lattner27d38752013-01-20 02:13:19 +00004352 case BitstreamEntry::Record:
4353 // The interesting case.
4354 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00004355 }
Joe Abbey97b7a172013-02-06 22:14:06 +00004356
Chris Lattner85b7b402007-05-01 05:52:21 +00004357 // Read a record.
4358 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00004359 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00004360 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00004361 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00004362 default: // Default behavior: reject
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004363 return error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004364 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00004365 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004366 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00004367 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00004368 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004369
4370 // See if anything took the address of blocks in this function.
4371 auto BBFRI = BasicBlockFwdRefs.find(F);
4372 if (BBFRI == BasicBlockFwdRefs.end()) {
4373 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4374 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
4375 } else {
4376 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00004377 // Check for invalid basic block references.
4378 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004379 return error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00004380 assert(!BBRefs.empty() && "Unexpected empty array");
4381 assert(!BBRefs.front() && "Invalid reference to entry block");
4382 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4383 ++I)
4384 if (I < RE && BBRefs[I]) {
4385 BBRefs[I]->insertInto(F);
4386 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004387 } else {
4388 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4389 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004390
4391 // Erase from the table.
4392 BasicBlockFwdRefs.erase(BBFRI);
4393 }
4394
Chris Lattner83930552007-05-01 07:01:57 +00004395 CurBB = FunctionBBs[0];
4396 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004397 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004398
Chris Lattner07d09ed2010-04-03 02:17:50 +00004399 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4400 // This record indicates that the last instruction is at the same
4401 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004402 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004403
Craig Topper2617dcc2014-04-15 06:32:26 +00004404 if (!I)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004405 return error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00004406 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004407 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004408 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004409
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00004410 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004411 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00004412 if (!I || Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004413 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004414
Chris Lattner07d09ed2010-04-03 02:17:50 +00004415 unsigned Line = Record[0], Col = Record[1];
4416 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004417
Craig Topper2617dcc2014-04-15 06:32:26 +00004418 MDNode *Scope = nullptr, *IA = nullptr;
Justin Bognerae341c62016-03-17 20:12:06 +00004419 if (ScopeID) {
4420 Scope = MetadataList.getMDNodeFwdRefOrNull(ScopeID - 1);
4421 if (!Scope)
4422 return error("Invalid record");
4423 }
4424 if (IAID) {
4425 IA = MetadataList.getMDNodeFwdRefOrNull(IAID - 1);
4426 if (!IA)
4427 return error("Invalid record");
4428 }
Chris Lattner07d09ed2010-04-03 02:17:50 +00004429 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4430 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004431 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004432 continue;
4433 }
4434
Chris Lattnere9759c22007-05-06 00:21:25 +00004435 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4436 unsigned OpNum = 0;
4437 Value *LHS, *RHS;
4438 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004439 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00004440 OpNum+1 > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004441 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004442
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004443 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00004444 if (Opc == -1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004445 return error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004446 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00004447 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00004448 if (OpNum < Record.size()) {
4449 if (Opc == Instruction::Add ||
4450 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00004451 Opc == Instruction::Mul ||
4452 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00004453 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00004454 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00004455 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00004456 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00004457 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00004458 Opc == Instruction::UDiv ||
4459 Opc == Instruction::LShr ||
4460 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00004461 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00004462 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004463 } else if (isa<FPMathOperator>(I)) {
James Molloy88eb5352015-07-10 12:52:00 +00004464 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004465 if (FMF.any())
4466 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00004467 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004468
Dan Gohman1b849082009-09-07 23:54:19 +00004469 }
Chris Lattner85b7b402007-05-01 05:52:21 +00004470 break;
4471 }
Chris Lattnere9759c22007-05-06 00:21:25 +00004472 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4473 unsigned OpNum = 0;
4474 Value *Op;
4475 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4476 OpNum+2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004477 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004478
Chris Lattner229907c2011-07-18 04:54:35 +00004479 Type *ResTy = getTypeByID(Record[OpNum]);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004480 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004481 if (Opc == -1 || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004482 return error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00004483 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004484 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4485 if (Temp) {
4486 InstructionList.push_back(Temp);
4487 CurBB->getInstList().push_back(Temp);
4488 }
4489 } else {
Filipe Cabecinhasb70fd872015-10-06 12:37:54 +00004490 auto CastOp = (Instruction::CastOps)Opc;
4491 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4492 return error("Invalid cast");
4493 I = CastInst::Create(CastOp, Op, ResTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004494 }
Devang Patelaf206b82009-09-18 19:26:43 +00004495 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004496 break;
4497 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00004498 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4499 case bitc::FUNC_CODE_INST_GEP_OLD:
4500 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004501 unsigned OpNum = 0;
David Blaikieb5b5efd2015-02-25 01:08:52 +00004502
4503 Type *Ty;
4504 bool InBounds;
4505
4506 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4507 InBounds = Record[OpNum++];
4508 Ty = getTypeByID(Record[OpNum++]);
4509 } else {
4510 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4511 Ty = nullptr;
4512 }
4513
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004514 Value *BasePtr;
4515 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004516 return error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00004517
David Blaikie60310f22015-05-08 00:42:26 +00004518 if (!Ty)
4519 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4520 ->getElementType();
4521 else if (Ty !=
4522 cast<SequentialType>(BasePtr->getType()->getScalarType())
4523 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004524 return error(
David Blaikie675e8cb2015-03-16 21:35:48 +00004525 "Explicit gep type does not match pointee type of pointer operand");
4526
Chris Lattner5285b5e2007-05-02 05:46:45 +00004527 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004528 while (OpNum != Record.size()) {
4529 Value *Op;
4530 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004531 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004532 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004533 }
4534
David Blaikie096b1da2015-03-14 19:53:33 +00004535 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
David Blaikie675e8cb2015-03-16 21:35:48 +00004536
Devang Patelaf206b82009-09-18 19:26:43 +00004537 InstructionList.push_back(I);
David Blaikieb5b5efd2015-02-25 01:08:52 +00004538 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004539 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004540 break;
4541 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004542
Dan Gohman1ecaf452008-05-31 00:58:22 +00004543 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4544 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00004545 unsigned OpNum = 0;
4546 Value *Agg;
4547 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004548 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004549
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004550 unsigned RecSize = Record.size();
4551 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004552 return error("EXTRACTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004553
Dan Gohman1ecaf452008-05-31 00:58:22 +00004554 SmallVector<unsigned, 4> EXTRACTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004555 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004556 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004557 bool IsArray = CurTy->isArrayTy();
4558 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00004559 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004560
4561 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004562 return error("EXTRACTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004563 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004564 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004565 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004566 return error("EXTRACTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004567 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004568 return error("EXTRACTVAL: Invalid array index");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004569 EXTRACTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004570
4571 if (IsStruct)
4572 CurTy = CurTy->subtypes()[Index];
4573 else
4574 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00004575 }
4576
Jay Foad57aa6362011-07-13 10:26:04 +00004577 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00004578 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00004579 break;
4580 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004581
Dan Gohman1ecaf452008-05-31 00:58:22 +00004582 case bitc::FUNC_CODE_INST_INSERTVAL: {
4583 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00004584 unsigned OpNum = 0;
4585 Value *Agg;
4586 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004587 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004588 Value *Val;
4589 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004590 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004591
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004592 unsigned RecSize = Record.size();
4593 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004594 return error("INSERTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004595
Dan Gohman1ecaf452008-05-31 00:58:22 +00004596 SmallVector<unsigned, 4> INSERTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004597 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004598 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004599 bool IsArray = CurTy->isArrayTy();
4600 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00004601 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004602
4603 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004604 return error("INSERTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004605 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004606 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004607 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004608 return error("INSERTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004609 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004610 return error("INSERTVAL: Invalid array index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004611
Dan Gohman1ecaf452008-05-31 00:58:22 +00004612 INSERTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004613 if (IsStruct)
4614 CurTy = CurTy->subtypes()[Index];
4615 else
4616 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00004617 }
4618
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00004619 if (CurTy != Val->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004620 return error("Inserted value type doesn't match aggregate type");
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00004621
Jay Foad57aa6362011-07-13 10:26:04 +00004622 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00004623 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00004624 break;
4625 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004626
Chris Lattnere9759c22007-05-06 00:21:25 +00004627 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00004628 // obsolete form of select
4629 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00004630 unsigned OpNum = 0;
4631 Value *TrueVal, *FalseVal, *Cond;
4632 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004633 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4634 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004635 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004636
Dan Gohmanc5d28922008-09-16 01:01:33 +00004637 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00004638 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00004639 break;
4640 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004641
Dan Gohmanc5d28922008-09-16 01:01:33 +00004642 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4643 // new form of select
4644 // handles select i1 or select [N x i1]
4645 unsigned OpNum = 0;
4646 Value *TrueVal, *FalseVal, *Cond;
4647 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004648 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00004649 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004650 return error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00004651
4652 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00004653 if (VectorType* vector_type =
4654 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00004655 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004656 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004657 return error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00004658 } else {
4659 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004660 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004661 return error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004662 }
4663
Gabor Greife9ecc682008-04-06 20:25:17 +00004664 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00004665 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004666 break;
4667 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004668
Chris Lattner1fc27f02007-05-02 05:16:49 +00004669 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00004670 unsigned OpNum = 0;
4671 Value *Vec, *Idx;
4672 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00004673 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004674 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004675 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004676 return error("Invalid type for value");
Eric Christopherc9742252009-07-25 02:28:41 +00004677 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00004678 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004679 break;
4680 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004681
Chris Lattner1fc27f02007-05-02 05:16:49 +00004682 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00004683 unsigned OpNum = 0;
4684 Value *Vec, *Elt, *Idx;
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004685 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004686 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004687 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004688 return error("Invalid type for value");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004689 if (popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00004690 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00004691 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004692 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00004693 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00004694 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004695 break;
4696 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004697
Chris Lattnere9759c22007-05-06 00:21:25 +00004698 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4699 unsigned OpNum = 0;
4700 Value *Vec1, *Vec2, *Mask;
4701 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004702 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004703 return error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00004704
Mon P Wang25f01062008-11-10 04:46:22 +00004705 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004706 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004707 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004708 return error("Invalid type for value");
Chris Lattner1fc27f02007-05-02 05:16:49 +00004709 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00004710 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004711 break;
4712 }
Mon P Wang25f01062008-11-10 04:46:22 +00004713
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004714 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4715 // Old form of ICmp/FCmp returning bool
4716 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4717 // both legal on vectors but had different behaviour.
4718 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4719 // FCmp/ICmp returning bool or vector of bool
4720
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004721 unsigned OpNum = 0;
4722 Value *LHS, *RHS;
4723 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
James Molloy88eb5352015-07-10 12:52:00 +00004724 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4725 return error("Invalid record");
4726
4727 unsigned PredVal = Record[OpNum];
4728 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4729 FastMathFlags FMF;
4730 if (IsFP && Record.size() > OpNum+1)
4731 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4732
4733 if (OpNum+1 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004734 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004735
Duncan Sands9dff9be2010-02-15 16:12:20 +00004736 if (LHS->getType()->isFPOrFPVectorTy())
James Molloy88eb5352015-07-10 12:52:00 +00004737 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004738 else
James Molloy88eb5352015-07-10 12:52:00 +00004739 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4740
4741 if (FMF.any())
4742 I->setFastMathFlags(FMF);
Devang Patelaf206b82009-09-18 19:26:43 +00004743 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00004744 break;
4745 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004746
Chris Lattnere53603e2007-05-02 04:27:25 +00004747 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00004748 {
4749 unsigned Size = Record.size();
4750 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00004751 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004752 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00004753 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004754 }
Devang Patelbbfd8742008-02-26 01:29:32 +00004755
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004756 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004757 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00004758 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004759 return error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00004760 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004761 return error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004762
Chris Lattnerf1c87102011-06-17 18:09:11 +00004763 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004764 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004765 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00004766 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004767 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00004768 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004769 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004770 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004771 if (!TrueDest)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004772 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004773
Devang Patelaf206b82009-09-18 19:26:43 +00004774 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00004775 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004776 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00004777 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004778 else {
4779 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004780 Value *Cond = getValue(Record, 2, NextValueNo,
4781 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00004782 if (!FalseDest || !Cond)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004783 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00004784 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004785 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004786 }
4787 break;
4788 }
David Majnemerb01aa9f2015-08-23 19:22:31 +00004789 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004790 if (Record.size() != 1 && Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00004791 return error("Invalid record");
4792 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004793 Value *CleanupPad =
4794 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004795 if (!CleanupPad)
David Majnemer654e1302015-07-31 17:58:14 +00004796 return error("Invalid record");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004797 BasicBlock *UnwindDest = nullptr;
4798 if (Record.size() == 2) {
David Majnemer654e1302015-07-31 17:58:14 +00004799 UnwindDest = getBasicBlock(Record[Idx++]);
4800 if (!UnwindDest)
4801 return error("Invalid record");
4802 }
4803
David Majnemer8a1c45d2015-12-12 05:38:55 +00004804 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
David Majnemer654e1302015-07-31 17:58:14 +00004805 InstructionList.push_back(I);
4806 break;
4807 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004808 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4809 if (Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00004810 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004811 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004812 Value *CatchPad =
4813 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004814 if (!CatchPad)
4815 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004816 BasicBlock *BB = getBasicBlock(Record[Idx++]);
David Majnemer654e1302015-07-31 17:58:14 +00004817 if (!BB)
4818 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004819
David Majnemer8a1c45d2015-12-12 05:38:55 +00004820 I = CatchReturnInst::Create(CatchPad, BB);
David Majnemer654e1302015-07-31 17:58:14 +00004821 InstructionList.push_back(I);
4822 break;
4823 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004824 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4825 // We must have, at minimum, the outer scope and the number of arguments.
4826 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00004827 return error("Invalid record");
4828
David Majnemer654e1302015-07-31 17:58:14 +00004829 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004830
4831 Value *ParentPad =
4832 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4833
4834 unsigned NumHandlers = Record[Idx++];
4835
4836 SmallVector<BasicBlock *, 2> Handlers;
4837 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4838 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4839 if (!BB)
David Majnemer654e1302015-07-31 17:58:14 +00004840 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004841 Handlers.push_back(BB);
4842 }
4843
4844 BasicBlock *UnwindDest = nullptr;
4845 if (Idx + 1 == Record.size()) {
David Majnemer654e1302015-07-31 17:58:14 +00004846 UnwindDest = getBasicBlock(Record[Idx++]);
4847 if (!UnwindDest)
4848 return error("Invalid record");
4849 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004850
4851 if (Record.size() != Idx)
4852 return error("Invalid record");
4853
4854 auto *CatchSwitch =
4855 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4856 for (BasicBlock *Handler : Handlers)
4857 CatchSwitch->addHandler(Handler);
4858 I = CatchSwitch;
4859 InstructionList.push_back(I);
4860 break;
4861 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004862 case bitc::FUNC_CODE_INST_CATCHPAD:
4863 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4864 // We must have, at minimum, the outer scope and the number of arguments.
4865 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00004866 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004867
David Majnemer654e1302015-07-31 17:58:14 +00004868 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004869
4870 Value *ParentPad =
4871 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4872
David Majnemer654e1302015-07-31 17:58:14 +00004873 unsigned NumArgOperands = Record[Idx++];
David Majnemer8a1c45d2015-12-12 05:38:55 +00004874
David Majnemer654e1302015-07-31 17:58:14 +00004875 SmallVector<Value *, 2> Args;
4876 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4877 Value *Val;
4878 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4879 return error("Invalid record");
4880 Args.push_back(Val);
4881 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004882
David Majnemer654e1302015-07-31 17:58:14 +00004883 if (Record.size() != Idx)
4884 return error("Invalid record");
4885
David Majnemer8a1c45d2015-12-12 05:38:55 +00004886 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4887 I = CleanupPadInst::Create(ParentPad, Args);
4888 else
4889 I = CatchPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00004890 InstructionList.push_back(I);
4891 break;
4892 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00004893 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004894 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004895 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00004896 // "New" SwitchInst format with case ranges. The changes to write this
4897 // format were reverted but we still recognize bitcode that uses it.
4898 // Hopefully someday we will have support for case ranges and can use
4899 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004900
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004901 Type *OpTy = getTypeByID(Record[1]);
4902 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4903
Jan Wen Voungafaced02012-10-11 20:20:40 +00004904 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004905 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004906 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004907 return error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004908
4909 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004910
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004911 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4912 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004913
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004914 unsigned CurIdx = 5;
4915 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00004916 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004917 unsigned NumItems = Record[CurIdx++];
4918 for (unsigned ci = 0; ci != NumItems; ++ci) {
4919 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004920
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004921 APInt Low;
4922 unsigned ActiveWords = 1;
4923 if (ValueBitWidth > 64)
4924 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004925 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
Benjamin Kramer9704ed02012-05-28 14:10:31 +00004926 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004927 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00004928
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004929 if (!isSingleNumber) {
4930 ActiveWords = 1;
4931 if (ValueBitWidth > 64)
4932 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004933 APInt High = readWideAPInt(
4934 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004935 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00004936
4937 // FIXME: It is not clear whether values in the range should be
4938 // compared as signed or unsigned values. The partially
4939 // implemented changes that used this format in the past used
4940 // unsigned comparisons.
4941 for ( ; Low.ule(High); ++Low)
4942 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004943 } else
Bob Wilsone4077362013-09-09 19:14:35 +00004944 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004945 }
4946 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00004947 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4948 cve = CaseVals.end(); cvi != cve; ++cvi)
4949 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004950 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004951 I = SI;
4952 break;
4953 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004954
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004955 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004956
Chris Lattner5285b5e2007-05-02 05:46:45 +00004957 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004958 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004959 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004960 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004961 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004962 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004963 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004964 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00004965 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00004966 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004967 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004968 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00004969 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4970 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004971 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00004972 delete SI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004973 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004974 }
4975 SI->addCase(CaseVal, DestBB);
4976 }
4977 I = SI;
4978 break;
4979 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004980 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00004981 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004982 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004983 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004984 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00004985 if (!OpTy || !Address)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004986 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004987 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004988 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00004989 InstructionList.push_back(IBI);
4990 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4991 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4992 IBI->addDestination(DestBB);
4993 } else {
4994 delete IBI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004995 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004996 }
4997 }
4998 I = IBI;
4999 break;
5000 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005001
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00005002 case bitc::FUNC_CODE_INST_INVOKE: {
5003 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00005004 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005005 return error("Invalid record");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005006 unsigned OpNum = 0;
5007 AttributeSet PAL = getAttributes(Record[OpNum++]);
5008 unsigned CCInfo = Record[OpNum++];
5009 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5010 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005011
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005012 FunctionType *FTy = nullptr;
5013 if (CCInfo >> 13 & 1 &&
5014 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005015 return error("Explicit invoke type is not a function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005016
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005017 Value *Callee;
5018 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005019 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005020
Chris Lattner229907c2011-07-18 04:54:35 +00005021 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005022 if (!CalleeTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005023 return error("Callee is not a pointer");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005024 if (!FTy) {
5025 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
5026 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005027 return error("Callee is not of pointer to function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005028 } else if (CalleeTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005029 return error("Explicit invoke type does not match pointee type of "
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005030 "callee operand");
5031 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005032 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005033
Chris Lattner5285b5e2007-05-02 05:46:45 +00005034 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005035 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00005036 Ops.push_back(getValue(Record, OpNum, NextValueNo,
5037 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00005038 if (!Ops.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005039 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00005040 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005041
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005042 if (!FTy->isVarArg()) {
5043 if (Record.size() != OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005044 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00005045 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005046 // Read type/value pairs for varargs params.
5047 while (OpNum != Record.size()) {
5048 Value *Op;
5049 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005050 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005051 Ops.push_back(Op);
5052 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00005053 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005054
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005055 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
5056 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00005057 InstructionList.push_back(I);
Vedant Kumarad6d6e72015-10-27 21:17:06 +00005058 cast<InvokeInst>(I)->setCallingConv(
5059 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00005060 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00005061 break;
5062 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00005063 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
5064 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005065 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005066 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005067 return error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00005068 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00005069 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005070 break;
5071 }
Chris Lattnere53603e2007-05-02 04:27:25 +00005072 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00005073 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00005074 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00005075 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00005076 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00005077 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005078 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00005079 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005080 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005081 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005082
Jay Foad52131342011-03-30 11:28:46 +00005083 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00005084 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005085
Chris Lattnere14cb882007-05-04 19:11:41 +00005086 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00005087 Value *V;
5088 // With the new function encoding, it is possible that operands have
5089 // negative IDs (for forward references). Use a signed VBR
5090 // representation to keep the encoding small.
5091 if (UseRelativeIDs)
5092 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
5093 else
5094 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00005095 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005096 if (!V || !BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005097 return error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00005098 PN->addIncoming(V, BB);
5099 }
5100 I = PN;
5101 break;
5102 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005103
David Majnemer7fddecc2015-06-17 20:52:32 +00005104 case bitc::FUNC_CODE_INST_LANDINGPAD:
5105 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
Bill Wendlingfae14752011-08-12 20:24:12 +00005106 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
5107 unsigned Idx = 0;
David Majnemer7fddecc2015-06-17 20:52:32 +00005108 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
5109 if (Record.size() < 3)
5110 return error("Invalid record");
5111 } else {
5112 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
5113 if (Record.size() < 4)
5114 return error("Invalid record");
5115 }
Bill Wendlingfae14752011-08-12 20:24:12 +00005116 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005117 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005118 return error("Invalid record");
David Majnemer7fddecc2015-06-17 20:52:32 +00005119 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
5120 Value *PersFn = nullptr;
5121 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
5122 return error("Invalid record");
5123
5124 if (!F->hasPersonalityFn())
5125 F->setPersonalityFn(cast<Constant>(PersFn));
5126 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
5127 return error("Personality function mismatch");
5128 }
Bill Wendlingfae14752011-08-12 20:24:12 +00005129
5130 bool IsCleanup = !!Record[Idx++];
5131 unsigned NumClauses = Record[Idx++];
David Majnemer7fddecc2015-06-17 20:52:32 +00005132 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
Bill Wendlingfae14752011-08-12 20:24:12 +00005133 LP->setCleanup(IsCleanup);
5134 for (unsigned J = 0; J != NumClauses; ++J) {
5135 LandingPadInst::ClauseType CT =
5136 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
5137 Value *Val;
5138
5139 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
5140 delete LP;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005141 return error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00005142 }
5143
5144 assert((CT != LandingPadInst::Catch ||
5145 !isa<ArrayType>(Val->getType())) &&
5146 "Catch clause has a invalid type!");
5147 assert((CT != LandingPadInst::Filter ||
5148 isa<ArrayType>(Val->getType())) &&
5149 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005150 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00005151 }
5152
5153 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00005154 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00005155 break;
5156 }
5157
Chris Lattnerf1c87102011-06-17 18:09:11 +00005158 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
5159 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005160 return error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00005161 uint64_t AlignRecord = Record[3];
5162 const uint64_t InAllocaMask = uint64_t(1) << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00005163 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00005164 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
5165 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
5166 SwiftErrorMask;
JF Bastien30bf96b2015-02-22 19:32:03 +00005167 bool InAlloca = AlignRecord & InAllocaMask;
Manman Ren9bfd0d02016-04-01 21:41:15 +00005168 bool SwiftError = AlignRecord & SwiftErrorMask;
David Blaikiebdb49102015-04-28 16:51:01 +00005169 Type *Ty = getTypeByID(Record[0]);
5170 if ((AlignRecord & ExplicitTypeMask) == 0) {
5171 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
5172 if (!PTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005173 return error("Old-style alloca with a non-pointer type");
David Blaikiebdb49102015-04-28 16:51:01 +00005174 Ty = PTy->getElementType();
5175 }
5176 Type *OpTy = getTypeByID(Record[1]);
5177 Value *Size = getFnValueByID(Record[2], OpTy);
JF Bastien30bf96b2015-02-22 19:32:03 +00005178 unsigned Align;
5179 if (std::error_code EC =
David Blaikiebdb49102015-04-28 16:51:01 +00005180 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
JF Bastien30bf96b2015-02-22 19:32:03 +00005181 return EC;
5182 }
Rafael Espindola48da4f42013-11-04 16:16:24 +00005183 if (!Ty || !Size)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005184 return error("Invalid record");
David Blaikiebdb49102015-04-28 16:51:01 +00005185 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00005186 AI->setUsedWithInAlloca(InAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005187 AI->setSwiftError(SwiftError);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00005188 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00005189 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00005190 break;
5191 }
Chris Lattner9f600c52007-05-03 22:04:19 +00005192 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005193 unsigned OpNum = 0;
5194 Value *Op;
5195 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00005196 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005197 return error("Invalid record");
David Blaikie85035652015-02-25 01:07:20 +00005198
5199 Type *Ty = nullptr;
5200 if (OpNum + 3 == Record.size())
5201 Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005202 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005203 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00005204 if (!Ty)
5205 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00005206
JF Bastien30bf96b2015-02-22 19:32:03 +00005207 unsigned Align;
5208 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5209 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00005210 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
David Blaikie85035652015-02-25 01:07:20 +00005211
Devang Patelaf206b82009-09-18 19:26:43 +00005212 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00005213 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00005214 }
Eli Friedman59b66882011-08-09 23:02:53 +00005215 case bitc::FUNC_CODE_INST_LOADATOMIC: {
5216 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
5217 unsigned OpNum = 0;
5218 Value *Op;
5219 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00005220 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005221 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00005222
David Blaikie85035652015-02-25 01:07:20 +00005223 Type *Ty = nullptr;
5224 if (OpNum + 5 == Record.size())
5225 Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005226 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005227 return EC;
5228 if (!Ty)
5229 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00005230
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005231 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00005232 if (Ordering == AtomicOrdering::NotAtomic ||
5233 Ordering == AtomicOrdering::Release ||
5234 Ordering == AtomicOrdering::AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005235 return error("Invalid record");
JF Bastien800f87a2016-04-06 21:19:33 +00005236 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005237 return error("Invalid record");
5238 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00005239
JF Bastien30bf96b2015-02-22 19:32:03 +00005240 unsigned Align;
5241 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5242 return EC;
5243 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
David Blaikie85035652015-02-25 01:07:20 +00005244
Eli Friedman59b66882011-08-09 23:02:53 +00005245 InstructionList.push_back(I);
5246 break;
5247 }
David Blaikie612ddbf2015-04-22 04:14:42 +00005248 case bitc::FUNC_CODE_INST_STORE:
5249 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00005250 unsigned OpNum = 0;
5251 Value *Val, *Ptr;
5252 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie612ddbf2015-04-22 04:14:42 +00005253 (BitCode == bitc::FUNC_CODE_INST_STORE
5254 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5255 : popValue(Record, OpNum, NextValueNo,
5256 cast<PointerType>(Ptr->getType())->getElementType(),
5257 Val)) ||
5258 OpNum + 2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005259 return error("Invalid record");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005260
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005261 if (std::error_code EC =
5262 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005263 return EC;
JF Bastien30bf96b2015-02-22 19:32:03 +00005264 unsigned Align;
5265 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5266 return EC;
5267 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
Devang Patelaf206b82009-09-18 19:26:43 +00005268 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00005269 break;
5270 }
David Blaikie50a06152015-04-22 04:14:46 +00005271 case bitc::FUNC_CODE_INST_STOREATOMIC:
5272 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
Eli Friedman59b66882011-08-09 23:02:53 +00005273 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
5274 unsigned OpNum = 0;
5275 Value *Val, *Ptr;
5276 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Filipe Cabecinhas036e73c2016-06-05 18:43:33 +00005277 !isa<PointerType>(Ptr->getType()) ||
David Blaikie50a06152015-04-22 04:14:46 +00005278 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
5279 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5280 : popValue(Record, OpNum, NextValueNo,
5281 cast<PointerType>(Ptr->getType())->getElementType(),
5282 Val)) ||
5283 OpNum + 4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005284 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00005285
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005286 if (std::error_code EC =
5287 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005288 return EC;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005289 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00005290 if (Ordering == AtomicOrdering::NotAtomic ||
5291 Ordering == AtomicOrdering::Acquire ||
5292 Ordering == AtomicOrdering::AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005293 return error("Invalid record");
5294 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
JF Bastien800f87a2016-04-06 21:19:33 +00005295 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005296 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00005297
JF Bastien30bf96b2015-02-22 19:32:03 +00005298 unsigned Align;
5299 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5300 return EC;
5301 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
Eli Friedman59b66882011-08-09 23:02:53 +00005302 InstructionList.push_back(I);
5303 break;
5304 }
David Blaikie2a661cd2015-04-28 04:30:29 +00005305 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005306 case bitc::FUNC_CODE_INST_CMPXCHG: {
Tim Northovere94a5182014-03-11 10:48:52 +00005307 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
Tim Northover420a2162014-06-13 14:24:07 +00005308 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005309 unsigned OpNum = 0;
5310 Value *Ptr, *Cmp, *New;
5311 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie2a661cd2015-04-28 04:30:29 +00005312 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
5313 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
5314 : popValue(Record, OpNum, NextValueNo,
5315 cast<PointerType>(Ptr->getType())->getElementType(),
5316 Cmp)) ||
5317 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
5318 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005319 return error("Invalid record");
5320 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
JF Bastien800f87a2016-04-06 21:19:33 +00005321 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
5322 SuccessOrdering == AtomicOrdering::Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005323 return error("Invalid record");
5324 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
Tim Northovere94a5182014-03-11 10:48:52 +00005325
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005326 if (std::error_code EC =
5327 typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005328 return EC;
Tim Northovere94a5182014-03-11 10:48:52 +00005329 AtomicOrdering FailureOrdering;
5330 if (Record.size() < 7)
5331 FailureOrdering =
5332 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
5333 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005334 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
Tim Northovere94a5182014-03-11 10:48:52 +00005335
5336 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
5337 SynchScope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005338 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00005339
5340 if (Record.size() < 8) {
5341 // Before weak cmpxchgs existed, the instruction simply returned the
5342 // value loaded from memory, so bitcode files from that era will be
5343 // expecting the first component of a modern cmpxchg.
5344 CurBB->getInstList().push_back(I);
5345 I = ExtractValueInst::Create(I, 0);
5346 } else {
5347 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
5348 }
5349
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005350 InstructionList.push_back(I);
5351 break;
5352 }
5353 case bitc::FUNC_CODE_INST_ATOMICRMW: {
5354 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
5355 unsigned OpNum = 0;
5356 Value *Ptr, *Val;
5357 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Filipe Cabecinhas6328f8e2016-06-05 18:43:40 +00005358 !isa<PointerType>(Ptr->getType()) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00005359 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005360 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
5361 OpNum+4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005362 return error("Invalid record");
5363 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005364 if (Operation < AtomicRMWInst::FIRST_BINOP ||
5365 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005366 return error("Invalid record");
5367 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00005368 if (Ordering == AtomicOrdering::NotAtomic ||
5369 Ordering == AtomicOrdering::Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005370 return error("Invalid record");
5371 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005372 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
5373 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
5374 InstructionList.push_back(I);
5375 break;
5376 }
Eli Friedmanfee02c62011-07-25 23:16:38 +00005377 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
5378 if (2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005379 return error("Invalid record");
5380 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
JF Bastien800f87a2016-04-06 21:19:33 +00005381 if (Ordering == AtomicOrdering::NotAtomic ||
5382 Ordering == AtomicOrdering::Unordered ||
5383 Ordering == AtomicOrdering::Monotonic)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005384 return error("Invalid record");
5385 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005386 I = new FenceInst(Context, Ordering, SynchScope);
5387 InstructionList.push_back(I);
5388 break;
5389 }
Chris Lattnerc44070802011-06-17 18:17:37 +00005390 case bitc::FUNC_CODE_INST_CALL: {
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005391 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00005392 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005393 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005394
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005395 unsigned OpNum = 0;
5396 AttributeSet PAL = getAttributes(Record[OpNum++]);
5397 unsigned CCInfo = Record[OpNum++];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005398
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005399 FastMathFlags FMF;
5400 if ((CCInfo >> bitc::CALL_FMF) & 1) {
5401 FMF = getDecodedFastMathFlags(Record[OpNum++]);
5402 if (!FMF.any())
5403 return error("Fast math flags indicator set for call with no FMF");
5404 }
5405
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005406 FunctionType *FTy = nullptr;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005407 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005408 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005409 return error("Explicit call type is not a function type");
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005410
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005411 Value *Callee;
5412 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005413 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005414
Chris Lattner229907c2011-07-18 04:54:35 +00005415 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005416 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005417 return error("Callee is not a pointer type");
David Blaikie348de692015-04-23 21:36:23 +00005418 if (!FTy) {
5419 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5420 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005421 return error("Callee is not of pointer to function type");
David Blaikie348de692015-04-23 21:36:23 +00005422 } else if (OpTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005423 return error("Explicit call type does not match pointee type of "
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005424 "callee operand");
5425 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005426 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005427
Chris Lattner9f600c52007-05-03 22:04:19 +00005428 SmallVector<Value*, 16> Args;
5429 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005430 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005431 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00005432 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00005433 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00005434 Args.push_back(getValue(Record, OpNum, NextValueNo,
5435 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00005436 if (!Args.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005437 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005438 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005439
Chris Lattner9f600c52007-05-03 22:04:19 +00005440 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00005441 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005442 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005443 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005444 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005445 while (OpNum != Record.size()) {
5446 Value *Op;
5447 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005448 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005449 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00005450 }
5451 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005452
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005453 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5454 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00005455 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00005456 cast<CallInst>(I)->setCallingConv(
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005457 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
Reid Kleckner5772b772014-04-24 20:14:34 +00005458 CallInst::TailCallKind TCK = CallInst::TCK_None;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005459 if (CCInfo & 1 << bitc::CALL_TAIL)
Reid Kleckner5772b772014-04-24 20:14:34 +00005460 TCK = CallInst::TCK_Tail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005461 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
Reid Kleckner5772b772014-04-24 20:14:34 +00005462 TCK = CallInst::TCK_MustTail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005463 if (CCInfo & (1 << bitc::CALL_NOTAIL))
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005464 TCK = CallInst::TCK_NoTail;
Reid Kleckner5772b772014-04-24 20:14:34 +00005465 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00005466 cast<CallInst>(I)->setAttributes(PAL);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005467 if (FMF.any()) {
5468 if (!isa<FPMathOperator>(I))
5469 return error("Fast-math-flags specified for call without "
5470 "floating-point scalar or vector return type");
5471 I->setFastMathFlags(FMF);
5472 }
Chris Lattner9f600c52007-05-03 22:04:19 +00005473 break;
5474 }
5475 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5476 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005477 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00005478 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00005479 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00005480 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00005481 if (!OpTy || !Op || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005482 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005483 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00005484 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00005485 break;
5486 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005487
5488 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5489 // A call or an invoke can be optionally prefixed with some variable
5490 // number of operand bundle blocks. These blocks are read into
5491 // OperandBundles and consumed at the next call or invoke instruction.
5492
5493 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5494 return error("Invalid record");
5495
Sanjoy Dasf79d3442015-11-18 08:30:07 +00005496 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005497
5498 unsigned OpNum = 1;
5499 while (OpNum != Record.size()) {
5500 Value *Op;
5501 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5502 return error("Invalid record");
5503 Inputs.push_back(Op);
5504 }
5505
Sanjoy Dasf79d3442015-11-18 08:30:07 +00005506 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005507 continue;
5508 }
Chris Lattner83930552007-05-01 07:01:57 +00005509 }
5510
5511 // Add instruction to end of current BB. If there is no current BB, reject
5512 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00005513 if (!CurBB) {
Chris Lattner83930552007-05-01 07:01:57 +00005514 delete I;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005515 return error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00005516 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005517 if (!OperandBundles.empty()) {
5518 delete I;
5519 return error("Operand bundles found with no consumer");
5520 }
Chris Lattner83930552007-05-01 07:01:57 +00005521 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005522
Chris Lattner83930552007-05-01 07:01:57 +00005523 // If this was a terminator instruction, move to the next block.
5524 if (isa<TerminatorInst>(I)) {
5525 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00005526 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00005527 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005528
Chris Lattner83930552007-05-01 07:01:57 +00005529 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00005530 if (I && !I->getType()->isVoidTy())
David Majnemer8a1c45d2015-12-12 05:38:55 +00005531 ValueList.assignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00005532 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005533
Chris Lattner27d38752013-01-20 02:13:19 +00005534OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00005535
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005536 if (!OperandBundles.empty())
5537 return error("Operand bundles found with no consumer");
5538
Chris Lattner83930552007-05-01 07:01:57 +00005539 // Check the function list for unresolved values.
5540 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005541 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00005542 // We found at least one unresolved value. Nuke them all to avoid leaks.
5543 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00005544 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00005545 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00005546 delete A;
5547 }
5548 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005549 return error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00005550 }
Chris Lattner83930552007-05-01 07:01:57 +00005551 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005552
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00005553 // Unexpected unresolved metadata about to be dropped.
5554 if (MetadataList.hasFwdRefs())
5555 return error("Invalid function metadata: outgoing forward refs");
Dan Gohman9b9ff462010-08-25 20:23:38 +00005556
Chris Lattner85b7b402007-05-01 05:52:21 +00005557 // Trim the value list down to the size it was before we parsed this function.
5558 ValueList.shrinkTo(ModuleValueListSize);
Teresa Johnson61b406e2015-12-29 23:00:22 +00005559 MetadataList.shrinkTo(ModuleMetadataListSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00005560 std::vector<BasicBlock*>().swap(FunctionBBs);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005561 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00005562}
5563
Rafael Espindola7d712032013-11-05 17:16:08 +00005564/// Find the function body in the bitcode stream
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005565std::error_code BitcodeReader::findFunctionInStream(
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005566 Function *F,
5567 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005568 while (DeferredFunctionInfoIterator->second == 0) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00005569 // This is the fallback handling for the old format bitcode that
Teresa Johnson1493ad92015-10-10 14:18:36 +00005570 // didn't contain the function index in the VST, or when we have
5571 // an anonymous function which would not have a VST entry.
5572 // Assert that we have one of those two cases.
5573 assert(VSTOffset == 0 || !F->hasName());
5574 // Parse the next body in the stream and set its position in the
5575 // DeferredFunctionInfo map.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005576 if (std::error_code EC = rememberAndSkipFunctionBodies())
5577 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005578 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005579 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005580}
5581
Chris Lattner9eeada92007-05-18 04:02:46 +00005582//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005583// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00005584//===----------------------------------------------------------------------===//
5585
Rafael Espindolac3f9b5a2014-06-23 21:53:12 +00005586void BitcodeReader::releaseBuffer() { Buffer.release(); }
Chris Lattner9eeada92007-05-18 04:02:46 +00005587
Rafael Espindola5a52e6d2014-10-24 22:50:48 +00005588std::error_code BitcodeReader::materialize(GlobalValue *GV) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005589 Function *F = dyn_cast<Function>(GV);
5590 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005591 if (!F || !F->isMaterializable())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005592 return std::error_code();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005593
5594 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00005595 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005596 // If its position is recorded as 0, its body is somewhere in the stream
5597 // but we haven't seen it yet.
Rafael Espindola1c863ca2015-06-22 18:06:15 +00005598 if (DFII->second == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005599 if (std::error_code EC = findFunctionInStream(F, DFII))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005600 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005601
Duncan P. N. Exon Smith03a04a52016-04-24 15:04:28 +00005602 // Materialize metadata before parsing any function bodies.
5603 if (std::error_code EC = materializeMetadata())
5604 return EC;
5605
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005606 // Move the bit stream to the saved position of the deferred function body.
5607 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005608
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005609 if (std::error_code EC = parseFunctionBody(F))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005610 return EC;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00005611 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00005612
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00005613 if (StripDebugInfo)
5614 stripDebugInfo(*F);
5615
Chandler Carruth7132e002007-08-04 01:51:18 +00005616 // Upgrade any old intrinsic calls in the function.
Rafael Espindola86e33402015-07-02 15:55:09 +00005617 for (auto &I : UpgradedIntrinsics) {
Rafael Espindola257a3532016-01-15 19:00:20 +00005618 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5619 UI != UE;) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005620 User *U = *UI;
5621 ++UI;
5622 if (CallInst *CI = dyn_cast<CallInst>(U))
5623 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00005624 }
5625 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005626
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00005627 // Update calls to the remangled intrinsics
5628 for (auto &I : RemangledIntrinsics)
5629 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5630 UI != UE;)
5631 // Don't expect any other users than call sites
5632 CallSite(*UI++).setCalledFunction(I.second);
5633
Peter Collingbourned4bff302015-11-05 22:03:56 +00005634 // Finish fn->subprogram upgrade for materialized functions.
5635 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5636 F->setSubprogram(SP);
5637
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005638 // Bring in any functions that this function forward-referenced via
5639 // blockaddresses.
5640 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00005641}
5642
Rafael Espindola79753a02015-12-18 21:18:57 +00005643std::error_code BitcodeReader::materializeModule() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00005644 if (std::error_code EC = materializeMetadata())
5645 return EC;
5646
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005647 // Promise to materialize all forward references.
5648 WillMaterializeAllForwardRefs = true;
5649
Chris Lattner06310bf2009-06-16 05:15:21 +00005650 // Iterate over the module, deserializing any functions that are still on
5651 // disk.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00005652 for (Function &F : *TheModule) {
5653 if (std::error_code EC = materialize(&F))
Rafael Espindola246c4fb2014-11-01 16:46:18 +00005654 return EC;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005655 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00005656 // At this point, if there are any function bodies, parse the rest of
5657 // the bits in the module past the last function block we have recorded
5658 // through either lazy scanning or the VST.
5659 if (LastFunctionBlockBit || NextUnreadBit)
5660 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5661 : NextUnreadBit);
Derek Schuff92ef9752012-02-29 00:07:09 +00005662
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005663 // Check that all block address forward references got resolved (as we
5664 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00005665 if (!BasicBlockFwdRefs.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005666 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005667
Chris Bieneman671d0dd2016-03-16 23:17:54 +00005668 // Upgrading intrinsic calls before TBAA can cause TBAA metadata to be lost,
5669 // to prevent this instructions with TBAA tags should be upgraded first.
5670 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5671 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5672
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005673 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5674 // delete the old functions to clean up. We can't do this unless the entire
5675 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00005676 // with calls to the old function.
Rafael Espindola86e33402015-07-02 15:55:09 +00005677 for (auto &I : UpgradedIntrinsics) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005678 for (auto *U : I.first->users()) {
5679 if (CallInst *CI = dyn_cast<CallInst>(U))
5680 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00005681 }
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005682 if (!I.first->use_empty())
5683 I.first->replaceAllUsesWith(I.second);
5684 I.first->eraseFromParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00005685 }
Rafael Espindola4e721212015-07-02 16:22:40 +00005686 UpgradedIntrinsics.clear();
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00005687 // Do the same for remangled intrinsics
5688 for (auto &I : RemangledIntrinsics) {
5689 I.first->replaceAllUsesWith(I.second);
5690 I.first->eraseFromParent();
5691 }
5692 RemangledIntrinsics.clear();
Devang Patel80ae3492009-08-28 23:24:31 +00005693
Rafael Espindola79753a02015-12-18 21:18:57 +00005694 UpgradeDebugInfo(*TheModule);
Manman Renb5d7ff42016-05-25 23:14:48 +00005695
5696 UpgradeModuleFlags(*TheModule);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005697 return std::error_code();
Chris Lattner9eeada92007-05-18 04:02:46 +00005698}
5699
Rafael Espindola2fa1e432014-12-03 07:18:23 +00005700std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5701 return IdentifiedStructTypes;
5702}
5703
Rafael Espindola1aabf982015-06-16 23:29:49 +00005704std::error_code
5705BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
Rafael Espindola4223a1f2015-06-15 20:08:17 +00005706 if (Streamer)
Rafael Espindola1aabf982015-06-16 23:29:49 +00005707 return initLazyStream(std::move(Streamer));
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005708 return initStreamFromBuffer();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005709}
5710
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005711std::error_code BitcodeReader::initStreamFromBuffer() {
Roman Divacky4717a8d2012-09-06 15:42:13 +00005712 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005713 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5714
Rafael Espindola27435252014-07-29 21:01:24 +00005715 if (Buffer->getBufferSize() & 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005716 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005717
5718 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5719 // The magic number is 0x0B17C0DE stored in little endian.
5720 if (isBitcodeWrapper(BufPtr, BufEnd))
5721 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005722 return error("Invalid bitcode wrapper header");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005723
5724 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00005725 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005726
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005727 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005728}
5729
Rafael Espindola1aabf982015-06-16 23:29:49 +00005730std::error_code
5731BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005732 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5733 // see it.
Rafael Espindola1aabf982015-06-16 23:29:49 +00005734 auto OwnedBytes =
5735 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
Rafael Espindola7d727b52014-12-18 05:08:43 +00005736 StreamingMemoryObject &Bytes = *OwnedBytes;
Yaron Keren06d69302014-12-18 10:03:35 +00005737 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00005738 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005739
5740 unsigned char buf[16];
Rafael Espindola7d727b52014-12-18 05:08:43 +00005741 if (Bytes.readBytes(buf, 16, 0) != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005742 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005743
5744 if (!isBitcode(buf, buf + 16))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005745 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005746
5747 if (isBitcodeWrapper(buf, buf + 4)) {
5748 const unsigned char *bitcodeStart = buf;
5749 const unsigned char *bitcodeEnd = buf + 16;
5750 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
Rafael Espindola7d727b52014-12-18 05:08:43 +00005751 Bytes.dropLeadingBytes(bitcodeStart - buf);
5752 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005753 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005754 return std::error_code();
Rafael Espindola48da4f42013-11-04 16:16:24 +00005755}
5756
Teresa Johnson26ab5772016-03-15 00:04:37 +00005757std::error_code ModuleSummaryIndexBitcodeReader::error(const Twine &Message) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005758 return ::error(DiagnosticHandler,
5759 make_error_code(BitcodeError::CorruptedBitcode), Message);
5760}
5761
Teresa Johnson26ab5772016-03-15 00:04:37 +00005762ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
Mehdi Amini354f5202015-11-19 05:52:29 +00005763 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson6fb3f192016-04-22 01:52:00 +00005764 bool CheckGlobalValSummaryPresenceOnly)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00005765 : DiagnosticHandler(std::move(DiagnosticHandler)), Buffer(Buffer),
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005766 CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
Teresa Johnson403a7872015-10-04 14:33:43 +00005767
Teresa Johnson26ab5772016-03-15 00:04:37 +00005768void ModuleSummaryIndexBitcodeReader::freeState() { Buffer = nullptr; }
Teresa Johnson403a7872015-10-04 14:33:43 +00005769
Teresa Johnson26ab5772016-03-15 00:04:37 +00005770void ModuleSummaryIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
Teresa Johnson403a7872015-10-04 14:33:43 +00005771
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005772std::pair<GlobalValue::GUID, GlobalValue::GUID>
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005773ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005774 auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId);
5775 assert(VGI != ValueIdToCallGraphGUIDMap.end());
5776 return VGI->second;
5777}
5778
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005779// Specialized value symbol table parser used when reading module index
Teresa Johnson28e457b2016-04-24 14:57:11 +00005780// blocks where we don't actually create global values. The parsed information
5781// is saved in the bitcode reader for use when later parsing summaries.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005782std::error_code ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005783 uint64_t Offset,
5784 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
5785 assert(Offset > 0 && "Expected non-zero VST offset");
5786 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
5787
Teresa Johnson403a7872015-10-04 14:33:43 +00005788 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5789 return error("Invalid record");
5790
5791 SmallVector<uint64_t, 64> Record;
5792
5793 // Read all the records for this value table.
5794 SmallString<128> ValueName;
5795 while (1) {
5796 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5797
5798 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005799 case BitstreamEntry::SubBlock: // Handled for us already.
5800 case BitstreamEntry::Error:
5801 return error("Malformed block");
5802 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005803 // Done parsing VST, jump back to wherever we came from.
5804 Stream.JumpToBit(CurrentBit);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005805 return std::error_code();
5806 case BitstreamEntry::Record:
5807 // The interesting case.
5808 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005809 }
5810
5811 // Read a record.
5812 Record.clear();
5813 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005814 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5815 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005816 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
5817 if (convertToString(Record, 1, ValueName))
5818 return error("Invalid record");
5819 unsigned ValueID = Record[0];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005820 assert(!SourceFileName.empty());
5821 auto VLI = ValueIdToLinkageMap.find(ValueID);
5822 assert(VLI != ValueIdToLinkageMap.end() &&
5823 "No linkage found for VST entry?");
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005824 auto Linkage = VLI->second;
5825 std::string GlobalId =
5826 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
Teresa Johnson916495d2016-04-04 18:52:58 +00005827 auto ValueGUID = GlobalValue::getGUID(GlobalId);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005828 auto OriginalNameID = ValueGUID;
5829 if (GlobalValue::isLocalLinkage(Linkage))
5830 OriginalNameID = GlobalValue::getGUID(ValueName);
Teresa Johnson916495d2016-04-04 18:52:58 +00005831 if (PrintSummaryGUIDs)
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005832 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
5833 << ValueName << "\n";
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005834 ValueIdToCallGraphGUIDMap[ValueID] =
5835 std::make_pair(ValueGUID, OriginalNameID);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005836 ValueName.clear();
5837 break;
5838 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005839 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00005840 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005841 if (convertToString(Record, 2, ValueName))
5842 return error("Invalid record");
5843 unsigned ValueID = Record[0];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005844 assert(!SourceFileName.empty());
5845 auto VLI = ValueIdToLinkageMap.find(ValueID);
5846 assert(VLI != ValueIdToLinkageMap.end() &&
5847 "No linkage found for VST entry?");
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005848 auto Linkage = VLI->second;
Teresa Johnsonb43027d2016-03-15 02:13:19 +00005849 std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier(
5850 ValueName, VLI->second, SourceFileName);
Teresa Johnson916495d2016-04-04 18:52:58 +00005851 auto FunctionGUID = GlobalValue::getGUID(FunctionGlobalId);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005852 auto OriginalNameID = FunctionGUID;
5853 if (GlobalValue::isLocalLinkage(Linkage))
5854 OriginalNameID = GlobalValue::getGUID(ValueName);
Teresa Johnson916495d2016-04-04 18:52:58 +00005855 if (PrintSummaryGUIDs)
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005856 dbgs() << "GUID " << FunctionGUID << "(" << OriginalNameID << ") is "
5857 << ValueName << "\n";
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005858 ValueIdToCallGraphGUIDMap[ValueID] =
5859 std::make_pair(FunctionGUID, OriginalNameID);
Teresa Johnson403a7872015-10-04 14:33:43 +00005860
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005861 ValueName.clear();
5862 break;
5863 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005864 case bitc::VST_CODE_COMBINED_ENTRY: {
5865 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
5866 unsigned ValueID = Record[0];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005867 GlobalValue::GUID RefGUID = Record[1];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005868 // The "original name", which is the second value of the pair will be
5869 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
5870 ValueIdToCallGraphGUIDMap[ValueID] = std::make_pair(RefGUID, RefGUID);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005871 break;
5872 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005873 }
5874 }
5875}
5876
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005877// Parse just the blocks needed for building the index out of the module.
5878// At the end of this routine the module Index is populated with a map
Teresa Johnson28e457b2016-04-24 14:57:11 +00005879// from global value id to GlobalValueSummary objects.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005880std::error_code ModuleSummaryIndexBitcodeReader::parseModule() {
Teresa Johnson403a7872015-10-04 14:33:43 +00005881 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5882 return error("Invalid record");
5883
Teresa Johnsone1164de2016-02-10 21:55:02 +00005884 SmallVector<uint64_t, 64> Record;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005885 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
5886 unsigned ValueId = 0;
Teresa Johnsone1164de2016-02-10 21:55:02 +00005887
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005888 // Read the index for this module.
Teresa Johnson403a7872015-10-04 14:33:43 +00005889 while (1) {
5890 BitstreamEntry Entry = Stream.advance();
5891
5892 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005893 case BitstreamEntry::Error:
5894 return error("Malformed block");
5895 case BitstreamEntry::EndBlock:
5896 return std::error_code();
5897
5898 case BitstreamEntry::SubBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005899 if (CheckGlobalValSummaryPresenceOnly) {
5900 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
5901 SeenGlobalValSummary = true;
Teresa Johnson6290dbc2015-11-21 21:55:48 +00005902 // No need to parse the rest since we found the summary.
5903 return std::error_code();
5904 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005905 if (Stream.SkipBlock())
5906 return error("Invalid record");
Teresa Johnson6290dbc2015-11-21 21:55:48 +00005907 continue;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005908 }
5909 switch (Entry.ID) {
5910 default: // Skip unknown content.
5911 if (Stream.SkipBlock())
5912 return error("Invalid record");
5913 break;
5914 case bitc::BLOCKINFO_BLOCK_ID:
5915 // Need to parse these to get abbrev ids (e.g. for VST)
5916 if (Stream.ReadBlockInfoBlock())
5917 return error("Malformed block");
5918 break;
5919 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005920 // Should have been parsed earlier via VSTOffset, unless there
5921 // is no summary section.
5922 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
5923 !SeenGlobalValSummary) &&
5924 "Expected early VST parse via VSTOffset record");
5925 if (Stream.SkipBlock())
5926 return error("Invalid record");
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005927 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005928 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
5929 assert(VSTOffset > 0 && "Expected non-zero VST offset");
5930 assert(!SeenValueSymbolTable &&
5931 "Already read VST when parsing summary block?");
5932 if (std::error_code EC =
5933 parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
5934 return EC;
5935 SeenValueSymbolTable = true;
5936 SeenGlobalValSummary = true;
Teresa Johnson6fb3f192016-04-22 01:52:00 +00005937 if (std::error_code EC = parseEntireSummary())
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005938 return EC;
5939 break;
5940 case bitc::MODULE_STRTAB_BLOCK_ID:
5941 if (std::error_code EC = parseModuleStringTable())
5942 return EC;
5943 break;
5944 }
5945 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00005946
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005947 case BitstreamEntry::Record: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00005948 Record.clear();
5949 auto BitCode = Stream.readRecord(Entry.ID, Record);
5950 switch (BitCode) {
5951 default:
5952 break; // Default behavior, ignore unknown content.
5953 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005954 case bitc::MODULE_CODE_SOURCE_FILENAME: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00005955 SmallString<128> ValueName;
5956 if (convertToString(Record, 0, ValueName))
5957 return error("Invalid record");
5958 SourceFileName = ValueName.c_str();
5959 break;
5960 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005961 /// MODULE_CODE_HASH: [5*i32]
5962 case bitc::MODULE_CODE_HASH: {
5963 if (Record.size() != 5)
5964 return error("Invalid hash length " + Twine(Record.size()).str());
5965 if (!TheIndex)
5966 break;
5967 if (TheIndex->modulePaths().empty())
5968 // Does not have any summary emitted.
5969 break;
5970 if (TheIndex->modulePaths().size() != 1)
5971 return error("Don't expect multiple modules defined?");
5972 auto &Hash = TheIndex->modulePaths().begin()->second.second;
5973 int Pos = 0;
5974 for (auto &Val : Record) {
5975 assert(!(Val >> 32) && "Unexpected high bits set");
5976 Hash[Pos++] = Val;
5977 }
5978 break;
5979 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005980 /// MODULE_CODE_VSTOFFSET: [offset]
5981 case bitc::MODULE_CODE_VSTOFFSET:
5982 if (Record.size() < 1)
5983 return error("Invalid record");
5984 VSTOffset = Record[0];
5985 break;
5986 // GLOBALVAR: [pointer type, isconst, initid,
5987 // linkage, alignment, section, visibility, threadlocal,
5988 // unnamed_addr, externally_initialized, dllstorageclass,
5989 // comdat]
5990 case bitc::MODULE_CODE_GLOBALVAR: {
5991 if (Record.size() < 6)
5992 return error("Invalid record");
5993 uint64_t RawLinkage = Record[3];
5994 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5995 ValueIdToLinkageMap[ValueId++] = Linkage;
5996 break;
5997 }
5998 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
5999 // alignment, section, visibility, gc, unnamed_addr,
6000 // prologuedata, dllstorageclass, comdat, prefixdata]
6001 case bitc::MODULE_CODE_FUNCTION: {
6002 if (Record.size() < 8)
6003 return error("Invalid record");
6004 uint64_t RawLinkage = Record[3];
6005 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6006 ValueIdToLinkageMap[ValueId++] = Linkage;
6007 break;
6008 }
6009 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
6010 // dllstorageclass]
6011 case bitc::MODULE_CODE_ALIAS: {
6012 if (Record.size() < 6)
6013 return error("Invalid record");
6014 uint64_t RawLinkage = Record[3];
6015 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6016 ValueIdToLinkageMap[ValueId++] = Linkage;
6017 break;
6018 }
6019 }
Teresa Johnsone1164de2016-02-10 21:55:02 +00006020 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006021 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00006022 }
6023 }
6024}
6025
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006026// Eagerly parse the entire summary block. This populates the GlobalValueSummary
6027// objects in the index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006028std::error_code ModuleSummaryIndexBitcodeReader::parseEntireSummary() {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006029 if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID))
Teresa Johnson403a7872015-10-04 14:33:43 +00006030 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00006031 SmallVector<uint64_t, 64> Record;
Mehdi Amini8fe69362016-04-24 03:18:11 +00006032
6033 // Parse version
6034 {
6035 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6036 if (Entry.Kind != BitstreamEntry::Record)
6037 return error("Invalid Summary Block: record for version expected");
6038 if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
6039 return error("Invalid Summary Block: version expected");
6040 }
6041 const uint64_t Version = Record[0];
6042 if (Version != 1)
6043 return error("Invalid summary version " + Twine(Version) + ", 1 expected");
6044 Record.clear();
6045
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006046 // Keep around the last seen summary to be used when we see an optional
6047 // "OriginalName" attachement.
6048 GlobalValueSummary *LastSeenSummary = nullptr;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006049 bool Combined = false;
Teresa Johnson403a7872015-10-04 14:33:43 +00006050 while (1) {
6051 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6052
6053 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006054 case BitstreamEntry::SubBlock: // Handled for us already.
6055 case BitstreamEntry::Error:
6056 return error("Malformed block");
6057 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006058 // For a per-module index, remove any entries that still have empty
6059 // summaries. The VST parsing creates entries eagerly for all symbols,
6060 // but not all have associated summaries (e.g. it doesn't know how to
6061 // distinguish between VST_CODE_ENTRY for function declarations vs global
6062 // variables with initializers that end up with a summary). Remove those
6063 // entries now so that we don't need to rely on the combined index merger
6064 // to clean them up (especially since that may not run for the first
6065 // module's index if we merge into that).
6066 if (!Combined)
6067 TheIndex->removeEmptySummaryEntries();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006068 return std::error_code();
6069 case BitstreamEntry::Record:
6070 // The interesting case.
6071 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00006072 }
6073
6074 // Read a record. The record format depends on whether this
6075 // is a per-module index or a combined index file. In the per-module
6076 // case the records contain the associated value's ID for correlation
6077 // with VST entries. In the combined index the correlation is done
6078 // via the bitcode offset of the summary records (which were saved
6079 // in the combined index VST entries). The records also contain
6080 // information used for ThinLTO renaming and importing.
6081 Record.clear();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006082 auto BitCode = Stream.readRecord(Entry.ID, Record);
6083 switch (BitCode) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006084 default: // Default behavior: ignore.
6085 break;
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006086 // FS_PERMODULE: [valueid, flags, instcount, numrefs, numrefs x valueid,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006087 // n x (valueid, callsitecount)]
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006088 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, numrefs,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006089 // numrefs x valueid,
6090 // n x (valueid, callsitecount, profilecount)]
6091 case bitc::FS_PERMODULE:
6092 case bitc::FS_PERMODULE_PROFILE: {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006093 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006094 uint64_t RawFlags = Record[1];
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006095 unsigned InstCount = Record[2];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006096 unsigned NumRefs = Record[3];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006097 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6098 std::unique_ptr<FunctionSummary> FS =
6099 llvm::make_unique<FunctionSummary>(Flags, InstCount);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006100 // The module path string ref set in the summary must be owned by the
6101 // index's module string table. Since we don't have a module path
6102 // string table section in the per-module index, we create a single
6103 // module path string table entry with an empty (0) ID to take
6104 // ownership.
6105 FS->setModulePath(
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006106 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006107 static int RefListStartIndex = 4;
6108 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6109 assert(Record.size() >= RefListStartIndex + NumRefs &&
6110 "Record size inconsistent with number of references");
6111 for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) {
6112 unsigned RefValueId = Record[I];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006113 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006114 FS->addRefEdge(RefGUID);
6115 }
6116 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
6117 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
6118 ++I) {
6119 unsigned CalleeValueId = Record[I];
6120 unsigned CallsiteCount = Record[++I];
6121 uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006122 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006123 FS->addCallGraphEdge(CalleeGUID,
6124 CalleeInfo(CallsiteCount, ProfileCount));
6125 }
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006126 auto GUID = getGUIDFromValueId(ValueID);
6127 FS->setOriginalName(GUID.second);
Teresa Johnson28e457b2016-04-24 14:57:11 +00006128 TheIndex->addGlobalValueSummary(GUID.first, std::move(FS));
Teresa Johnsonbbe05452016-02-24 17:57:28 +00006129 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006130 }
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006131 // FS_ALIAS: [valueid, flags, valueid]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006132 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
6133 // they expect all aliasee summaries to be available.
6134 case bitc::FS_ALIAS: {
6135 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006136 uint64_t RawFlags = Record[1];
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006137 unsigned AliaseeID = Record[2];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006138 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6139 std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006140 // The module path string ref set in the summary must be owned by the
6141 // index's module string table. Since we don't have a module path
6142 // string table section in the per-module index, we create a single
6143 // module path string table entry with an empty (0) ID to take
6144 // ownership.
6145 AS->setModulePath(
6146 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
6147
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006148 GlobalValue::GUID AliaseeGUID = getGUIDFromValueId(AliaseeID).first;
Teresa Johnson28e457b2016-04-24 14:57:11 +00006149 auto *AliaseeSummary = TheIndex->getGlobalValueSummary(AliaseeGUID);
6150 if (!AliaseeSummary)
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006151 return error("Alias expects aliasee summary to be parsed");
Teresa Johnson28e457b2016-04-24 14:57:11 +00006152 AS->setAliasee(AliaseeSummary);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006153
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006154 auto GUID = getGUIDFromValueId(ValueID);
6155 AS->setOriginalName(GUID.second);
Teresa Johnson28e457b2016-04-24 14:57:11 +00006156 TheIndex->addGlobalValueSummary(GUID.first, std::move(AS));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006157 break;
6158 }
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006159 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006160 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
6161 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006162 uint64_t RawFlags = Record[1];
6163 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006164 std::unique_ptr<GlobalVarSummary> FS =
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006165 llvm::make_unique<GlobalVarSummary>(Flags);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006166 FS->setModulePath(
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006167 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006168 for (unsigned I = 2, E = Record.size(); I != E; ++I) {
6169 unsigned RefValueId = Record[I];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006170 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006171 FS->addRefEdge(RefGUID);
6172 }
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006173 auto GUID = getGUIDFromValueId(ValueID);
6174 FS->setOriginalName(GUID.second);
Teresa Johnson28e457b2016-04-24 14:57:11 +00006175 TheIndex->addGlobalValueSummary(GUID.first, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006176 break;
6177 }
Teresa Johnson02e98332016-04-27 13:28:35 +00006178 // FS_COMBINED: [valueid, modid, flags, instcount, numrefs,
6179 // numrefs x valueid, n x (valueid, callsitecount)]
6180 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, numrefs,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006181 // numrefs x valueid,
6182 // n x (valueid, callsitecount, profilecount)]
6183 case bitc::FS_COMBINED:
6184 case bitc::FS_COMBINED_PROFILE: {
Teresa Johnson02e98332016-04-27 13:28:35 +00006185 unsigned ValueID = Record[0];
6186 uint64_t ModuleId = Record[1];
6187 uint64_t RawFlags = Record[2];
6188 unsigned InstCount = Record[3];
6189 unsigned NumRefs = Record[4];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006190 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6191 std::unique_ptr<FunctionSummary> FS =
6192 llvm::make_unique<FunctionSummary>(Flags, InstCount);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006193 LastSeenSummary = FS.get();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006194 FS->setModulePath(ModuleIdMap[ModuleId]);
Teresa Johnson02e98332016-04-27 13:28:35 +00006195 static int RefListStartIndex = 5;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006196 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6197 assert(Record.size() >= RefListStartIndex + NumRefs &&
6198 "Record size inconsistent with number of references");
Teresa Johnson02e98332016-04-27 13:28:35 +00006199 for (unsigned I = RefListStartIndex, E = CallGraphEdgeStartIndex; I != E;
6200 ++I) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006201 unsigned RefValueId = Record[I];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006202 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006203 FS->addRefEdge(RefGUID);
6204 }
6205 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
6206 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
6207 ++I) {
6208 unsigned CalleeValueId = Record[I];
6209 unsigned CallsiteCount = Record[++I];
6210 uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006211 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006212 FS->addCallGraphEdge(CalleeGUID,
6213 CalleeInfo(CallsiteCount, ProfileCount));
6214 }
Teresa Johnson02e98332016-04-27 13:28:35 +00006215 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
Teresa Johnson28e457b2016-04-24 14:57:11 +00006216 TheIndex->addGlobalValueSummary(GUID, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006217 Combined = true;
6218 break;
6219 }
Teresa Johnson02e98332016-04-27 13:28:35 +00006220 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006221 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
6222 // they expect all aliasee summaries to be available.
6223 case bitc::FS_COMBINED_ALIAS: {
Teresa Johnson02e98332016-04-27 13:28:35 +00006224 unsigned ValueID = Record[0];
6225 uint64_t ModuleId = Record[1];
6226 uint64_t RawFlags = Record[2];
6227 unsigned AliaseeValueId = Record[3];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006228 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6229 std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006230 LastSeenSummary = AS.get();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006231 AS->setModulePath(ModuleIdMap[ModuleId]);
6232
Teresa Johnson02e98332016-04-27 13:28:35 +00006233 auto AliaseeGUID = getGUIDFromValueId(AliaseeValueId).first;
6234 auto AliaseeInModule =
6235 TheIndex->findSummaryInModule(AliaseeGUID, AS->modulePath());
6236 if (!AliaseeInModule)
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006237 return error("Alias expects aliasee summary to be parsed");
Teresa Johnson02e98332016-04-27 13:28:35 +00006238 AS->setAliasee(AliaseeInModule);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006239
Teresa Johnson02e98332016-04-27 13:28:35 +00006240 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
Teresa Johnson28e457b2016-04-24 14:57:11 +00006241 TheIndex->addGlobalValueSummary(GUID, std::move(AS));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006242 Combined = true;
6243 break;
6244 }
Teresa Johnson02e98332016-04-27 13:28:35 +00006245 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006246 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
Teresa Johnson02e98332016-04-27 13:28:35 +00006247 unsigned ValueID = Record[0];
6248 uint64_t ModuleId = Record[1];
6249 uint64_t RawFlags = Record[2];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006250 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006251 std::unique_ptr<GlobalVarSummary> FS =
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006252 llvm::make_unique<GlobalVarSummary>(Flags);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006253 LastSeenSummary = FS.get();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006254 FS->setModulePath(ModuleIdMap[ModuleId]);
Teresa Johnson02e98332016-04-27 13:28:35 +00006255 for (unsigned I = 3, E = Record.size(); I != E; ++I) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006256 unsigned RefValueId = Record[I];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006257 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006258 FS->addRefEdge(RefGUID);
6259 }
Teresa Johnson02e98332016-04-27 13:28:35 +00006260 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
Teresa Johnson28e457b2016-04-24 14:57:11 +00006261 TheIndex->addGlobalValueSummary(GUID, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006262 Combined = true;
Teresa Johnsonbbe05452016-02-24 17:57:28 +00006263 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006264 }
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006265 // FS_COMBINED_ORIGINAL_NAME: [original_name]
6266 case bitc::FS_COMBINED_ORIGINAL_NAME: {
6267 uint64_t OriginalName = Record[0];
6268 if (!LastSeenSummary)
6269 return error("Name attachment that does not follow a combined record");
6270 LastSeenSummary->setOriginalName(OriginalName);
6271 // Reset the LastSeenSummary
6272 LastSeenSummary = nullptr;
6273 }
Teresa Johnson403a7872015-10-04 14:33:43 +00006274 }
6275 }
6276 llvm_unreachable("Exit infinite loop");
6277}
6278
6279// Parse the module string table block into the Index.
6280// This populates the ModulePathStringTable map in the index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006281std::error_code ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
Teresa Johnson403a7872015-10-04 14:33:43 +00006282 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
6283 return error("Invalid record");
6284
6285 SmallVector<uint64_t, 64> Record;
6286
6287 SmallString<128> ModulePath;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006288 ModulePathStringTableTy::iterator LastSeenModulePath;
Teresa Johnson403a7872015-10-04 14:33:43 +00006289 while (1) {
6290 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6291
6292 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006293 case BitstreamEntry::SubBlock: // Handled for us already.
6294 case BitstreamEntry::Error:
6295 return error("Malformed block");
6296 case BitstreamEntry::EndBlock:
6297 return std::error_code();
6298 case BitstreamEntry::Record:
6299 // The interesting case.
6300 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00006301 }
6302
6303 Record.clear();
6304 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006305 default: // Default behavior: ignore.
6306 break;
6307 case bitc::MST_CODE_ENTRY: {
6308 // MST_ENTRY: [modid, namechar x N]
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006309 uint64_t ModuleId = Record[0];
6310
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006311 if (convertToString(Record, 1, ModulePath))
6312 return error("Invalid record");
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006313
6314 LastSeenModulePath = TheIndex->addModulePath(ModulePath, ModuleId);
6315 ModuleIdMap[ModuleId] = LastSeenModulePath->first();
6316
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006317 ModulePath.clear();
6318 break;
6319 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006320 /// MST_CODE_HASH: [5*i32]
6321 case bitc::MST_CODE_HASH: {
6322 if (Record.size() != 5)
6323 return error("Invalid hash length " + Twine(Record.size()).str());
6324 if (LastSeenModulePath == TheIndex->modulePaths().end())
6325 return error("Invalid hash that does not follow a module path");
6326 int Pos = 0;
6327 for (auto &Val : Record) {
6328 assert(!(Val >> 32) && "Unexpected high bits set");
6329 LastSeenModulePath->second.second[Pos++] = Val;
6330 }
6331 // Reset LastSeenModulePath to avoid overriding the hash unexpectedly.
6332 LastSeenModulePath = TheIndex->modulePaths().end();
6333 break;
6334 }
Teresa Johnson403a7872015-10-04 14:33:43 +00006335 }
6336 }
6337 llvm_unreachable("Exit infinite loop");
6338}
6339
6340// Parse the function info index from the bitcode streamer into the given index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006341std::error_code ModuleSummaryIndexBitcodeReader::parseSummaryIndexInto(
6342 std::unique_ptr<DataStreamer> Streamer, ModuleSummaryIndex *I) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006343 TheIndex = I;
6344
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006345 if (std::error_code EC = initStream(std::move(Streamer)))
6346 return EC;
Teresa Johnson403a7872015-10-04 14:33:43 +00006347
6348 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006349 if (!hasValidBitcodeHeader(Stream))
6350 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006351
6352 // We expect a number of well-defined blocks, though we don't necessarily
6353 // need to understand them all.
6354 while (1) {
6355 if (Stream.AtEndOfStream()) {
6356 // We didn't really read a proper Module block.
6357 return error("Malformed block");
6358 }
6359
6360 BitstreamEntry Entry =
6361 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
6362
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006363 if (Entry.Kind != BitstreamEntry::SubBlock)
6364 return error("Malformed block");
Teresa Johnson403a7872015-10-04 14:33:43 +00006365
6366 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
6367 // building the function summary index.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006368 if (Entry.ID == bitc::MODULE_BLOCK_ID)
6369 return parseModule();
Teresa Johnson403a7872015-10-04 14:33:43 +00006370
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006371 if (Stream.SkipBlock())
6372 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00006373 }
6374}
6375
Teresa Johnson26ab5772016-03-15 00:04:37 +00006376std::error_code ModuleSummaryIndexBitcodeReader::initStream(
6377 std::unique_ptr<DataStreamer> Streamer) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006378 if (Streamer)
6379 return initLazyStream(std::move(Streamer));
Teresa Johnson403a7872015-10-04 14:33:43 +00006380 return initStreamFromBuffer();
6381}
6382
Teresa Johnson26ab5772016-03-15 00:04:37 +00006383std::error_code ModuleSummaryIndexBitcodeReader::initStreamFromBuffer() {
Teresa Johnson403a7872015-10-04 14:33:43 +00006384 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
6385 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
6386
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006387 if (Buffer->getBufferSize() & 3)
6388 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006389
6390 // If we have a wrapper header, parse it and ignore the non-bc file contents.
6391 // The magic number is 0x0B17C0DE stored in little endian.
6392 if (isBitcodeWrapper(BufPtr, BufEnd))
6393 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
6394 return error("Invalid bitcode wrapper header");
6395
6396 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
6397 Stream.init(&*StreamFile);
6398
6399 return std::error_code();
6400}
6401
Teresa Johnson26ab5772016-03-15 00:04:37 +00006402std::error_code ModuleSummaryIndexBitcodeReader::initLazyStream(
Teresa Johnson403a7872015-10-04 14:33:43 +00006403 std::unique_ptr<DataStreamer> Streamer) {
6404 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
6405 // see it.
6406 auto OwnedBytes =
6407 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
6408 StreamingMemoryObject &Bytes = *OwnedBytes;
6409 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
6410 Stream.init(&*StreamFile);
6411
6412 unsigned char buf[16];
6413 if (Bytes.readBytes(buf, 16, 0) != 16)
6414 return error("Invalid bitcode signature");
6415
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006416 if (!isBitcode(buf, buf + 16))
6417 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006418
6419 if (isBitcodeWrapper(buf, buf + 4)) {
6420 const unsigned char *bitcodeStart = buf;
6421 const unsigned char *bitcodeEnd = buf + 16;
6422 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
6423 Bytes.dropLeadingBytes(bitcodeStart - buf);
6424 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
6425 }
6426 return std::error_code();
6427}
6428
Rafael Espindola48da4f42013-11-04 16:16:24 +00006429namespace {
Peter Collingbourne4718f8b2016-05-24 20:13:46 +00006430// FIXME: This class is only here to support the transition to llvm::Error. It
6431// will be removed once this transition is complete. Clients should prefer to
6432// deal with the Error value directly, rather than converting to error_code.
Rafael Espindola25188c92014-06-12 01:45:43 +00006433class BitcodeErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +00006434 const char *name() const LLVM_NOEXCEPT override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00006435 return "llvm.bitcode";
6436 }
Craig Topper73156022014-03-02 09:09:27 +00006437 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006438 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00006439 switch (E) {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006440 case BitcodeError::InvalidBitcodeSignature:
Rafael Espindola48da4f42013-11-04 16:16:24 +00006441 return "Invalid bitcode signature";
Rafael Espindolad0b23be2015-01-10 00:07:30 +00006442 case BitcodeError::CorruptedBitcode:
6443 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00006444 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00006445 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00006446 }
6447};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00006448} // end anonymous namespace
Rafael Espindola48da4f42013-11-04 16:16:24 +00006449
Chris Bieneman770163e2014-09-19 20:29:02 +00006450static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
6451
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006452const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00006453 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006454}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00006455
Chris Lattner6694f602007-04-29 07:54:31 +00006456//===----------------------------------------------------------------------===//
6457// External interface
6458//===----------------------------------------------------------------------===//
6459
Rafael Espindola456baad2015-06-17 01:15:47 +00006460static ErrorOr<std::unique_ptr<Module>>
6461getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
6462 BitcodeReader *R, LLVMContext &Context,
6463 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
6464 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
6465 M->setMaterializer(R);
6466
6467 auto cleanupOnError = [&](std::error_code EC) {
6468 R->releaseBuffer(); // Never take ownership on error.
6469 return EC;
6470 };
6471
6472 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
6473 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
6474 ShouldLazyLoadMetadata))
6475 return cleanupOnError(EC);
6476
6477 if (MaterializeAll) {
6478 // Read in the entire module, and destroy the BitcodeReader.
Rafael Espindolac4a03482015-12-18 20:13:39 +00006479 if (std::error_code EC = M->materializeAll())
Rafael Espindola456baad2015-06-17 01:15:47 +00006480 return cleanupOnError(EC);
6481 } else {
6482 // Resolve forward references from blockaddresses.
6483 if (std::error_code EC = R->materializeForwardReferencedFunctions())
6484 return cleanupOnError(EC);
6485 }
6486 return std::move(M);
6487}
6488
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006489/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00006490///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006491/// This isn't always used in a lazy context. In particular, it's also used by
6492/// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
6493/// in forward-referenced functions from block address references.
6494///
Rafael Espindola728074b2015-06-17 00:40:56 +00006495/// \param[in] MaterializeAll Set to \c true if we should materialize
6496/// everything.
Rafael Espindoladcd1dca2015-06-16 22:27:55 +00006497static ErrorOr<std::unique_ptr<Module>>
Rafael Espindola68812152014-09-03 17:31:46 +00006498getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindola728074b2015-06-17 00:40:56 +00006499 LLVMContext &Context, bool MaterializeAll,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00006500 bool ShouldLazyLoadMetadata = false) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006501 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00006502
Rafael Espindola456baad2015-06-17 01:15:47 +00006503 ErrorOr<std::unique_ptr<Module>> Ret =
6504 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
6505 MaterializeAll, ShouldLazyLoadMetadata);
6506 if (!Ret)
6507 return Ret;
Rafael Espindolab7993462012-01-02 07:49:53 +00006508
Rafael Espindolae2c1d772014-08-26 22:00:09 +00006509 Buffer.release(); // The BitcodeReader owns it now.
Rafael Espindola456baad2015-06-17 01:15:47 +00006510 return Ret;
Chris Lattner6694f602007-04-29 07:54:31 +00006511}
6512
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006513ErrorOr<std::unique_ptr<Module>>
6514llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
6515 LLVMContext &Context, bool ShouldLazyLoadMetadata) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00006516 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006517 ShouldLazyLoadMetadata);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006518}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006519
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006520ErrorOr<std::unique_ptr<Module>>
6521llvm::getStreamedBitcodeModule(StringRef Name,
6522 std::unique_ptr<DataStreamer> Streamer,
6523 LLVMContext &Context) {
Rafael Espindola7d727b52014-12-18 05:08:43 +00006524 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006525 BitcodeReader *R = new BitcodeReader(Context);
Rafael Espindola456baad2015-06-17 01:15:47 +00006526
6527 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
6528 false);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006529}
6530
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006531ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
6532 LLVMContext &Context) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00006533 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006534 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
Chad Rosierca2567b2011-12-07 21:44:12 +00006535 // TODO: Restore the use-lists to the in-memory state when the bitcode was
6536 // written. We must defer until the Module has been fully materialized.
Chris Lattner6694f602007-04-29 07:54:31 +00006537}
Bill Wendling0198ce02010-10-06 01:22:42 +00006538
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006539std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
6540 LLVMContext &Context) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00006541 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006542 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00006543 ErrorOr<std::string> Triple = R->parseTriple();
Rafael Espindolad346cc82014-07-04 13:52:01 +00006544 if (Triple.getError())
6545 return "";
6546 return Triple.get();
Bill Wendling0198ce02010-10-06 01:22:42 +00006547}
Teresa Johnson403a7872015-10-04 14:33:43 +00006548
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006549std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
6550 LLVMContext &Context) {
Mehdi Amini3383ccc2015-11-09 02:46:41 +00006551 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006552 BitcodeReader R(Buf.release(), Context);
Mehdi Amini3383ccc2015-11-09 02:46:41 +00006553 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
6554 if (ProducerString.getError())
6555 return "";
6556 return ProducerString.get();
6557}
6558
Teresa Johnson403a7872015-10-04 14:33:43 +00006559// Parse the specified bitcode buffer, returning the function info index.
Benjamin Kramer1afc1de2016-06-17 20:41:14 +00006560ErrorOr<std::unique_ptr<ModuleSummaryIndex>> llvm::getModuleSummaryIndex(
6561 MemoryBufferRef Buffer,
6562 const DiagnosticHandlerFunction &DiagnosticHandler) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006563 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Teresa Johnson6fb3f192016-04-22 01:52:00 +00006564 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler);
Teresa Johnson403a7872015-10-04 14:33:43 +00006565
Teresa Johnson26ab5772016-03-15 00:04:37 +00006566 auto Index = llvm::make_unique<ModuleSummaryIndex>();
Teresa Johnson403a7872015-10-04 14:33:43 +00006567
6568 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006569 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00006570 return EC;
6571 };
6572
6573 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
6574 return cleanupOnError(EC);
6575
Teresa Johnson26ab5772016-03-15 00:04:37 +00006576 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
Teresa Johnson403a7872015-10-04 14:33:43 +00006577 return std::move(Index);
6578}
6579
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006580// Check if the given bitcode buffer contains a global value summary block.
Benjamin Kramer1afc1de2016-06-17 20:41:14 +00006581bool llvm::hasGlobalValueSummary(
6582 MemoryBufferRef Buffer,
6583 const DiagnosticHandlerFunction &DiagnosticHandler) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006584 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Teresa Johnson6fb3f192016-04-22 01:52:00 +00006585 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler, true);
Teresa Johnson403a7872015-10-04 14:33:43 +00006586
6587 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006588 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00006589 return false;
6590 };
6591
6592 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
6593 return cleanupOnError(EC);
6594
Teresa Johnson26ab5772016-03-15 00:04:37 +00006595 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006596 return R.foundGlobalValSummary();
Teresa Johnson403a7872015-10-04 14:33:43 +00006597}