blob: 9aaf3500cad43aca3faafd14b4e318997198dc2b [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;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001467 case bitc::ATTR_KIND_WRITEONLY:
1468 return Attribute::WriteOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001469 case bitc::ATTR_KIND_Z_EXT:
1470 return Attribute::ZExt;
1471 }
1472}
1473
JF Bastien30bf96b2015-02-22 19:32:03 +00001474std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1475 unsigned &Alignment) {
1476 // Note: Alignment in bitcode files is incremented by 1, so that zero
1477 // can be used for default alignment.
1478 if (Exponent > Value::MaxAlignmentExponent + 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001479 return error("Invalid alignment value");
JF Bastien30bf96b2015-02-22 19:32:03 +00001480 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1481 return std::error_code();
1482}
1483
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001484std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001485 Attribute::AttrKind *Kind) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001486 *Kind = getAttrFromCode(Code);
Reid Klecknere9f36af2013-11-12 01:31:00 +00001487 if (*Kind == Attribute::None)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001488 return error(BitcodeError::CorruptedBitcode,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001489 "Unknown attribute kind (" + Twine(Code) + ")");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001490 return std::error_code();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001491}
1492
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001493std::error_code BitcodeReader::parseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +00001494 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001495 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001496
1497 if (!MAttributeGroups.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001498 return error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +00001499
1500 SmallVector<uint64_t, 64> Record;
1501
1502 // Read all the records.
1503 while (1) {
1504 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1505
1506 switch (Entry.Kind) {
1507 case BitstreamEntry::SubBlock: // Handled for us already.
1508 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001509 return error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +00001510 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001511 return std::error_code();
Bill Wendlingba629332013-02-10 23:24:25 +00001512 case BitstreamEntry::Record:
1513 // The interesting case.
1514 break;
1515 }
1516
1517 // Read a record.
1518 Record.clear();
1519 switch (Stream.readRecord(Entry.ID, Record)) {
1520 default: // Default behavior: ignore.
1521 break;
1522 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1523 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001524 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001525
Bill Wendlinge46707e2013-02-11 22:32:29 +00001526 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +00001527 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1528
1529 AttrBuilder B;
1530 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1531 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001532 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001533 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001534 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001535
1536 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +00001537 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001538 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001539 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001540 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001541 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001542 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001543 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001544 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001545 else if (Kind == Attribute::Dereferenceable)
1546 B.addDereferenceableAttr(Record[++i]);
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001547 else if (Kind == Attribute::DereferenceableOrNull)
1548 B.addDereferenceableOrNullAttr(Record[++i]);
George Burgess IV278199f2016-04-12 01:05:35 +00001549 else if (Kind == Attribute::AllocSize)
1550 B.addAllocSizeAttrFromRawRepr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +00001551 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +00001552 assert((Record[i] == 3 || Record[i] == 4) &&
1553 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +00001554 bool HasValue = (Record[i++] == 4);
1555 SmallString<64> KindStr;
1556 SmallString<64> ValStr;
1557
1558 while (Record[i] != 0 && i != e)
1559 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001560 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001561
1562 if (HasValue) {
1563 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +00001564 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +00001565 while (Record[i] != 0 && i != e)
1566 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001567 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001568 }
1569
1570 B.addAttribute(KindStr.str(), ValStr.str());
1571 }
1572 }
1573
Bill Wendlinge46707e2013-02-11 22:32:29 +00001574 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +00001575 break;
1576 }
1577 }
1578 }
1579}
1580
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001581std::error_code BitcodeReader::parseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001582 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001583 return error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +00001584
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001585 return parseTypeTableBody();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001586}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001587
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001588std::error_code BitcodeReader::parseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +00001589 if (!TypeList.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001590 return error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +00001591
1592 SmallVector<uint64_t, 64> Record;
1593 unsigned NumRecords = 0;
1594
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001595 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +00001596
Chris Lattner1314b992007-04-22 06:23:29 +00001597 // Read all the records for this type table.
1598 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001599 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001600
Chris Lattner27d38752013-01-20 02:13:19 +00001601 switch (Entry.Kind) {
1602 case BitstreamEntry::SubBlock: // Handled for us already.
1603 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001604 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001605 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +00001606 if (NumRecords != TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001607 return error("Malformed block");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001608 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001609 case BitstreamEntry::Record:
1610 // The interesting case.
1611 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001612 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001613
Chris Lattner1314b992007-04-22 06:23:29 +00001614 // Read a record.
1615 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001616 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001617 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001618 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001619 return error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +00001620 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1621 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1622 // type list. This allows us to reserve space.
1623 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001624 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001625 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001626 continue;
Chris Lattner1314b992007-04-22 06:23:29 +00001627 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +00001628 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001629 break;
Dan Gohman518cda42011-12-17 00:04:22 +00001630 case bitc::TYPE_CODE_HALF: // HALF
1631 ResultTy = Type::getHalfTy(Context);
1632 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001633 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +00001634 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001635 break;
1636 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +00001637 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001638 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001639 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +00001640 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001641 break;
1642 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001643 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001644 break;
1645 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001646 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001647 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001648 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +00001649 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001650 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001651 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +00001652 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001653 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +00001654 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1655 ResultTy = Type::getX86_MMXTy(Context);
1656 break;
David Majnemerb611e3f2015-08-14 05:09:07 +00001657 case bitc::TYPE_CODE_TOKEN: // TOKEN
1658 ResultTy = Type::getTokenTy(Context);
1659 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001660 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
Chris Lattner1314b992007-04-22 06:23:29 +00001661 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001662 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001663
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001664 uint64_t NumBits = Record[0];
1665 if (NumBits < IntegerType::MIN_INT_BITS ||
1666 NumBits > IntegerType::MAX_INT_BITS)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001667 return error("Bitwidth for integer type out of range");
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001668 ResultTy = IntegerType::get(Context, NumBits);
Chris Lattner1314b992007-04-22 06:23:29 +00001669 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001670 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001671 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001672 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +00001673 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001674 return error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001675 unsigned AddressSpace = 0;
1676 if (Record.size() == 2)
1677 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001678 ResultTy = getTypeByID(Record[0]);
Filipe Cabecinhasd8a1bcd2015-04-29 02:27:28 +00001679 if (!ResultTy ||
1680 !PointerType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001681 return error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001682 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +00001683 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001684 }
Nuno Lopes561dae02012-05-23 15:19:39 +00001685 case bitc::TYPE_CODE_FUNCTION_OLD: {
1686 // FIXME: attrid is dead, remove it in LLVM 4.0
1687 // FUNCTION: [vararg, attrid, retty, paramty x N]
1688 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001689 return error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +00001690 SmallVector<Type*, 8> ArgTys;
1691 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1692 if (Type *T = getTypeByID(Record[i]))
1693 ArgTys.push_back(T);
1694 else
1695 break;
1696 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001697
Nuno Lopes561dae02012-05-23 15:19:39 +00001698 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001699 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001700 return error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +00001701
1702 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1703 break;
1704 }
Chad Rosier95898722011-11-03 00:14:01 +00001705 case bitc::TYPE_CODE_FUNCTION: {
1706 // FUNCTION: [vararg, retty, paramty x N]
1707 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001708 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001709 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +00001710 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001711 if (Type *T = getTypeByID(Record[i])) {
1712 if (!FunctionType::isValidArgumentType(T))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001713 return error("Invalid function argument type");
Chad Rosier95898722011-11-03 00:14:01 +00001714 ArgTys.push_back(T);
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001715 }
Chad Rosier95898722011-11-03 00:14:01 +00001716 else
1717 break;
1718 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001719
Chad Rosier95898722011-11-03 00:14:01 +00001720 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001721 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001722 return error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +00001723
1724 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1725 break;
1726 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001727 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +00001728 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001729 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001730 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001731 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1732 if (Type *T = getTypeByID(Record[i]))
1733 EltTys.push_back(T);
1734 else
1735 break;
1736 }
1737 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001738 return error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001739 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001740 break;
1741 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001742 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001743 if (convertToString(Record, 0, TypeName))
1744 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001745 continue;
1746
1747 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1748 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001749 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001750
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001751 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001752 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001753
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001754 // Check to see if this was forward referenced, if so fill in the temp.
1755 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1756 if (Res) {
1757 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001758 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001759 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001760 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001761 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001762
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001763 SmallVector<Type*, 8> EltTys;
1764 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1765 if (Type *T = getTypeByID(Record[i]))
1766 EltTys.push_back(T);
1767 else
1768 break;
1769 }
1770 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001771 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001772 Res->setBody(EltTys, Record[0]);
1773 ResultTy = Res;
1774 break;
1775 }
1776 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1777 if (Record.size() != 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001778 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001779
1780 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001781 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001782
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001783 // Check to see if this was forward referenced, if so fill in the temp.
1784 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1785 if (Res) {
1786 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001787 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001788 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001789 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001790 TypeName.clear();
1791 ResultTy = Res;
1792 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001793 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001794 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1795 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001796 return error("Invalid record");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001797 ResultTy = getTypeByID(Record[1]);
1798 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001799 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001800 ResultTy = ArrayType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001801 break;
1802 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1803 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001804 return error("Invalid record");
Filipe Cabecinhas8e421902015-06-03 00:05:30 +00001805 if (Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001806 return error("Invalid vector length");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001807 ResultTy = getTypeByID(Record[1]);
1808 if (!ResultTy || !StructType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001809 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001810 ResultTy = VectorType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001811 break;
1812 }
1813
1814 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001815 return error("Invalid TYPE table");
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001816 if (TypeList[NumRecords])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001817 return error(
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001818 "Invalid TYPE table: Only named structs can be forward referenced");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001819 assert(ResultTy && "Didn't read a type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001820 TypeList[NumRecords++] = ResultTy;
1821 }
1822}
1823
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001824std::error_code BitcodeReader::parseOperandBundleTags() {
1825 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1826 return error("Invalid record");
1827
1828 if (!BundleTags.empty())
1829 return error("Invalid multiple blocks");
1830
1831 SmallVector<uint64_t, 64> Record;
1832
1833 while (1) {
1834 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1835
1836 switch (Entry.Kind) {
1837 case BitstreamEntry::SubBlock: // Handled for us already.
1838 case BitstreamEntry::Error:
1839 return error("Malformed block");
1840 case BitstreamEntry::EndBlock:
1841 return std::error_code();
1842 case BitstreamEntry::Record:
1843 // The interesting case.
1844 break;
1845 }
1846
1847 // Tags are implicitly mapped to integers by their order.
1848
1849 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1850 return error("Invalid record");
1851
1852 // OPERAND_BUNDLE_TAG: [strchr x N]
1853 BundleTags.emplace_back();
1854 if (convertToString(Record, 0, BundleTags.back()))
1855 return error("Invalid record");
1856 Record.clear();
1857 }
1858}
1859
Teresa Johnsonff642b92015-09-17 20:12:00 +00001860/// Associate a value with its name from the given index in the provided record.
1861ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1862 unsigned NameIndex, Triple &TT) {
1863 SmallString<128> ValueName;
1864 if (convertToString(Record, NameIndex, ValueName))
1865 return error("Invalid record");
1866 unsigned ValueID = Record[0];
1867 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1868 return error("Invalid record");
1869 Value *V = ValueList[ValueID];
1870
Filipe Cabecinhasa2b0ac42015-11-04 14:53:36 +00001871 StringRef NameStr(ValueName.data(), ValueName.size());
1872 if (NameStr.find_first_of(0) != StringRef::npos)
1873 return error("Invalid value name");
1874 V->setName(NameStr);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001875 auto *GO = dyn_cast<GlobalObject>(V);
1876 if (GO) {
1877 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1878 if (TT.isOSBinFormatMachO())
1879 GO->setComdat(nullptr);
1880 else
1881 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1882 }
1883 }
1884 return V;
1885}
1886
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001887/// Helper to note and return the current location, and jump to the given
1888/// offset.
1889static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1890 BitstreamCursor &Stream) {
1891 // Save the current parsing location so we can jump back at the end
1892 // of the VST read.
1893 uint64_t CurrentBit = Stream.GetCurrentBitNo();
1894 Stream.JumpToBit(Offset * 32);
1895#ifndef NDEBUG
1896 // Do some checking if we are in debug mode.
1897 BitstreamEntry Entry = Stream.advance();
1898 assert(Entry.Kind == BitstreamEntry::SubBlock);
1899 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1900#else
1901 // In NDEBUG mode ignore the output so we don't get an unused variable
1902 // warning.
1903 Stream.advance();
1904#endif
1905 return CurrentBit;
1906}
1907
Teresa Johnsonff642b92015-09-17 20:12:00 +00001908/// Parse the value symbol table at either the current parsing location or
1909/// at the given bit offset if provided.
Peter Collingbourne128a9762015-10-27 23:01:25 +00001910std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001911 uint64_t CurrentBit;
1912 // Pass in the Offset to distinguish between calling for the module-level
1913 // VST (where we want to jump to the VST offset) and the function-level
1914 // VST (where we don't).
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001915 if (Offset > 0)
1916 CurrentBit = jumpToValueSymbolTable(Offset, Stream);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001917
1918 // Compute the delta between the bitcode indices in the VST (the word offset
1919 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1920 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1921 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1922 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1923 // just before entering the VST subblock because: 1) the EnterSubBlock
1924 // changes the AbbrevID width; 2) the VST block is nested within the same
1925 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1926 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1927 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1928 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1929 unsigned FuncBitcodeOffsetDelta =
1930 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1931
Chris Lattner982ec1e2007-05-05 00:17:00 +00001932 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001933 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001934
1935 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001936
David Majnemer3087b222015-01-20 05:58:07 +00001937 Triple TT(TheModule->getTargetTriple());
1938
Chris Lattnerccaa4482007-04-23 21:26:05 +00001939 // Read all the records for this value table.
1940 SmallString<128> ValueName;
1941 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001942 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001943
Chris Lattner27d38752013-01-20 02:13:19 +00001944 switch (Entry.Kind) {
1945 case BitstreamEntry::SubBlock: // Handled for us already.
1946 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001947 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001948 case BitstreamEntry::EndBlock:
Teresa Johnsonff642b92015-09-17 20:12:00 +00001949 if (Offset > 0)
1950 Stream.JumpToBit(CurrentBit);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001951 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001952 case BitstreamEntry::Record:
1953 // The interesting case.
1954 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001955 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001956
Chris Lattnerccaa4482007-04-23 21:26:05 +00001957 // Read a record.
1958 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001959 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001960 default: // Default behavior: unknown type.
1961 break;
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001962 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
Teresa Johnsonff642b92015-09-17 20:12:00 +00001963 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1964 if (std::error_code EC = ValOrErr.getError())
1965 return EC;
1966 ValOrErr.get();
1967 break;
1968 }
1969 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001970 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonff642b92015-09-17 20:12:00 +00001971 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1972 if (std::error_code EC = ValOrErr.getError())
1973 return EC;
1974 Value *V = ValOrErr.get();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001975
Teresa Johnsonff642b92015-09-17 20:12:00 +00001976 auto *GO = dyn_cast<GlobalObject>(V);
1977 if (!GO) {
1978 // If this is an alias, need to get the actual Function object
1979 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1980 auto *GA = dyn_cast<GlobalAlias>(V);
1981 if (GA)
1982 GO = GA->getBaseObject();
1983 assert(GO);
Rafael Espindola12ca34f2015-01-19 15:16:06 +00001984 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001985
1986 uint64_t FuncWordOffset = Record[1];
1987 Function *F = dyn_cast<Function>(GO);
1988 assert(F);
1989 uint64_t FuncBitOffset = FuncWordOffset * 32;
1990 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
Teresa Johnson1493ad92015-10-10 14:18:36 +00001991 // Set the LastFunctionBlockBit to point to the last function block.
Teresa Johnsonff642b92015-09-17 20:12:00 +00001992 // Later when parsing is resumed after function materialization,
1993 // we can simply skip that last function block.
Teresa Johnson1493ad92015-10-10 14:18:36 +00001994 if (FuncBitOffset > LastFunctionBlockBit)
1995 LastFunctionBlockBit = FuncBitOffset;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001996 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00001997 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00001998 case bitc::VST_CODE_BBENTRY: {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001999 if (convertToString(Record, 1, ValueName))
2000 return error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00002001 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002002 if (!BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002003 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002004
Daniel Dunbard786b512009-07-26 00:34:27 +00002005 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00002006 ValueName.clear();
2007 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00002008 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00002009 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00002010 }
2011}
2012
Teresa Johnson12545072015-11-15 02:00:09 +00002013/// Parse a single METADATA_KIND record, inserting result in MDKindMap.
2014std::error_code
2015BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
2016 if (Record.size() < 2)
2017 return error("Invalid record");
2018
2019 unsigned Kind = Record[0];
2020 SmallString<8> Name(Record.begin() + 1, Record.end());
2021
2022 unsigned NewKind = TheModule->getMDKindID(Name.str());
2023 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2024 return error("Conflicting METADATA_KIND records");
2025 return std::error_code();
2026}
2027
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002028static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
2029
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002030std::error_code BitcodeReader::parseMetadataStrings(ArrayRef<uint64_t> Record,
2031 StringRef Blob,
2032 unsigned &NextMetadataNo) {
2033 // All the MDStrings in the block are emitted together in a single
2034 // record. The strings are concatenated and stored in a blob along with
2035 // their sizes.
2036 if (Record.size() != 2)
2037 return error("Invalid record: metadata strings layout");
2038
2039 unsigned NumStrings = Record[0];
2040 unsigned StringsOffset = Record[1];
2041 if (!NumStrings)
2042 return error("Invalid record: metadata strings with no strings");
Duncan P. N. Exon Smithbb7ce3b2016-03-29 05:25:17 +00002043 if (StringsOffset > Blob.size())
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002044 return error("Invalid record: metadata strings corrupt offset");
2045
2046 StringRef Lengths = Blob.slice(0, StringsOffset);
2047 SimpleBitstreamCursor R(*StreamFile);
2048 R.jumpToPointer(Lengths.begin());
2049
2050 // Ensure that Blob doesn't get invalidated, even if this is reading from
2051 // a StreamingMemoryObject with corrupt data.
2052 R.setArtificialByteLimit(R.getCurrentByteNo() + StringsOffset);
2053
2054 StringRef Strings = Blob.drop_front(StringsOffset);
2055 do {
2056 if (R.AtEndOfStream())
2057 return error("Invalid record: metadata strings bad length");
2058
2059 unsigned Size = R.ReadVBR(6);
2060 if (Strings.size() < Size)
2061 return error("Invalid record: metadata strings truncated chars");
2062
2063 MetadataList.assignValue(MDString::get(Context, Strings.slice(0, Size)),
2064 NextMetadataNo++);
2065 Strings = Strings.drop_front(Size);
2066 } while (--NumStrings);
2067
2068 return std::error_code();
2069}
2070
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002071namespace {
2072class PlaceholderQueue {
2073 // Placeholders would thrash around when moved, so store in a std::deque
2074 // instead of some sort of vector.
2075 std::deque<DistinctMDOperandPlaceholder> PHs;
2076
2077public:
2078 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
2079 void flush(BitcodeReaderMetadataList &MetadataList);
2080};
2081} // end namespace
2082
2083DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
2084 PHs.emplace_back(ID);
2085 return PHs.back();
2086}
2087
2088void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
2089 while (!PHs.empty()) {
2090 PHs.front().replaceUseWith(
2091 MetadataList.getMetadataFwdRef(PHs.front().getID()));
2092 PHs.pop_front();
2093 }
2094}
2095
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00002096/// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
2097/// module level metadata.
2098std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
Duncan P. N. Exon Smith03a04a52016-04-24 15:04:28 +00002099 assert((ModuleLevel || DeferredMetadataInfo.empty()) &&
2100 "Must read all module-level metadata before function-level");
2101
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002102 IsMetadataMaterialized = true;
Teresa Johnson61b406e2015-12-29 23:00:22 +00002103 unsigned NextMetadataNo = MetadataList.size();
Devang Patel7428d8a2009-07-22 17:43:22 +00002104
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00002105 if (!ModuleLevel && MetadataList.hasFwdRefs())
2106 return error("Invalid metadata: fwd refs into function blocks");
2107
Devang Patel7428d8a2009-07-22 17:43:22 +00002108 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002109 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002110
Adrian Prantl75819ae2016-04-15 15:57:41 +00002111 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
Devang Patel7428d8a2009-07-22 17:43:22 +00002112 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002113
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002114 PlaceholderQueue Placeholders;
2115 bool IsDistinct;
Duncan P. N. Exon Smith498b4972016-04-23 04:52:47 +00002116 auto getMD = [&](unsigned ID) -> Metadata * {
2117 if (!IsDistinct)
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002118 return MetadataList.getMetadataFwdRef(ID);
2119 if (auto *MD = MetadataList.getMetadataIfResolved(ID))
2120 return MD;
2121 return &Placeholders.getPlaceholderOp(ID);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002122 };
Duncan P. N. Exon Smith498b4972016-04-23 04:52:47 +00002123 auto getMDOrNull = [&](unsigned ID) -> Metadata * {
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002124 if (ID)
Duncan P. N. Exon Smith498b4972016-04-23 04:52:47 +00002125 return getMD(ID - 1);
2126 return nullptr;
2127 };
2128 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
2129 if (ID)
2130 return MetadataList.getMetadataFwdRef(ID - 1);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002131 return nullptr;
2132 };
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002133 auto getMDString = [&](unsigned ID) -> MDString *{
2134 // This requires that the ID is not really a forward reference. In
2135 // particular, the MDString must already have been resolved.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002136 return cast_or_null<MDString>(getMDOrNull(ID));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002137 };
2138
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002139 // Support for old type refs.
2140 auto getDITypeRefOrNull = [&](unsigned ID) {
2141 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
2142 };
2143
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002144#define GET_OR_DISTINCT(CLASS, ARGS) \
2145 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002146
Devang Patel7428d8a2009-07-22 17:43:22 +00002147 // Read all the records.
2148 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002149 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002150
Chris Lattner27d38752013-01-20 02:13:19 +00002151 switch (Entry.Kind) {
2152 case BitstreamEntry::SubBlock: // Handled for us already.
2153 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002154 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002155 case BitstreamEntry::EndBlock:
Adrian Prantl75819ae2016-04-15 15:57:41 +00002156 // Upgrade old-style CU <-> SP pointers to point from SP to CU.
2157 for (auto CU_SP : CUSubprograms)
2158 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
2159 for (auto &Op : SPs->operands())
2160 if (auto *SP = dyn_cast_or_null<MDNode>(Op))
2161 SP->replaceOperandWith(7, CU_SP.first);
2162
Teresa Johnson61b406e2015-12-29 23:00:22 +00002163 MetadataList.tryToResolveCycles();
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002164 Placeholders.flush(MetadataList);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002165 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002166 case BitstreamEntry::Record:
2167 // The interesting case.
2168 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00002169 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002170
Devang Patel7428d8a2009-07-22 17:43:22 +00002171 // Read a record.
2172 Record.clear();
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002173 StringRef Blob;
2174 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
Duncan P. N. Exon Smith4b1bc642016-04-23 04:15:56 +00002175 IsDistinct = false;
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00002176 switch (Code) {
Devang Patel7428d8a2009-07-22 17:43:22 +00002177 default: // Default behavior: ignore.
2178 break;
Devang Patel27c87ff2009-07-29 22:34:41 +00002179 case bitc::METADATA_NAME: {
Chris Lattner8d140532013-01-20 02:54:05 +00002180 // Read name of the named metadata.
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002181 SmallString<8> Name(Record.begin(), Record.end());
Devang Patel27c87ff2009-07-29 22:34:41 +00002182 Record.clear();
2183 Code = Stream.ReadCode();
2184
Chris Lattner27d38752013-01-20 02:13:19 +00002185 unsigned NextBitCode = Stream.readRecord(Code, Record);
Filipe Cabecinhas14e68672015-05-30 00:17:20 +00002186 if (NextBitCode != bitc::METADATA_NAMED_NODE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002187 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
Devang Patel27c87ff2009-07-29 22:34:41 +00002188
2189 // Read named metadata elements.
2190 unsigned Size = Record.size();
Dan Gohman2637cc12010-07-21 23:38:33 +00002191 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patel27c87ff2009-07-29 22:34:41 +00002192 for (unsigned i = 0; i != Size; ++i) {
Justin Bognerae341c62016-03-17 20:12:06 +00002193 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002194 if (!MD)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002195 return error("Invalid record");
Dan Gohman2637cc12010-07-21 23:38:33 +00002196 NMD->addOperand(MD);
Devang Patel27c87ff2009-07-29 22:34:41 +00002197 }
Devang Patel27c87ff2009-07-29 22:34:41 +00002198 break;
2199 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00002200 case bitc::METADATA_OLD_FN_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00002201 // FIXME: Remove in 4.0.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002202 // This is a LocalAsMetadata record, the only type of function-local
2203 // metadata.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002204 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002205 return error("Invalid record");
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002206
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002207 // If this isn't a LocalAsMetadata record, we're dropping it. This used
2208 // to be legal, but there's no upgrade path.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002209 auto dropRecord = [&] {
Teresa Johnson61b406e2015-12-29 23:00:22 +00002210 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002211 };
2212 if (Record.size() != 2) {
2213 dropRecord();
2214 break;
2215 }
2216
2217 Type *Ty = getTypeByID(Record[0]);
2218 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
2219 dropRecord();
2220 break;
2221 }
2222
Teresa Johnson61b406e2015-12-29 23:00:22 +00002223 MetadataList.assignValue(
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002224 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002225 NextMetadataNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002226 break;
2227 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00002228 case bitc::METADATA_OLD_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00002229 // FIXME: Remove in 4.0.
Dan Gohman1e0213a2010-07-13 19:33:27 +00002230 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002231 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002232
Devang Patele059ba6e2009-07-23 01:07:34 +00002233 unsigned Size = Record.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002234 SmallVector<Metadata *, 8> Elts;
Devang Patele059ba6e2009-07-23 01:07:34 +00002235 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00002236 Type *Ty = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002237 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002238 return error("Invalid record");
Chris Lattnerfdd87902009-10-05 05:54:46 +00002239 if (Ty->isMetadataTy())
Duncan P. N. Exon Smith004509d2016-04-23 03:55:14 +00002240 Elts.push_back(getMD(Record[i + 1]));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002241 else if (!Ty->isVoidTy()) {
2242 auto *MD =
2243 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2244 assert(isa<ConstantAsMetadata>(MD) &&
2245 "Expected non-function-local metadata");
2246 Elts.push_back(MD);
2247 } else
Craig Topper2617dcc2014-04-15 06:32:26 +00002248 Elts.push_back(nullptr);
Devang Patele059ba6e2009-07-23 01:07:34 +00002249 }
Teresa Johnson61b406e2015-12-29 23:00:22 +00002250 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++);
Devang Patele059ba6e2009-07-23 01:07:34 +00002251 break;
2252 }
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002253 case bitc::METADATA_VALUE: {
2254 if (Record.size() != 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002255 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002256
2257 Type *Ty = getTypeByID(Record[0]);
2258 if (Ty->isMetadataTy() || Ty->isVoidTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002259 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002260
Teresa Johnson61b406e2015-12-29 23:00:22 +00002261 MetadataList.assignValue(
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002262 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002263 NextMetadataNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002264 break;
2265 }
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00002266 case bitc::METADATA_DISTINCT_NODE:
2267 IsDistinct = true;
2268 // fallthrough...
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002269 case bitc::METADATA_NODE: {
2270 SmallVector<Metadata *, 8> Elts;
2271 Elts.reserve(Record.size());
2272 for (unsigned ID : Record)
Duncan P. N. Exon Smith004509d2016-04-23 03:55:14 +00002273 Elts.push_back(getMDOrNull(ID));
Teresa Johnson61b406e2015-12-29 23:00:22 +00002274 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2275 : MDNode::get(Context, Elts),
2276 NextMetadataNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002277 break;
2278 }
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002279 case bitc::METADATA_LOCATION: {
2280 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002281 return error("Invalid record");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002282
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002283 IsDistinct = Record[0];
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002284 unsigned Line = Record[1];
2285 unsigned Column = Record[2];
Duncan P. N. Exon Smith004509d2016-04-23 03:55:14 +00002286 Metadata *Scope = getMD(Record[3]);
2287 Metadata *InlinedAt = getMDOrNull(Record[4]);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002288 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002289 GET_OR_DISTINCT(DILocation,
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00002290 (Context, Line, Column, Scope, InlinedAt)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002291 NextMetadataNo++);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002292 break;
2293 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002294 case bitc::METADATA_GENERIC_DEBUG: {
2295 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002296 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002297
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002298 IsDistinct = Record[0];
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002299 unsigned Tag = Record[1];
2300 unsigned Version = Record[2];
2301
2302 if (Tag >= 1u << 16 || Version != 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002303 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002304
2305 auto *Header = getMDString(Record[3]);
2306 SmallVector<Metadata *, 8> DwarfOps;
2307 for (unsigned I = 4, E = Record.size(); I != E; ++I)
Duncan P. N. Exon Smith004509d2016-04-23 03:55:14 +00002308 DwarfOps.push_back(getMDOrNull(Record[I]));
Teresa Johnson61b406e2015-12-29 23:00:22 +00002309 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002310 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002311 NextMetadataNo++);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002312 break;
2313 }
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002314 case bitc::METADATA_SUBRANGE: {
2315 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002316 return error("Invalid record");
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002317
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002318 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002319 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002320 GET_OR_DISTINCT(DISubrange,
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002321 (Context, Record[1], unrotateSign(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002322 NextMetadataNo++);
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002323 break;
2324 }
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002325 case bitc::METADATA_ENUMERATOR: {
2326 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002327 return error("Invalid record");
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002328
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002329 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002330 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002331 GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]),
2332 getMDString(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002333 NextMetadataNo++);
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002334 break;
2335 }
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002336 case bitc::METADATA_BASIC_TYPE: {
2337 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002338 return error("Invalid record");
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002339
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002340 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002341 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002342 GET_OR_DISTINCT(DIBasicType,
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002343 (Context, Record[1], getMDString(Record[2]),
2344 Record[3], Record[4], Record[5])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002345 NextMetadataNo++);
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002346 break;
2347 }
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002348 case bitc::METADATA_DERIVED_TYPE: {
2349 if (Record.size() != 12)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002350 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002351
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002352 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002353 MetadataList.assignValue(
Duncan P. N. Exon Smith5892c6b2016-04-24 06:52:01 +00002354 GET_OR_DISTINCT(
2355 DIDerivedType,
2356 (Context, Record[1], getMDString(Record[2]),
2357 getMDOrNull(Record[3]), Record[4], getDITypeRefOrNull(Record[5]),
2358 getDITypeRefOrNull(Record[6]), Record[7], Record[8], Record[9],
2359 Record[10], getDITypeRefOrNull(Record[11]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002360 NextMetadataNo++);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002361 break;
2362 }
2363 case bitc::METADATA_COMPOSITE_TYPE: {
2364 if (Record.size() != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002365 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002366
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002367 // If we have a UUID and this is not a forward declaration, lookup the
2368 // mapping.
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002369 IsDistinct = Record[0] & 0x1;
2370 bool IsNotUsedInTypeRef = Record[0] >= 2;
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002371 unsigned Tag = Record[1];
2372 MDString *Name = getMDString(Record[2]);
2373 Metadata *File = getMDOrNull(Record[3]);
2374 unsigned Line = Record[4];
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002375 Metadata *Scope = getDITypeRefOrNull(Record[5]);
2376 Metadata *BaseType = getDITypeRefOrNull(Record[6]);
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002377 uint64_t SizeInBits = Record[7];
2378 uint64_t AlignInBits = Record[8];
2379 uint64_t OffsetInBits = Record[9];
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002380 unsigned Flags = Record[10];
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002381 Metadata *Elements = getMDOrNull(Record[11]);
2382 unsigned RuntimeLang = Record[12];
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002383 Metadata *VTableHolder = getDITypeRefOrNull(Record[13]);
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002384 Metadata *TemplateParams = getMDOrNull(Record[14]);
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002385 auto *Identifier = getMDString(Record[15]);
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002386 DICompositeType *CT = nullptr;
Duncan P. N. Exon Smith97386022016-04-19 18:00:19 +00002387 if (Identifier)
2388 CT = DICompositeType::buildODRType(
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002389 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
2390 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
2391 VTableHolder, TemplateParams);
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002392
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002393 // Create a node if we didn't get a lazy ODR type.
2394 if (!CT)
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002395 CT = GET_OR_DISTINCT(DICompositeType,
Duncan P. N. Exon Smith0b0271e2016-04-19 14:55:09 +00002396 (Context, Tag, Name, File, Line, Scope, BaseType,
2397 SizeInBits, AlignInBits, OffsetInBits, Flags,
2398 Elements, RuntimeLang, VTableHolder,
2399 TemplateParams, Identifier));
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002400 if (!IsNotUsedInTypeRef && Identifier)
2401 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
Duncan P. N. Exon Smith5ab2be02016-04-17 03:58:21 +00002402
2403 MetadataList.assignValue(CT, NextMetadataNo++);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002404 break;
2405 }
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002406 case bitc::METADATA_SUBROUTINE_TYPE: {
Reid Klecknerde3d8b52016-06-08 20:34:29 +00002407 if (Record.size() < 3 || Record.size() > 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002408 return error("Invalid record");
Reid Klecknerde3d8b52016-06-08 20:34:29 +00002409 bool IsOldTypeRefArray = Record[0] < 2;
2410 unsigned CC = (Record.size() > 3) ? Record[3] : 0;
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002411
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002412 IsDistinct = Record[0] & 0x1;
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002413 Metadata *Types = getMDOrNull(Record[2]);
2414 if (LLVM_UNLIKELY(IsOldTypeRefArray))
2415 Types = MetadataList.upgradeTypeRefArray(Types);
2416
Teresa Johnson61b406e2015-12-29 23:00:22 +00002417 MetadataList.assignValue(
Reid Klecknerde3d8b52016-06-08 20:34:29 +00002418 GET_OR_DISTINCT(DISubroutineType, (Context, Record[1], CC, Types)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002419 NextMetadataNo++);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002420 break;
2421 }
Adrian Prantlab1243f2015-06-29 23:03:47 +00002422
2423 case bitc::METADATA_MODULE: {
2424 if (Record.size() != 6)
2425 return error("Invalid record");
2426
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002427 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002428 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002429 GET_OR_DISTINCT(DIModule,
Adrian Prantlab1243f2015-06-29 23:03:47 +00002430 (Context, getMDOrNull(Record[1]),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002431 getMDString(Record[2]), getMDString(Record[3]),
2432 getMDString(Record[4]), getMDString(Record[5]))),
2433 NextMetadataNo++);
Adrian Prantlab1243f2015-06-29 23:03:47 +00002434 break;
2435 }
2436
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002437 case bitc::METADATA_FILE: {
2438 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002439 return error("Invalid record");
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002440
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002441 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002442 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002443 GET_OR_DISTINCT(DIFile, (Context, getMDString(Record[1]),
2444 getMDString(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002445 NextMetadataNo++);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002446 break;
2447 }
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002448 case bitc::METADATA_COMPILE_UNIT: {
Amjad Abouda9bcf162015-12-10 12:56:35 +00002449 if (Record.size() < 14 || Record.size() > 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002450 return error("Invalid record");
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002451
Amjad Abouda9bcf162015-12-10 12:56:35 +00002452 // Ignore Record[0], which indicates whether this compile unit is
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00002453 // distinct. It's always distinct.
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002454 IsDistinct = true;
Adrian Prantl75819ae2016-04-15 15:57:41 +00002455 auto *CU = DICompileUnit::getDistinct(
2456 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
2457 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
2458 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2459 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
2460 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
2461 Record.size() <= 14 ? 0 : Record[14]);
2462
2463 MetadataList.assignValue(CU, NextMetadataNo++);
2464
2465 // Move the Upgrade the list of subprograms.
Duncan P. N. Exon Smith498b4972016-04-23 04:52:47 +00002466 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
Adrian Prantl75819ae2016-04-15 15:57:41 +00002467 CUSubprograms.push_back({CU, SPs});
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002468 break;
2469 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002470 case bitc::METADATA_SUBPROGRAM: {
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002471 if (Record.size() < 18 || Record.size() > 20)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002472 return error("Invalid record");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002473
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002474 IsDistinct =
Adrian Prantl85338cb2016-05-06 22:53:06 +00002475 (Record[0] & 1) || Record[8]; // All definitions should be distinct.
Adrian Prantl75819ae2016-04-15 15:57:41 +00002476 // Version 1 has a Function as Record[15].
2477 // Version 2 has removed Record[15].
2478 // Version 3 has the Unit as Record[15].
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002479 // Version 4 added thisAdjustment.
Adrian Prantl85338cb2016-05-06 22:53:06 +00002480 bool HasUnit = Record[0] >= 2;
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002481 if (HasUnit && Record.size() < 19)
Adrian Prantl85338cb2016-05-06 22:53:06 +00002482 return error("Invalid record");
Adrian Prantl75819ae2016-04-15 15:57:41 +00002483 Metadata *CUorFn = getMDOrNull(Record[15]);
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002484 unsigned Offset = Record.size() >= 19 ? 1 : 0;
Adrian Prantl85338cb2016-05-06 22:53:06 +00002485 bool HasFn = Offset && !HasUnit;
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002486 bool HasThisAdj = Record.size() >= 20;
Peter Collingbourned4bff302015-11-05 22:03:56 +00002487 DISubprogram *SP = GET_OR_DISTINCT(
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002488 DISubprogram, (Context,
2489 getDITypeRefOrNull(Record[1]), // scope
2490 getMDString(Record[2]), // name
2491 getMDString(Record[3]), // linkageName
2492 getMDOrNull(Record[4]), // file
2493 Record[5], // line
2494 getMDOrNull(Record[6]), // type
2495 Record[7], // isLocal
2496 Record[8], // isDefinition
2497 Record[9], // scopeLine
2498 getDITypeRefOrNull(Record[10]), // containingType
2499 Record[11], // virtuality
2500 Record[12], // virtualIndex
2501 HasThisAdj ? Record[19] : 0, // thisAdjustment
2502 Record[13], // flags
2503 Record[14], // isOptimized
2504 HasUnit ? CUorFn : nullptr, // unit
2505 getMDOrNull(Record[15 + Offset]), // templateParams
2506 getMDOrNull(Record[16 + Offset]), // declaration
2507 getMDOrNull(Record[17 + Offset]) // variables
2508 ));
Teresa Johnson61b406e2015-12-29 23:00:22 +00002509 MetadataList.assignValue(SP, NextMetadataNo++);
Peter Collingbourned4bff302015-11-05 22:03:56 +00002510
2511 // Upgrade sp->function mapping to function->sp mapping.
Adrian Prantl75819ae2016-04-15 15:57:41 +00002512 if (HasFn) {
Adrian Prantl85338cb2016-05-06 22:53:06 +00002513 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
Peter Collingbourned4bff302015-11-05 22:03:56 +00002514 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2515 if (F->isMaterializable())
2516 // Defer until materialized; unmaterialized functions may not have
2517 // metadata.
2518 FunctionsWithSPs[F] = SP;
2519 else if (!F->empty())
2520 F->setSubprogram(SP);
2521 }
2522 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002523 break;
2524 }
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002525 case bitc::METADATA_LEXICAL_BLOCK: {
2526 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002527 return error("Invalid record");
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002528
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002529 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002530 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002531 GET_OR_DISTINCT(DILexicalBlock,
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002532 (Context, getMDOrNull(Record[1]),
2533 getMDOrNull(Record[2]), Record[3], Record[4])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002534 NextMetadataNo++);
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002535 break;
2536 }
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002537 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2538 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002539 return error("Invalid record");
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002540
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002541 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002542 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002543 GET_OR_DISTINCT(DILexicalBlockFile,
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002544 (Context, getMDOrNull(Record[1]),
2545 getMDOrNull(Record[2]), Record[3])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002546 NextMetadataNo++);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002547 break;
2548 }
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002549 case bitc::METADATA_NAMESPACE: {
2550 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002551 return error("Invalid record");
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002552
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002553 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002554 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002555 GET_OR_DISTINCT(DINamespace, (Context, getMDOrNull(Record[1]),
2556 getMDOrNull(Record[2]),
2557 getMDString(Record[3]), Record[4])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002558 NextMetadataNo++);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002559 break;
2560 }
Amjad Abouda9bcf162015-12-10 12:56:35 +00002561 case bitc::METADATA_MACRO: {
2562 if (Record.size() != 5)
2563 return error("Invalid record");
2564
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002565 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002566 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002567 GET_OR_DISTINCT(DIMacro,
Amjad Abouda9bcf162015-12-10 12:56:35 +00002568 (Context, Record[1], Record[2],
2569 getMDString(Record[3]), getMDString(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002570 NextMetadataNo++);
Amjad Abouda9bcf162015-12-10 12:56:35 +00002571 break;
2572 }
2573 case bitc::METADATA_MACRO_FILE: {
2574 if (Record.size() != 5)
2575 return error("Invalid record");
2576
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002577 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002578 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002579 GET_OR_DISTINCT(DIMacroFile,
Amjad Abouda9bcf162015-12-10 12:56:35 +00002580 (Context, Record[1], Record[2],
2581 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002582 NextMetadataNo++);
Amjad Abouda9bcf162015-12-10 12:56:35 +00002583 break;
2584 }
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002585 case bitc::METADATA_TEMPLATE_TYPE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002586 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002587 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002588
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002589 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002590 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
Teresa Johnson61b406e2015-12-29 23:00:22 +00002591 (Context, getMDString(Record[1]),
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002592 getDITypeRefOrNull(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002593 NextMetadataNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002594 break;
2595 }
2596 case bitc::METADATA_TEMPLATE_VALUE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002597 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002598 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002599
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002600 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002601 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002602 GET_OR_DISTINCT(DITemplateValueParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002603 (Context, Record[1], getMDString(Record[2]),
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002604 getDITypeRefOrNull(Record[3]),
2605 getMDOrNull(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002606 NextMetadataNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002607 break;
2608 }
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002609 case bitc::METADATA_GLOBAL_VAR: {
2610 if (Record.size() != 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002611 return error("Invalid record");
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002612
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002613 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002614 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002615 GET_OR_DISTINCT(DIGlobalVariable,
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002616 (Context, getMDOrNull(Record[1]),
2617 getMDString(Record[2]), getMDString(Record[3]),
2618 getMDOrNull(Record[4]), Record[5],
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002619 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002620 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002621 NextMetadataNo++);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002622 break;
2623 }
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002624 case bitc::METADATA_LOCAL_VAR: {
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00002625 // 10th field is for the obseleted 'inlinedAt:' field.
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002626 if (Record.size() < 8 || Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002627 return error("Invalid record");
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002628
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002629 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2630 // DW_TAG_arg_variable.
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002631 IsDistinct = Record[0];
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002632 bool HasTag = Record.size() > 8;
Teresa Johnson61b406e2015-12-29 23:00:22 +00002633 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002634 GET_OR_DISTINCT(DILocalVariable,
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002635 (Context, getMDOrNull(Record[1 + HasTag]),
2636 getMDString(Record[2 + HasTag]),
2637 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002638 getDITypeRefOrNull(Record[5 + HasTag]),
2639 Record[6 + HasTag], Record[7 + HasTag])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002640 NextMetadataNo++);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002641 break;
2642 }
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002643 case bitc::METADATA_EXPRESSION: {
2644 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002645 return error("Invalid record");
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002646
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002647 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002648 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002649 GET_OR_DISTINCT(DIExpression,
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002650 (Context, makeArrayRef(Record).slice(1))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002651 NextMetadataNo++);
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002652 break;
2653 }
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002654 case bitc::METADATA_OBJC_PROPERTY: {
2655 if (Record.size() != 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002656 return error("Invalid record");
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002657
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002658 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002659 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002660 GET_OR_DISTINCT(DIObjCProperty,
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002661 (Context, getMDString(Record[1]),
2662 getMDOrNull(Record[2]), Record[3],
2663 getMDString(Record[4]), getMDString(Record[5]),
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002664 Record[6], getDITypeRefOrNull(Record[7]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002665 NextMetadataNo++);
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002666 break;
2667 }
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002668 case bitc::METADATA_IMPORTED_ENTITY: {
2669 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002670 return error("Invalid record");
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002671
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002672 IsDistinct = Record[0];
Teresa Johnson61b406e2015-12-29 23:00:22 +00002673 MetadataList.assignValue(
Duncan P. N. Exon Smith30ab4b42016-04-23 04:01:57 +00002674 GET_OR_DISTINCT(DIImportedEntity,
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002675 (Context, Record[1], getMDOrNull(Record[2]),
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00002676 getDITypeRefOrNull(Record[3]), Record[4],
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002677 getMDString(Record[5]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002678 NextMetadataNo++);
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002679 break;
2680 }
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002681 case bitc::METADATA_STRING_OLD: {
Eli Bendersky5d5e18d2014-06-25 15:41:00 +00002682 std::string String(Record.begin(), Record.end());
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00002683
2684 // Test for upgrading !llvm.loop.
2685 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2686
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002687 Metadata *MD = MDString::get(Context, String);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002688 MetadataList.assignValue(MD, NextMetadataNo++);
Devang Patel7428d8a2009-07-22 17:43:22 +00002689 break;
2690 }
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002691 case bitc::METADATA_STRINGS:
2692 if (std::error_code EC =
2693 parseMetadataStrings(Record, Blob, NextMetadataNo))
2694 return EC;
2695 break;
Peter Collingbourne21521892016-06-21 23:42:48 +00002696 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
2697 if (Record.size() % 2 == 0)
2698 return error("Invalid record");
2699 unsigned ValueID = Record[0];
2700 if (ValueID >= ValueList.size())
2701 return error("Invalid record");
2702 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
2703 parseGlobalObjectAttachment(*GO, ArrayRef<uint64_t>(Record).slice(1));
2704 break;
2705 }
Devang Patelaf206b82009-09-18 19:26:43 +00002706 case bitc::METADATA_KIND: {
Teresa Johnson12545072015-11-15 02:00:09 +00002707 // Support older bitcode files that had METADATA_KIND records in a
2708 // block with METADATA_BLOCK_ID.
2709 if (std::error_code EC = parseMetadataKindRecord(Record))
2710 return EC;
Devang Patelaf206b82009-09-18 19:26:43 +00002711 break;
2712 }
Devang Patel7428d8a2009-07-22 17:43:22 +00002713 }
2714 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002715#undef GET_OR_DISTINCT
Devang Patel7428d8a2009-07-22 17:43:22 +00002716}
2717
Teresa Johnson12545072015-11-15 02:00:09 +00002718/// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2719std::error_code BitcodeReader::parseMetadataKinds() {
2720 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2721 return error("Invalid record");
2722
2723 SmallVector<uint64_t, 64> Record;
2724
2725 // Read all the records.
2726 while (1) {
2727 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2728
2729 switch (Entry.Kind) {
2730 case BitstreamEntry::SubBlock: // Handled for us already.
2731 case BitstreamEntry::Error:
2732 return error("Malformed block");
2733 case BitstreamEntry::EndBlock:
2734 return std::error_code();
2735 case BitstreamEntry::Record:
2736 // The interesting case.
2737 break;
2738 }
2739
2740 // Read a record.
2741 Record.clear();
2742 unsigned Code = Stream.readRecord(Entry.ID, Record);
2743 switch (Code) {
2744 default: // Default behavior: ignore.
2745 break;
2746 case bitc::METADATA_KIND: {
2747 if (std::error_code EC = parseMetadataKindRecord(Record))
2748 return EC;
2749 break;
2750 }
2751 }
2752 }
2753}
2754
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002755/// Decode a signed value stored with the sign bit in the LSB for dense VBR
2756/// encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002757uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00002758 if ((V & 1) == 0)
2759 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002760 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00002761 return -(V >> 1);
2762 // There is no such thing as -0 with integers. "-0" really means MININT.
2763 return 1ULL << 63;
2764}
2765
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002766/// Resolve all of the initializers for global values and aliases that we can.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002767std::error_code BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00002768 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002769 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
2770 IndirectSymbolInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002771 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002772 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
David Majnemer7fddecc2015-06-17 20:52:32 +00002773 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002774
Chris Lattner44c17072007-04-26 02:46:40 +00002775 GlobalInitWorklist.swap(GlobalInits);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002776 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002777 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002778 FunctionPrologueWorklist.swap(FunctionPrologues);
David Majnemer7fddecc2015-06-17 20:52:32 +00002779 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
Chris Lattner44c17072007-04-26 02:46:40 +00002780
2781 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00002782 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002783 if (ValID >= ValueList.size()) {
2784 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00002785 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002786 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002787 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00002788 GlobalInitWorklist.back().first->setInitializer(C);
2789 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002790 return error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00002791 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002792 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002793 }
2794
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002795 while (!IndirectSymbolInitWorklist.empty()) {
2796 unsigned ValID = IndirectSymbolInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002797 if (ValID >= ValueList.size()) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002798 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002799 } else {
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002800 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2801 if (!C)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002802 return error("Expected a constant");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002803 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2804 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002805 return error("Alias and aliasee types don't match");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002806 GIS->setIndirectSymbol(C);
Chris Lattner44c17072007-04-26 02:46:40 +00002807 }
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002808 IndirectSymbolInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002809 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002810
2811 while (!FunctionPrefixWorklist.empty()) {
2812 unsigned ValID = FunctionPrefixWorklist.back().second;
2813 if (ValID >= ValueList.size()) {
2814 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2815 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002816 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002817 FunctionPrefixWorklist.back().first->setPrefixData(C);
2818 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002819 return error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002820 }
2821 FunctionPrefixWorklist.pop_back();
2822 }
2823
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002824 while (!FunctionPrologueWorklist.empty()) {
2825 unsigned ValID = FunctionPrologueWorklist.back().second;
2826 if (ValID >= ValueList.size()) {
2827 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2828 } else {
2829 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2830 FunctionPrologueWorklist.back().first->setPrologueData(C);
2831 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002832 return error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002833 }
2834 FunctionPrologueWorklist.pop_back();
2835 }
2836
David Majnemer7fddecc2015-06-17 20:52:32 +00002837 while (!FunctionPersonalityFnWorklist.empty()) {
2838 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2839 if (ValID >= ValueList.size()) {
2840 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2841 } else {
2842 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2843 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2844 else
2845 return error("Expected a constant");
2846 }
2847 FunctionPersonalityFnWorklist.pop_back();
2848 }
2849
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002850 return std::error_code();
Chris Lattner44c17072007-04-26 02:46:40 +00002851}
2852
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002853static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002854 SmallVector<uint64_t, 8> Words(Vals.size());
2855 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00002856 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002857
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002858 return APInt(TypeBits, Words);
2859}
2860
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002861std::error_code BitcodeReader::parseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002862 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002863 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002864
2865 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002866
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002867 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00002868 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00002869 unsigned NextCstNo = ValueList.size();
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002870 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002871 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002872
Chris Lattner27d38752013-01-20 02:13:19 +00002873 switch (Entry.Kind) {
2874 case BitstreamEntry::SubBlock: // Handled for us already.
2875 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002876 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002877 case BitstreamEntry::EndBlock:
2878 if (NextCstNo != ValueList.size())
George Burgess IV1030d682016-01-20 22:15:23 +00002879 return error("Invalid constant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00002880
Chris Lattner27d38752013-01-20 02:13:19 +00002881 // Once all the constants have been read, go through and resolve forward
2882 // references.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002883 ValueList.resolveConstantForwardRefs();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002884 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002885 case BitstreamEntry::Record:
2886 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00002887 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002888 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002889
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002890 // Read a record.
2891 Record.clear();
Filipe Cabecinhas2849b482016-06-05 18:43:17 +00002892 Type *VoidType = Type::getVoidTy(Context);
Craig Topper2617dcc2014-04-15 06:32:26 +00002893 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002894 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002895 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002896 default: // Default behavior: unknown constant
2897 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00002898 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002899 break;
2900 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2901 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002902 return error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00002903 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002904 return error("Invalid record");
Filipe Cabecinhas2849b482016-06-05 18:43:17 +00002905 if (TypeList[Record[0]] == VoidType)
2906 return error("Invalid constant type");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002907 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00002908 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002909 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00002910 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002911 break;
2912 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002913 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002914 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002915 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00002916 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00002917 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002918 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002919 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002920
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002921 APInt VInt =
2922 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002923 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002924
Chris Lattner08feb1e2007-04-24 04:04:35 +00002925 break;
2926 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002927 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00002928 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002929 return error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00002930 if (CurTy->isHalfTy())
Tim Northover29178a32013-01-22 09:46:31 +00002931 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2932 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00002933 else if (CurTy->isFloatTy())
Tim Northover29178a32013-01-22 09:46:31 +00002934 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2935 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002936 else if (CurTy->isDoubleTy())
Tim Northover29178a32013-01-22 09:46:31 +00002937 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2938 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002939 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00002940 // Bits are not stored the same way as a normal i80 APInt, compensate.
2941 uint64_t Rearrange[2];
2942 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2943 Rearrange[1] = Record[0] >> 48;
Tim Northover29178a32013-01-22 09:46:31 +00002944 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2945 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002946 } else if (CurTy->isFP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002947 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2948 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002949 else if (CurTy->isPPC_FP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002950 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2951 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002952 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00002953 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002954 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00002955 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002956
Chris Lattnere14cb882007-05-04 19:11:41 +00002957 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2958 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002959 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002960
Chris Lattnere14cb882007-05-04 19:11:41 +00002961 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00002962 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002963
Chris Lattner229907c2011-07-18 04:54:35 +00002964 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00002965 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002966 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00002967 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00002968 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002969 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2970 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002971 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002972 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00002973 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002974 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2975 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002976 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002977 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00002978 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00002979 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002980 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00002981 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002982 break;
2983 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002984 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00002985 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2986 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002987 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002988
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002989 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002990 V = ConstantDataArray::getString(Context, Elts,
2991 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00002992 break;
2993 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002994 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2995 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002996 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002997
Chris Lattner372dd1e2012-01-30 00:51:16 +00002998 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
Chris Lattner372dd1e2012-01-30 00:51:16 +00002999 if (EltTy->isIntegerTy(8)) {
3000 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
3001 if (isa<VectorType>(CurTy))
3002 V = ConstantDataVector::get(Context, Elts);
3003 else
3004 V = ConstantDataArray::get(Context, Elts);
3005 } else if (EltTy->isIntegerTy(16)) {
3006 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3007 if (isa<VectorType>(CurTy))
3008 V = ConstantDataVector::get(Context, Elts);
3009 else
3010 V = ConstantDataArray::get(Context, Elts);
3011 } else if (EltTy->isIntegerTy(32)) {
3012 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3013 if (isa<VectorType>(CurTy))
3014 V = ConstantDataVector::get(Context, Elts);
3015 else
3016 V = ConstantDataArray::get(Context, Elts);
3017 } else if (EltTy->isIntegerTy(64)) {
3018 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3019 if (isa<VectorType>(CurTy))
3020 V = ConstantDataVector::get(Context, Elts);
3021 else
3022 V = ConstantDataArray::get(Context, Elts);
Justin Bognera43eacb2016-01-06 22:31:32 +00003023 } else if (EltTy->isHalfTy()) {
3024 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3025 if (isa<VectorType>(CurTy))
3026 V = ConstantDataVector::getFP(Context, Elts);
3027 else
3028 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00003029 } else if (EltTy->isFloatTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00003030 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00003031 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00003032 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00003033 else
Justin Bognera43eacb2016-01-06 22:31:32 +00003034 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00003035 } else if (EltTy->isDoubleTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00003036 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00003037 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00003038 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00003039 else
Justin Bognera43eacb2016-01-06 22:31:32 +00003040 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00003041 } else {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003042 return error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00003043 }
3044 break;
3045 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003046 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003047 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003048 return error("Invalid record");
3049 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00003050 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00003051 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00003052 } else {
3053 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
3054 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00003055 unsigned Flags = 0;
3056 if (Record.size() >= 4) {
3057 if (Opc == Instruction::Add ||
3058 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003059 Opc == Instruction::Mul ||
3060 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00003061 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3062 Flags |= OverflowingBinaryOperator::NoSignedWrap;
3063 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3064 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00003065 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003066 Opc == Instruction::UDiv ||
3067 Opc == Instruction::LShr ||
3068 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00003069 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00003070 Flags |= SDivOperator::IsExact;
3071 }
3072 }
3073 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00003074 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003075 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003076 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003077 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003078 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003079 return error("Invalid record");
3080 int Opc = getDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00003081 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00003082 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00003083 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00003084 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003085 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003086 return error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00003087 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003088 V = UpgradeBitCastExpr(Opc, Op, CurTy);
3089 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00003090 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003091 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003092 }
Dan Gohman1639c392009-07-27 21:53:46 +00003093 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003094 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
David Blaikieb9263572015-03-13 21:03:36 +00003095 unsigned OpNum = 0;
3096 Type *PointeeType = nullptr;
3097 if (Record.size() % 2)
3098 PointeeType = getTypeByID(Record[OpNum++]);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003099 SmallVector<Constant*, 16> Elts;
David Blaikieb9263572015-03-13 21:03:36 +00003100 while (OpNum != Record.size()) {
3101 Type *ElTy = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003102 if (!ElTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003103 return error("Invalid record");
David Blaikieb9263572015-03-13 21:03:36 +00003104 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003105 }
David Blaikieb9263572015-03-13 21:03:36 +00003106
David Blaikieb9263572015-03-13 21:03:36 +00003107 if (PointeeType &&
David Blaikie4a2e73b2015-04-02 18:55:32 +00003108 PointeeType !=
3109 cast<SequentialType>(Elts[0]->getType()->getScalarType())
3110 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003111 return error("Explicit gep operator type does not match pointee type "
David Blaikie12cf5d702015-03-16 22:03:50 +00003112 "of pointer operand");
David Blaikie4a2e73b2015-04-02 18:55:32 +00003113
Filipe Cabecinhasfc2a3c92016-06-05 18:43:26 +00003114 if (Elts.size() < 1)
3115 return error("Invalid gep with no operands");
3116
David Blaikie4a2e73b2015-04-02 18:55:32 +00003117 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3118 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
3119 BitCode ==
3120 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattner890683d2007-04-24 18:15:21 +00003121 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003122 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00003123 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003124 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003125 return error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00003126
3127 Type *SelectorTy = Type::getInt1Ty(Context);
3128
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00003129 // The selector might be an i1 or an <n x i1>
3130 // Get the type from the ValueList before getting a forward ref.
Joe Abbey1a6e7702013-09-12 22:02:31 +00003131 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00003132 if (Value *V = ValueList[Record[0]])
3133 if (SelectorTy != V->getType())
3134 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
Joe Abbey1a6e7702013-09-12 22:02:31 +00003135
3136 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
3137 SelectorTy),
3138 ValueList.getConstantFwdRef(Record[1],CurTy),
3139 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003140 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00003141 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003142 case bitc::CST_CODE_CE_EXTRACTELT
3143 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003144 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003145 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003146 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003147 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00003148 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003149 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003150 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003151 Constant *Op1 = nullptr;
3152 if (Record.size() == 4) {
3153 Type *IdxTy = getTypeByID(Record[2]);
3154 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003155 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003156 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
3157 } else // TODO: Remove with llvm 4.0
3158 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
3159 if (!Op1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003160 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00003161 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003162 break;
3163 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003164 case bitc::CST_CODE_CE_INSERTELT
3165 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00003166 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00003167 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003168 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003169 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
3170 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
3171 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003172 Constant *Op2 = nullptr;
3173 if (Record.size() == 4) {
3174 Type *IdxTy = getTypeByID(Record[2]);
3175 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003176 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003177 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
3178 } else // TODO: Remove with llvm 4.0
3179 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
3180 if (!Op2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003181 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00003182 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003183 break;
3184 }
3185 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00003186 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00003187 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003188 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003189 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
3190 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00003191 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00003192 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003193 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00003194 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003195 break;
3196 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00003197 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00003198 VectorType *RTy = dyn_cast<VectorType>(CurTy);
3199 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00003200 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00003201 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003202 return error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00003203 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3204 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00003205 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00003206 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00003207 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00003208 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00003209 break;
3210 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003211 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00003212 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003213 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003214 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003215 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003216 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003217 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
3218 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
3219
Duncan Sands9dff9be2010-02-15 16:12:20 +00003220 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00003221 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00003222 else
Owen Anderson487375e2009-07-29 18:55:55 +00003223 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00003224 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00003225 }
Chad Rosierd8c76102012-09-05 19:00:49 +00003226 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00003227 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003228 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003229 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003230 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003231 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00003232 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00003233 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003234 unsigned AsmStrSize = Record[1];
3235 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003236 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003237 unsigned ConstStrSize = Record[2+AsmStrSize];
3238 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003239 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003240
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003241 for (unsigned i = 0; i != AsmStrSize; ++i)
3242 AsmStr += (char)Record[2+i];
3243 for (unsigned i = 0; i != ConstStrSize; ++i)
3244 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00003245 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003246 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00003247 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00003248 break;
3249 }
Chad Rosierd8c76102012-09-05 19:00:49 +00003250 // This version adds support for the asm dialect keywords (e.g.,
3251 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003252 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003253 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003254 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003255 std::string AsmStr, ConstrStr;
3256 bool HasSideEffects = Record[0] & 1;
3257 bool IsAlignStack = (Record[0] >> 1) & 1;
3258 unsigned AsmDialect = Record[0] >> 2;
3259 unsigned AsmStrSize = Record[1];
3260 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003261 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003262 unsigned ConstStrSize = Record[2+AsmStrSize];
3263 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003264 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003265
3266 for (unsigned i = 0; i != AsmStrSize; ++i)
3267 AsmStr += (char)Record[2+i];
3268 for (unsigned i = 0; i != ConstStrSize; ++i)
3269 ConstrStr += (char)Record[3+AsmStrSize+i];
3270 PointerType *PTy = cast<PointerType>(CurTy);
3271 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
3272 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00003273 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00003274 break;
3275 }
Chris Lattner5956dc82009-10-28 05:53:48 +00003276 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00003277 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003278 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003279 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003280 if (!FnTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003281 return error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00003282 Function *Fn =
3283 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00003284 if (!Fn)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003285 return error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003286
3287 // If the function is already parsed we can insert the block address right
3288 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003289 BasicBlock *BB;
3290 unsigned BBID = Record[2];
3291 if (!BBID)
3292 // Invalid reference to entry block.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003293 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003294 if (!Fn->empty()) {
3295 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003296 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003297 if (BBI == BBE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003298 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003299 ++BBI;
3300 }
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00003301 BB = &*BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003302 } else {
3303 // Otherwise insert a placeholder and remember it so it can be inserted
3304 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00003305 auto &FwdBBs = BasicBlockFwdRefs[Fn];
3306 if (FwdBBs.empty())
3307 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003308 if (FwdBBs.size() < BBID + 1)
3309 FwdBBs.resize(BBID + 1);
3310 if (!FwdBBs[BBID])
3311 FwdBBs[BBID] = BasicBlock::Create(Context);
3312 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003313 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003314 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00003315 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003316 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003317 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003318
David Majnemer8a1c45d2015-12-12 05:38:55 +00003319 ValueList.assignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00003320 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003321 }
3322}
Chris Lattner1314b992007-04-22 06:23:29 +00003323
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003324std::error_code BitcodeReader::parseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00003325 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003326 return error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00003327
Chad Rosierca2567b2011-12-07 21:44:12 +00003328 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003329 SmallVector<uint64_t, 64> Record;
Chad Rosierca2567b2011-12-07 21:44:12 +00003330 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00003331 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003332
Chris Lattner27d38752013-01-20 02:13:19 +00003333 switch (Entry.Kind) {
3334 case BitstreamEntry::SubBlock: // Handled for us already.
3335 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003336 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003337 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003338 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003339 case BitstreamEntry::Record:
3340 // The interesting case.
3341 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003342 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003343
Chad Rosierca2567b2011-12-07 21:44:12 +00003344 // Read a use list record.
3345 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003346 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00003347 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00003348 default: // Default behavior: unknown type.
3349 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003350 case bitc::USELIST_CODE_BB:
3351 IsBB = true;
3352 // fallthrough
3353 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00003354 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003355 if (RecordLength < 3)
3356 // Records should have at least an ID and two indexes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003357 return error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003358 unsigned ID = Record.back();
3359 Record.pop_back();
3360
3361 Value *V;
3362 if (IsBB) {
3363 assert(ID < FunctionBBs.size() && "Basic block not found");
3364 V = FunctionBBs[ID];
3365 } else
3366 V = ValueList[ID];
3367 unsigned NumUses = 0;
3368 SmallDenseMap<const Use *, unsigned, 16> Order;
Rafael Espindola257a3532016-01-15 19:00:20 +00003369 for (const Use &U : V->materialized_uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00003370 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003371 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00003372 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003373 }
3374 if (Order.size() != Record.size() || NumUses > Record.size())
3375 // Mismatches can happen if the functions are being materialized lazily
3376 // (out-of-order), or a value has been upgraded.
3377 break;
3378
3379 V->sortUseList([&](const Use &L, const Use &R) {
3380 return Order.lookup(&L) < Order.lookup(&R);
3381 });
Chad Rosierca2567b2011-12-07 21:44:12 +00003382 break;
3383 }
3384 }
3385 }
3386}
3387
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003388/// When we see the block for metadata, remember where it is and then skip it.
3389/// This lets us lazily deserialize the metadata.
3390std::error_code BitcodeReader::rememberAndSkipMetadata() {
3391 // Save the current stream state.
3392 uint64_t CurBit = Stream.GetCurrentBitNo();
3393 DeferredMetadataInfo.push_back(CurBit);
3394
3395 // Skip over the block for now.
3396 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003397 return error("Invalid record");
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003398 return std::error_code();
3399}
3400
3401std::error_code BitcodeReader::materializeMetadata() {
3402 for (uint64_t BitPos : DeferredMetadataInfo) {
3403 // Move the bit stream to the saved position.
3404 Stream.JumpToBit(BitPos);
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003405 if (std::error_code EC = parseMetadata(true))
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003406 return EC;
3407 }
3408 DeferredMetadataInfo.clear();
3409 return std::error_code();
3410}
3411
Rafael Espindola468b8682015-04-01 14:44:59 +00003412void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00003413
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003414/// When we see the block for a function body, remember where it is and then
3415/// skip it. This lets us lazily deserialize the functions.
3416std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003417 // Get the function we are talking about.
3418 if (FunctionsWithBodies.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003419 return error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003420
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003421 Function *Fn = FunctionsWithBodies.back();
3422 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003423
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003424 // Save the current stream state.
3425 uint64_t CurBit = Stream.GetCurrentBitNo();
Teresa Johnson1493ad92015-10-10 14:18:36 +00003426 assert(
3427 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3428 "Mismatch between VST and scanned function offsets");
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003429 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003430
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003431 // Skip over the function block for now.
3432 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003433 return error("Invalid record");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003434 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003435}
3436
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003437std::error_code BitcodeReader::globalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003438 // Patch the initializers for globals and aliases up.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003439 resolveGlobalAndIndirectSymbolInits();
3440 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003441 return error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003442
3443 // Look for intrinsic functions which need to be upgraded at some point
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003444 for (Function &F : *TheModule) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003445 Function *NewFn;
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003446 if (UpgradeIntrinsicFunction(&F, NewFn))
Rafael Espindola4e721212015-07-02 16:22:40 +00003447 UpgradedIntrinsics[&F] = NewFn;
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00003448 else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
3449 // Some types could be renamed during loading if several modules are
3450 // loaded in the same LLVMContext (LTO scenario). In this case we should
3451 // remangle intrinsics names as well.
3452 RemangledIntrinsics[&F] = Remangled.getValue();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003453 }
3454
3455 // Look for global variables which need to be renamed.
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003456 for (GlobalVariable &GV : TheModule->globals())
3457 UpgradeGlobalVariable(&GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00003458
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003459 // Force deallocation of memory for these vectors to favor the client that
3460 // want lazy deserialization.
3461 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003462 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap(
3463 IndirectSymbolInits);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003464 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003465}
3466
Teresa Johnson1493ad92015-10-10 14:18:36 +00003467/// Support for lazy parsing of function bodies. This is required if we
3468/// either have an old bitcode file without a VST forward declaration record,
3469/// or if we have an anonymous function being materialized, since anonymous
3470/// functions do not have a name and are therefore not in the VST.
3471std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3472 Stream.JumpToBit(NextUnreadBit);
3473
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003474 if (Stream.AtEndOfStream())
3475 return error("Could not find function in stream");
Teresa Johnson1493ad92015-10-10 14:18:36 +00003476
Filipe Cabecinhas7aae2f22015-11-03 13:48:26 +00003477 if (!SeenFirstFunctionBody)
3478 return error("Trying to materialize functions before seeing function blocks");
3479
Teresa Johnson1493ad92015-10-10 14:18:36 +00003480 // An old bitcode file with the symbol table at the end would have
3481 // finished the parse greedily.
3482 assert(SeenValueSymbolTable);
3483
3484 SmallVector<uint64_t, 64> Record;
3485
3486 while (1) {
3487 BitstreamEntry Entry = Stream.advance();
3488 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003489 default:
3490 return error("Expect SubBlock");
3491 case BitstreamEntry::SubBlock:
3492 switch (Entry.ID) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003493 default:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003494 return error("Expect function block");
3495 case bitc::FUNCTION_BLOCK_ID:
3496 if (std::error_code EC = rememberAndSkipFunctionBody())
3497 return EC;
3498 NextUnreadBit = Stream.GetCurrentBitNo();
3499 return std::error_code();
3500 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00003501 }
3502 }
3503}
3504
Mehdi Amini5d303282015-10-26 18:37:00 +00003505std::error_code BitcodeReader::parseBitcodeVersion() {
3506 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3507 return error("Invalid record");
3508
3509 // Read all the records.
3510 SmallVector<uint64_t, 64> Record;
3511 while (1) {
3512 BitstreamEntry Entry = Stream.advance();
3513
3514 switch (Entry.Kind) {
3515 default:
3516 case BitstreamEntry::Error:
3517 return error("Malformed block");
3518 case BitstreamEntry::EndBlock:
3519 return std::error_code();
3520 case BitstreamEntry::Record:
3521 // The interesting case.
3522 break;
3523 }
3524
3525 // Read a record.
3526 Record.clear();
3527 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3528 switch (BitCode) {
3529 default: // Default behavior: reject
3530 return error("Invalid value");
3531 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3532 // N]
3533 convertToString(Record, 0, ProducerIdentification);
3534 break;
3535 }
3536 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3537 unsigned epoch = (unsigned)Record[0];
3538 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
Oleksiy Vyalov6c2403f2015-10-26 22:37:36 +00003539 return error(
3540 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3541 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
Mehdi Amini5d303282015-10-26 18:37:00 +00003542 }
3543 }
3544 }
3545 }
3546}
3547
Teresa Johnson1493ad92015-10-10 14:18:36 +00003548std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003549 bool ShouldLazyLoadMetadata) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003550 if (ResumeBit)
3551 Stream.JumpToBit(ResumeBit);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003552 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003553 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003554
Chris Lattner1314b992007-04-22 06:23:29 +00003555 SmallVector<uint64_t, 64> Record;
3556 std::vector<std::string> SectionTable;
Gordon Henriksend930f912008-08-17 18:44:35 +00003557 std::vector<std::string> GCTable;
Chris Lattner1314b992007-04-22 06:23:29 +00003558
3559 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00003560 while (1) {
3561 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003562
Chris Lattner27d38752013-01-20 02:13:19 +00003563 switch (Entry.Kind) {
3564 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003565 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003566 case BitstreamEntry::EndBlock:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003567 return globalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00003568
Chris Lattner27d38752013-01-20 02:13:19 +00003569 case BitstreamEntry::SubBlock:
3570 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00003571 default: // Skip unknown content.
3572 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003573 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003574 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003575 case bitc::BLOCKINFO_BLOCK_ID:
3576 if (Stream.ReadBlockInfoBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003577 return error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003578 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003579 case bitc::PARAMATTR_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003580 if (std::error_code EC = parseAttributeBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003581 return EC;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003582 break;
Bill Wendlingba629332013-02-10 23:24:25 +00003583 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003584 if (std::error_code EC = parseAttributeGroupBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003585 return EC;
Bill Wendlingba629332013-02-10 23:24:25 +00003586 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003587 case bitc::TYPE_BLOCK_ID_NEW:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003588 if (std::error_code EC = parseTypeTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003589 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00003590 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00003591 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnsonff642b92015-09-17 20:12:00 +00003592 if (!SeenValueSymbolTable) {
3593 // Either this is an old form VST without function index and an
3594 // associated VST forward declaration record (which would have caused
3595 // the VST to be jumped to and parsed before it was encountered
3596 // normally in the stream), or there were no function blocks to
3597 // trigger an earlier parsing of the VST.
3598 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3599 if (std::error_code EC = parseValueSymbolTable())
3600 return EC;
3601 SeenValueSymbolTable = true;
3602 } else {
3603 // We must have had a VST forward declaration record, which caused
3604 // the parser to jump to and parse the VST earlier.
3605 assert(VSTOffset > 0);
3606 if (Stream.SkipBlock())
3607 return error("Invalid record");
3608 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00003609 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003610 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003611 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003612 return EC;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003613 if (std::error_code EC = resolveGlobalAndIndirectSymbolInits())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003614 return EC;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003615 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00003616 case bitc::METADATA_BLOCK_ID:
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003617 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3618 if (std::error_code EC = rememberAndSkipMetadata())
3619 return EC;
3620 break;
3621 }
3622 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003623 if (std::error_code EC = parseMetadata(true))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003624 return EC;
Devang Patel7428d8a2009-07-22 17:43:22 +00003625 break;
Teresa Johnson12545072015-11-15 02:00:09 +00003626 case bitc::METADATA_KIND_BLOCK_ID:
3627 if (std::error_code EC = parseMetadataKinds())
3628 return EC;
3629 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003630 case bitc::FUNCTION_BLOCK_ID:
3631 // If this is the first function body we've seen, reverse the
3632 // FunctionsWithBodies list.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003633 if (!SeenFirstFunctionBody) {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003634 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003635 if (std::error_code EC = globalCleanup())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003636 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003637 SeenFirstFunctionBody = true;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003638 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003639
Teresa Johnsonff642b92015-09-17 20:12:00 +00003640 if (VSTOffset > 0) {
3641 // If we have a VST forward declaration record, make sure we
3642 // parse the VST now if we haven't already. It is needed to
3643 // set up the DeferredFunctionInfo vector for lazy reading.
3644 if (!SeenValueSymbolTable) {
3645 if (std::error_code EC =
3646 BitcodeReader::parseValueSymbolTable(VSTOffset))
3647 return EC;
3648 SeenValueSymbolTable = true;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003649 // Fall through so that we record the NextUnreadBit below.
3650 // This is necessary in case we have an anonymous function that
3651 // is later materialized. Since it will not have a VST entry we
3652 // need to fall back to the lazy parse to find its offset.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003653 } else {
3654 // If we have a VST forward declaration record, but have already
3655 // parsed the VST (just above, when the first function body was
3656 // encountered here), then we are resuming the parse after
Teresa Johnson1493ad92015-10-10 14:18:36 +00003657 // materializing functions. The ResumeBit points to the
3658 // start of the last function block recorded in the
3659 // DeferredFunctionInfo map. Skip it.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003660 if (Stream.SkipBlock())
3661 return error("Invalid record");
3662 continue;
3663 }
3664 }
3665
3666 // Support older bitcode files that did not have the function
Teresa Johnson1493ad92015-10-10 14:18:36 +00003667 // index in the VST, nor a VST forward declaration record, as
3668 // well as anonymous functions that do not have VST entries.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003669 // Build the DeferredFunctionInfo vector on the fly.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003670 if (std::error_code EC = rememberAndSkipFunctionBody())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003671 return EC;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003672
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003673 // Suspend parsing when we reach the function bodies. Subsequent
3674 // materialization calls will resume it when necessary. If the bitcode
3675 // file is old, the symbol table will be at the end instead and will not
3676 // have been seen yet. In this case, just finish the parse now.
3677 if (SeenValueSymbolTable) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003678 NextUnreadBit = Stream.GetCurrentBitNo();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003679 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003680 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003681 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003682 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003683 if (std::error_code EC = parseUseLists())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003684 return EC;
Chad Rosierca2567b2011-12-07 21:44:12 +00003685 break;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003686 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3687 if (std::error_code EC = parseOperandBundleTags())
3688 return EC;
3689 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003690 }
3691 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003692
Chris Lattner27d38752013-01-20 02:13:19 +00003693 case BitstreamEntry::Record:
3694 // The interesting case.
3695 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003696 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003697
Chris Lattner1314b992007-04-22 06:23:29 +00003698 // Read a record.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003699 auto BitCode = Stream.readRecord(Entry.ID, Record);
3700 switch (BitCode) {
Chris Lattner1314b992007-04-22 06:23:29 +00003701 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungafaced02012-10-11 20:20:40 +00003702 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattner1314b992007-04-22 06:23:29 +00003703 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003704 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00003705 // Only version #0 and #1 are supported so far.
3706 unsigned module_version = Record[0];
3707 switch (module_version) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003708 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003709 return error("Invalid value");
Jan Wen Voungafaced02012-10-11 20:20:40 +00003710 case 0:
3711 UseRelativeIDs = false;
3712 break;
3713 case 1:
3714 UseRelativeIDs = true;
3715 break;
3716 }
Chris Lattner1314b992007-04-22 06:23:29 +00003717 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00003718 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003719 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003720 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003721 if (convertToString(Record, 0, S))
3722 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003723 TheModule->setTargetTriple(S);
3724 break;
3725 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003726 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003727 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003728 if (convertToString(Record, 0, S))
3729 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003730 TheModule->setDataLayout(S);
3731 break;
3732 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003733 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003734 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003735 if (convertToString(Record, 0, S))
3736 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003737 TheModule->setModuleInlineAsm(S);
3738 break;
3739 }
Bill Wendling706d3d62012-11-28 08:41:48 +00003740 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3741 // FIXME: Remove in 4.0.
3742 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003743 if (convertToString(Record, 0, S))
3744 return error("Invalid record");
Bill Wendling706d3d62012-11-28 08:41:48 +00003745 // Ignore value.
3746 break;
3747 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003748 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003749 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003750 if (convertToString(Record, 0, S))
3751 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003752 SectionTable.push_back(S);
3753 break;
3754 }
Gordon Henriksend930f912008-08-17 18:44:35 +00003755 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00003756 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003757 if (convertToString(Record, 0, S))
3758 return error("Invalid record");
Gordon Henriksend930f912008-08-17 18:44:35 +00003759 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00003760 break;
3761 }
David Majnemerdad0a642014-06-27 18:19:56 +00003762 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3763 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003764 return error("Invalid record");
David Majnemerdad0a642014-06-27 18:19:56 +00003765 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3766 unsigned ComdatNameSize = Record[1];
3767 std::string ComdatName;
3768 ComdatName.reserve(ComdatNameSize);
3769 for (unsigned i = 0; i != ComdatNameSize; ++i)
3770 ComdatName += (char)Record[2 + i];
3771 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3772 C->setSelectionKind(SK);
3773 ComdatList.push_back(C);
3774 break;
3775 }
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003776 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00003777 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00003778 // unnamed_addr, externally_initialized, dllstorageclass,
3779 // comdat]
Chris Lattner1314b992007-04-22 06:23:29 +00003780 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner4b00d922007-04-23 16:04:05 +00003781 if (Record.size() < 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003782 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003783 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003784 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003785 return error("Invalid record");
David Blaikie1a848da2015-04-27 19:58:56 +00003786 bool isConstant = Record[1] & 1;
3787 bool explicitType = Record[1] & 2;
3788 unsigned AddressSpace;
3789 if (explicitType) {
3790 AddressSpace = Record[1] >> 2;
3791 } else {
3792 if (!Ty->isPointerTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003793 return error("Invalid type for value");
David Blaikie1a848da2015-04-27 19:58:56 +00003794 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3795 Ty = cast<PointerType>(Ty)->getElementType();
3796 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003797
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003798 uint64_t RawLinkage = Record[3];
3799 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
JF Bastien30bf96b2015-02-22 19:32:03 +00003800 unsigned Alignment;
3801 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3802 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00003803 std::string Section;
3804 if (Record[5]) {
3805 if (Record[5]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003806 return error("Invalid ID");
Chris Lattner1314b992007-04-22 06:23:29 +00003807 Section = SectionTable[Record[5]-1];
3808 }
Chris Lattner4b00d922007-04-23 16:04:05 +00003809 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003810 // Local linkage must have default visibility.
3811 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3812 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003813 Visibility = getDecodedVisibility(Record[6]);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00003814
3815 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner53862f72007-05-06 19:27:46 +00003816 if (Record.size() > 7)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003817 TLM = getDecodedThreadLocalMode(Record[7]);
Chris Lattner1314b992007-04-22 06:23:29 +00003818
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003819 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola45e6c192011-01-08 16:42:36 +00003820 if (Record.size() > 8)
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003821 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003822
Michael Gottesman27e7ef32013-02-05 05:57:38 +00003823 bool ExternallyInitialized = false;
3824 if (Record.size() > 9)
3825 ExternallyInitialized = Record[9];
3826
Chris Lattner1314b992007-04-22 06:23:29 +00003827 GlobalVariable *NewGV =
Craig Topper2617dcc2014-04-15 06:32:26 +00003828 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
Michael Gottesman27e7ef32013-02-05 05:57:38 +00003829 TLM, AddressSpace, ExternallyInitialized);
Chris Lattner1314b992007-04-22 06:23:29 +00003830 NewGV->setAlignment(Alignment);
3831 if (!Section.empty())
3832 NewGV->setSection(Section);
3833 NewGV->setVisibility(Visibility);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003834 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003835
Nico Rieck7157bb72014-01-14 15:22:47 +00003836 if (Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003837 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003838 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003839 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00003840
Chris Lattnerccaa4482007-04-23 21:26:05 +00003841 ValueList.push_back(NewGV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003842
Chris Lattner47d131b2007-04-24 00:18:21 +00003843 // Remember which value to use for the global initializer.
3844 if (unsigned InitID = Record[2])
3845 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
David Majnemerdad0a642014-06-27 18:19:56 +00003846
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003847 if (Record.size() > 11) {
David Majnemerdad0a642014-06-27 18:19:56 +00003848 if (unsigned ComdatID = Record[11]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00003849 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003850 return error("Invalid global variable comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00003851 NewGV->setComdat(ComdatList[ComdatID - 1]);
3852 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003853 } else if (hasImplicitComdat(RawLinkage)) {
3854 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3855 }
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003856
Chris Lattner1314b992007-04-22 06:23:29 +00003857 break;
3858 }
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003859 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Nico Rieck7157bb72014-01-14 15:22:47 +00003860 // alignment, section, visibility, gc, unnamed_addr,
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003861 // prologuedata, dllstorageclass, comdat, prefixdata]
Chris Lattner1314b992007-04-22 06:23:29 +00003862 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003863 if (Record.size() < 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003864 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003865 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003866 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003867 return error("Invalid record");
David Blaikie561a1572015-04-17 16:28:26 +00003868 if (auto *PTy = dyn_cast<PointerType>(Ty))
3869 Ty = PTy->getElementType();
3870 auto *FTy = dyn_cast<FunctionType>(Ty);
Chris Lattner1314b992007-04-22 06:23:29 +00003871 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003872 return error("Invalid type for value");
Vedant Kumarad6d6e72015-10-27 21:17:06 +00003873 auto CC = static_cast<CallingConv::ID>(Record[1]);
3874 if (CC & ~CallingConv::MaxID)
3875 return error("Invalid calling convention ID");
Chris Lattner1314b992007-04-22 06:23:29 +00003876
Gabor Greife9ecc682008-04-06 20:25:17 +00003877 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3878 "", TheModule);
Chris Lattner1314b992007-04-22 06:23:29 +00003879
Vedant Kumarad6d6e72015-10-27 21:17:06 +00003880 Func->setCallingConv(CC);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003881 bool isProto = Record[2];
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003882 uint64_t RawLinkage = Record[3];
3883 Func->setLinkage(getDecodedLinkage(RawLinkage));
Devang Patel4c758ea2008-09-25 21:00:45 +00003884 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003885
JF Bastien30bf96b2015-02-22 19:32:03 +00003886 unsigned Alignment;
3887 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3888 return EC;
3889 Func->setAlignment(Alignment);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003890 if (Record[6]) {
3891 if (Record[6]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003892 return error("Invalid ID");
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003893 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattner1314b992007-04-22 06:23:29 +00003894 }
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003895 // Local linkage must have default visibility.
3896 if (!Func->hasLocalLinkage())
3897 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003898 Func->setVisibility(getDecodedVisibility(Record[7]));
Gordon Henriksen71183b62007-12-10 03:18:06 +00003899 if (Record.size() > 8 && Record[8]) {
Filipe Cabecinhasf8a16a92015-04-30 04:09:41 +00003900 if (Record[8]-1 >= GCTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003901 return error("Invalid ID");
Benjamin Kramer728f4442016-05-29 10:46:35 +00003902 Func->setGC(GCTable[Record[8] - 1]);
Gordon Henriksen71183b62007-12-10 03:18:06 +00003903 }
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003904 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
Rafael Espindola45e6c192011-01-08 16:42:36 +00003905 if (Record.size() > 9)
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003906 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003907 Func->setUnnamedAddr(UnnamedAddr);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003908 if (Record.size() > 10 && Record[10] != 0)
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003909 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
Nico Rieck7157bb72014-01-14 15:22:47 +00003910
3911 if (Record.size() > 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003912 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003913 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003914 upgradeDLLImportExportLinkage(Func, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00003915
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003916 if (Record.size() > 12) {
David Majnemerdad0a642014-06-27 18:19:56 +00003917 if (unsigned ComdatID = Record[12]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00003918 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003919 return error("Invalid function comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00003920 Func->setComdat(ComdatList[ComdatID - 1]);
3921 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003922 } else if (hasImplicitComdat(RawLinkage)) {
3923 Func->setComdat(reinterpret_cast<Comdat *>(1));
3924 }
David Majnemerdad0a642014-06-27 18:19:56 +00003925
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003926 if (Record.size() > 13 && Record[13] != 0)
3927 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3928
David Majnemer7fddecc2015-06-17 20:52:32 +00003929 if (Record.size() > 14 && Record[14] != 0)
3930 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3931
Chris Lattnerccaa4482007-04-23 21:26:05 +00003932 ValueList.push_back(Func);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003933
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003934 // If this is a function with a body, remember the prototype we are
3935 // creating now, so that we can match up the body with them later.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003936 if (!isProto) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00003937 Func->setIsMaterializable(true);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003938 FunctionsWithBodies.push_back(Func);
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003939 DeferredFunctionInfo[Func] = 0;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003940 }
Chris Lattner1314b992007-04-22 06:23:29 +00003941 break;
3942 }
David Blaikie6a51dbd2015-09-17 22:18:59 +00003943 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3944 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003945 // IFUNC: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3946 case bitc::MODULE_CODE_IFUNC:
David Blaikie6a51dbd2015-09-17 22:18:59 +00003947 case bitc::MODULE_CODE_ALIAS:
3948 case bitc::MODULE_CODE_ALIAS_OLD: {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003949 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
Aaron Ballman2d0f38c2015-09-18 13:31:42 +00003950 if (Record.size() < (3 + (unsigned)NewRecord))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003951 return error("Invalid record");
David Blaikie6a51dbd2015-09-17 22:18:59 +00003952 unsigned OpNum = 0;
3953 Type *Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003954 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003955 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003956
David Blaikie6a51dbd2015-09-17 22:18:59 +00003957 unsigned AddrSpace;
3958 if (!NewRecord) {
3959 auto *PTy = dyn_cast<PointerType>(Ty);
3960 if (!PTy)
3961 return error("Invalid type for value");
3962 Ty = PTy->getElementType();
3963 AddrSpace = PTy->getAddressSpace();
3964 } else {
3965 AddrSpace = Record[OpNum++];
3966 }
3967
3968 auto Val = Record[OpNum++];
3969 auto Linkage = Record[OpNum++];
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003970 GlobalIndirectSymbol *NewGA;
3971 if (BitCode == bitc::MODULE_CODE_ALIAS ||
3972 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003973 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
3974 "", TheModule);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003975 else
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003976 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
3977 "", nullptr, TheModule);
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00003978 // Old bitcode files didn't have visibility field.
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003979 // Local linkage must have default visibility.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003980 if (OpNum != Record.size()) {
3981 auto VisInd = OpNum++;
3982 if (!NewGA->hasLocalLinkage())
3983 // FIXME: Change to an error if non-default in 4.0.
3984 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3985 }
3986 if (OpNum != Record.size())
3987 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003988 else
David Blaikie6a51dbd2015-09-17 22:18:59 +00003989 upgradeDLLImportExportLinkage(NewGA, Linkage);
3990 if (OpNum != Record.size())
3991 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3992 if (OpNum != Record.size())
Peter Collingbourne96efdd62016-06-14 21:01:22 +00003993 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
Chris Lattner44c17072007-04-26 02:46:40 +00003994 ValueList.push_back(NewGA);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003995 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
Chris Lattner44c17072007-04-26 02:46:40 +00003996 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003997 }
Chris Lattner831d4202007-04-26 03:27:58 +00003998 /// MODULE_CODE_PURGEVALS: [numvals]
3999 case bitc::MODULE_CODE_PURGEVALS:
4000 // Trim down the value list to the specified size.
4001 if (Record.size() < 1 || Record[0] > ValueList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004002 return error("Invalid record");
Chris Lattner831d4202007-04-26 03:27:58 +00004003 ValueList.shrinkTo(Record[0]);
4004 break;
Teresa Johnsonff642b92015-09-17 20:12:00 +00004005 /// MODULE_CODE_VSTOFFSET: [offset]
4006 case bitc::MODULE_CODE_VSTOFFSET:
4007 if (Record.size() < 1)
4008 return error("Invalid record");
4009 VSTOffset = Record[0];
4010 break;
Teresa Johnsone1164de2016-02-10 21:55:02 +00004011 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4012 case bitc::MODULE_CODE_SOURCE_FILENAME:
4013 SmallString<128> ValueName;
4014 if (convertToString(Record, 0, ValueName))
4015 return error("Invalid record");
4016 TheModule->setSourceFileName(ValueName);
4017 break;
Chris Lattner831d4202007-04-26 03:27:58 +00004018 }
Chris Lattner1314b992007-04-22 06:23:29 +00004019 Record.clear();
4020 }
Chris Lattner1314b992007-04-22 06:23:29 +00004021}
4022
Teresa Johnson403a7872015-10-04 14:33:43 +00004023/// Helper to read the header common to all bitcode files.
4024static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
4025 // Sniff for the signature.
4026 if (Stream.Read(8) != 'B' ||
4027 Stream.Read(8) != 'C' ||
4028 Stream.Read(4) != 0x0 ||
4029 Stream.Read(4) != 0xC ||
4030 Stream.Read(4) != 0xE ||
4031 Stream.Read(4) != 0xD)
4032 return false;
4033 return true;
4034}
4035
Rafael Espindola1aabf982015-06-16 23:29:49 +00004036std::error_code
4037BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
4038 Module *M, bool ShouldLazyLoadMetadata) {
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00004039 TheModule = M;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004040
Rafael Espindola1aabf982015-06-16 23:29:49 +00004041 if (std::error_code EC = initStream(std::move(Streamer)))
Rafael Espindola48da4f42013-11-04 16:16:24 +00004042 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004043
Chris Lattner1314b992007-04-22 06:23:29 +00004044 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004045 if (!hasValidBitcodeHeader(Stream))
4046 return error("Invalid bitcode signature");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004047
Chris Lattner1314b992007-04-22 06:23:29 +00004048 // We expect a number of well-defined blocks, though we don't necessarily
4049 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00004050 while (1) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00004051 if (Stream.AtEndOfStream()) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00004052 // We didn't really read a proper Module.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004053 return error("Malformed IR file");
Filipe Cabecinhas22554272015-04-14 14:07:15 +00004054 }
Joe Abbey97b7a172013-02-06 22:14:06 +00004055
Chris Lattner27d38752013-01-20 02:13:19 +00004056 BitstreamEntry Entry =
4057 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbey97b7a172013-02-06 22:14:06 +00004058
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00004059 if (Entry.Kind != BitstreamEntry::SubBlock)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004060 return error("Malformed block");
Joe Abbey97b7a172013-02-06 22:14:06 +00004061
Mehdi Amini5d303282015-10-26 18:37:00 +00004062 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
4063 parseBitcodeVersion();
4064 continue;
4065 }
4066
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00004067 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Teresa Johnson1493ad92015-10-10 14:18:36 +00004068 return parseModule(0, ShouldLazyLoadMetadata);
Joe Abbey97b7a172013-02-06 22:14:06 +00004069
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00004070 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004071 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00004072 }
Chris Lattner1314b992007-04-22 06:23:29 +00004073}
Chris Lattner6694f602007-04-29 07:54:31 +00004074
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004075ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
Bill Wendling0198ce02010-10-06 01:22:42 +00004076 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004077 return error("Invalid record");
Bill Wendling0198ce02010-10-06 01:22:42 +00004078
4079 SmallVector<uint64_t, 64> Record;
4080
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004081 std::string Triple;
Bill Wendling0198ce02010-10-06 01:22:42 +00004082 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00004083 while (1) {
4084 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00004085
Chris Lattner27d38752013-01-20 02:13:19 +00004086 switch (Entry.Kind) {
4087 case BitstreamEntry::SubBlock: // Handled for us already.
4088 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004089 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004090 case BitstreamEntry::EndBlock:
Rafael Espindolae6107792014-07-04 20:05:56 +00004091 return Triple;
Chris Lattner27d38752013-01-20 02:13:19 +00004092 case BitstreamEntry::Record:
4093 // The interesting case.
4094 break;
Bill Wendling0198ce02010-10-06 01:22:42 +00004095 }
4096
4097 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00004098 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling0198ce02010-10-06 01:22:42 +00004099 default: break; // Default behavior, ignore unknown content.
Bill Wendling0198ce02010-10-06 01:22:42 +00004100 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004101 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004102 if (convertToString(Record, 0, S))
4103 return error("Invalid record");
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004104 Triple = S;
Bill Wendling0198ce02010-10-06 01:22:42 +00004105 break;
4106 }
4107 }
4108 Record.clear();
4109 }
Rafael Espindolae6107792014-07-04 20:05:56 +00004110 llvm_unreachable("Exit infinite loop");
Bill Wendling0198ce02010-10-06 01:22:42 +00004111}
4112
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004113ErrorOr<std::string> BitcodeReader::parseTriple() {
Rafael Espindola1aabf982015-06-16 23:29:49 +00004114 if (std::error_code EC = initStream(nullptr))
Rafael Espindola48da4f42013-11-04 16:16:24 +00004115 return EC;
Bill Wendling0198ce02010-10-06 01:22:42 +00004116
4117 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004118 if (!hasValidBitcodeHeader(Stream))
4119 return error("Invalid bitcode signature");
Bill Wendling0198ce02010-10-06 01:22:42 +00004120
4121 // We expect a number of well-defined blocks, though we don't necessarily
4122 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00004123 while (1) {
4124 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00004125
Chris Lattner27d38752013-01-20 02:13:19 +00004126 switch (Entry.Kind) {
4127 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004128 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004129 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004130 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00004131
Chris Lattner27d38752013-01-20 02:13:19 +00004132 case BitstreamEntry::SubBlock:
4133 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Rafael Espindolad346cc82014-07-04 13:52:01 +00004134 return parseModuleTriple();
Joe Abbey97b7a172013-02-06 22:14:06 +00004135
Chris Lattner27d38752013-01-20 02:13:19 +00004136 // Ignore other sub-blocks.
Rafael Espindola48da4f42013-11-04 16:16:24 +00004137 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004138 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004139 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00004140
Chris Lattner27d38752013-01-20 02:13:19 +00004141 case BitstreamEntry::Record:
4142 Stream.skipRecord(Entry.ID);
4143 continue;
Bill Wendling0198ce02010-10-06 01:22:42 +00004144 }
4145 }
Bill Wendling0198ce02010-10-06 01:22:42 +00004146}
4147
Mehdi Amini3383ccc2015-11-09 02:46:41 +00004148ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
4149 if (std::error_code EC = initStream(nullptr))
4150 return EC;
4151
4152 // Sniff for the signature.
4153 if (!hasValidBitcodeHeader(Stream))
4154 return error("Invalid bitcode signature");
4155
4156 // We expect a number of well-defined blocks, though we don't necessarily
4157 // need to understand them all.
4158 while (1) {
4159 BitstreamEntry Entry = Stream.advance();
4160 switch (Entry.Kind) {
4161 case BitstreamEntry::Error:
4162 return error("Malformed block");
4163 case BitstreamEntry::EndBlock:
4164 return std::error_code();
4165
4166 case BitstreamEntry::SubBlock:
4167 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
4168 if (std::error_code EC = parseBitcodeVersion())
4169 return EC;
4170 return ProducerIdentification;
4171 }
4172 // Ignore other sub-blocks.
4173 if (Stream.SkipBlock())
4174 return error("Malformed block");
4175 continue;
4176 case BitstreamEntry::Record:
4177 Stream.skipRecord(Entry.ID);
4178 continue;
4179 }
4180 }
4181}
4182
Peter Collingbournecceae7f2016-05-31 23:01:54 +00004183std::error_code BitcodeReader::parseGlobalObjectAttachment(
4184 GlobalObject &GO, ArrayRef<uint64_t> Record) {
4185 assert(Record.size() % 2 == 0);
4186 for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
4187 auto K = MDKindMap.find(Record[I]);
4188 if (K == MDKindMap.end())
4189 return error("Invalid ID");
4190 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
4191 if (!MD)
4192 return error("Invalid metadata attachment");
Peter Collingbourne382d81c2016-06-01 01:17:57 +00004193 GO.addMetadata(K->second, *MD);
Peter Collingbournecceae7f2016-05-31 23:01:54 +00004194 }
4195 return std::error_code();
4196}
4197
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004198/// Parse metadata attachments.
4199std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
Devang Patelaf206b82009-09-18 19:26:43 +00004200 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004201 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004202
Devang Patelaf206b82009-09-18 19:26:43 +00004203 SmallVector<uint64_t, 64> Record;
Chris Lattner27d38752013-01-20 02:13:19 +00004204 while (1) {
4205 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00004206
Chris Lattner27d38752013-01-20 02:13:19 +00004207 switch (Entry.Kind) {
4208 case BitstreamEntry::SubBlock: // Handled for us already.
4209 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004210 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004211 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004212 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00004213 case BitstreamEntry::Record:
4214 // The interesting case.
Devang Patelaf206b82009-09-18 19:26:43 +00004215 break;
4216 }
Chris Lattner27d38752013-01-20 02:13:19 +00004217
Devang Patelaf206b82009-09-18 19:26:43 +00004218 // Read a metadata attachment record.
4219 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00004220 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patelaf206b82009-09-18 19:26:43 +00004221 default: // Default behavior: ignore.
4222 break;
Chris Lattnerb8778552011-06-17 17:50:30 +00004223 case bitc::METADATA_ATTACHMENT: {
Devang Patelaf206b82009-09-18 19:26:43 +00004224 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00004225 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004226 return error("Invalid record");
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00004227 if (RecordLength % 2 == 0) {
4228 // A function attachment.
Peter Collingbournecceae7f2016-05-31 23:01:54 +00004229 if (std::error_code EC = parseGlobalObjectAttachment(F, Record))
4230 return EC;
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00004231 continue;
4232 }
4233
4234 // An instruction attachment.
Devang Patelaf206b82009-09-18 19:26:43 +00004235 Instruction *Inst = InstructionList[Record[0]];
4236 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patelb1a44772009-09-28 21:14:55 +00004237 unsigned Kind = Record[i];
Dan Gohman43aa8f02010-07-20 21:42:28 +00004238 DenseMap<unsigned, unsigned>::iterator I =
4239 MDKindMap.find(Kind);
4240 if (I == MDKindMap.end())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004241 return error("Invalid ID");
Justin Bognerae341c62016-03-17 20:12:06 +00004242 Metadata *Node = MetadataList.getMetadataFwdRef(Record[i + 1]);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004243 if (isa<LocalAsMetadata>(Node))
Duncan P. N. Exon Smith35303fd2014-12-06 02:29:44 +00004244 // Drop the attachment. This used to be legal, but there's no
4245 // upgrade path.
4246 break;
Justin Bognerae341c62016-03-17 20:12:06 +00004247 MDNode *MD = dyn_cast_or_null<MDNode>(Node);
4248 if (!MD)
4249 return error("Invalid metadata attachment");
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00004250
4251 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
4252 MD = upgradeInstructionLoopAttachment(*MD);
4253
Justin Bognerae341c62016-03-17 20:12:06 +00004254 Inst->setMetadata(I->second, MD);
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00004255 if (I->second == LLVMContext::MD_tbaa) {
Manman Ren209b17c2013-09-28 00:22:27 +00004256 InstsWithTBAATag.push_back(Inst);
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00004257 continue;
4258 }
Devang Patelaf206b82009-09-18 19:26:43 +00004259 }
4260 break;
4261 }
4262 }
4263 }
Devang Patelaf206b82009-09-18 19:26:43 +00004264}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004265
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004266static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
4267 LLVMContext &Context = PtrType->getContext();
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004268 if (!isa<PointerType>(PtrType))
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004269 return error(Context, "Load/Store operand is not a pointer type");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004270 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
4271
4272 if (ValType && ValType != ElemType)
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004273 return error(Context, "Explicit load/store type does not match pointee "
4274 "type of pointer operand");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004275 if (!PointerType::isLoadableOrStorableType(ElemType))
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004276 return error(Context, "Cannot load/store from pointer");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004277 return std::error_code();
4278}
4279
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004280/// Lazily parse the specified function body block.
4281std::error_code BitcodeReader::parseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00004282 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004283 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004284
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00004285 // Unexpected unresolved metadata when parsing function.
4286 if (MetadataList.hasFwdRefs())
4287 return error("Invalid function metadata: incoming forward references");
4288
Nick Lewyckya72e1af2010-02-25 08:30:17 +00004289 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00004290 unsigned ModuleValueListSize = ValueList.size();
Teresa Johnson61b406e2015-12-29 23:00:22 +00004291 unsigned ModuleMetadataListSize = MetadataList.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004292
Chris Lattner85b7b402007-05-01 05:52:21 +00004293 // Add all the function arguments to the value table.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00004294 for (Argument &I : F->args())
4295 ValueList.push_back(&I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004296
Chris Lattner83930552007-05-01 07:01:57 +00004297 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00004298 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00004299 unsigned CurBBNo = 0;
4300
Chris Lattner07d09ed2010-04-03 02:17:50 +00004301 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004302 auto getLastInstruction = [&]() -> Instruction * {
4303 if (CurBB && !CurBB->empty())
4304 return &CurBB->back();
4305 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4306 !FunctionBBs[CurBBNo - 1]->empty())
4307 return &FunctionBBs[CurBBNo - 1]->back();
4308 return nullptr;
4309 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004310
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004311 std::vector<OperandBundleDef> OperandBundles;
4312
Chris Lattner85b7b402007-05-01 05:52:21 +00004313 // Read all the records.
4314 SmallVector<uint64_t, 64> Record;
4315 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00004316 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00004317
Chris Lattner27d38752013-01-20 02:13:19 +00004318 switch (Entry.Kind) {
4319 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004320 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004321 case BitstreamEntry::EndBlock:
4322 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00004323
Chris Lattner27d38752013-01-20 02:13:19 +00004324 case BitstreamEntry::SubBlock:
4325 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00004326 default: // Skip unknown content.
4327 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004328 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00004329 break;
4330 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004331 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004332 return EC;
Chris Lattner83930552007-05-01 07:01:57 +00004333 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00004334 break;
4335 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004336 if (std::error_code EC = parseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004337 return EC;
Chris Lattner85b7b402007-05-01 05:52:21 +00004338 break;
Devang Patelaf206b82009-09-18 19:26:43 +00004339 case bitc::METADATA_ATTACHMENT_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004340 if (std::error_code EC = parseMetadataAttachment(*F))
Rafael Espindola48da4f42013-11-04 16:16:24 +00004341 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004342 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00004343 case bitc::METADATA_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004344 if (std::error_code EC = parseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004345 return EC;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00004346 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004347 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004348 if (std::error_code EC = parseUseLists())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004349 return EC;
4350 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00004351 }
4352 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00004353
Chris Lattner27d38752013-01-20 02:13:19 +00004354 case BitstreamEntry::Record:
4355 // The interesting case.
4356 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00004357 }
Joe Abbey97b7a172013-02-06 22:14:06 +00004358
Chris Lattner85b7b402007-05-01 05:52:21 +00004359 // Read a record.
4360 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00004361 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00004362 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00004363 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00004364 default: // Default behavior: reject
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004365 return error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004366 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00004367 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004368 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00004369 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00004370 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004371
4372 // See if anything took the address of blocks in this function.
4373 auto BBFRI = BasicBlockFwdRefs.find(F);
4374 if (BBFRI == BasicBlockFwdRefs.end()) {
4375 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4376 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
4377 } else {
4378 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00004379 // Check for invalid basic block references.
4380 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004381 return error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00004382 assert(!BBRefs.empty() && "Unexpected empty array");
4383 assert(!BBRefs.front() && "Invalid reference to entry block");
4384 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4385 ++I)
4386 if (I < RE && BBRefs[I]) {
4387 BBRefs[I]->insertInto(F);
4388 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004389 } else {
4390 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4391 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004392
4393 // Erase from the table.
4394 BasicBlockFwdRefs.erase(BBFRI);
4395 }
4396
Chris Lattner83930552007-05-01 07:01:57 +00004397 CurBB = FunctionBBs[0];
4398 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004399 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004400
Chris Lattner07d09ed2010-04-03 02:17:50 +00004401 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4402 // This record indicates that the last instruction is at the same
4403 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004404 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004405
Craig Topper2617dcc2014-04-15 06:32:26 +00004406 if (!I)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004407 return error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00004408 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004409 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004410 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004411
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00004412 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004413 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00004414 if (!I || Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004415 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004416
Chris Lattner07d09ed2010-04-03 02:17:50 +00004417 unsigned Line = Record[0], Col = Record[1];
4418 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004419
Craig Topper2617dcc2014-04-15 06:32:26 +00004420 MDNode *Scope = nullptr, *IA = nullptr;
Justin Bognerae341c62016-03-17 20:12:06 +00004421 if (ScopeID) {
4422 Scope = MetadataList.getMDNodeFwdRefOrNull(ScopeID - 1);
4423 if (!Scope)
4424 return error("Invalid record");
4425 }
4426 if (IAID) {
4427 IA = MetadataList.getMDNodeFwdRefOrNull(IAID - 1);
4428 if (!IA)
4429 return error("Invalid record");
4430 }
Chris Lattner07d09ed2010-04-03 02:17:50 +00004431 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4432 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004433 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004434 continue;
4435 }
4436
Chris Lattnere9759c22007-05-06 00:21:25 +00004437 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4438 unsigned OpNum = 0;
4439 Value *LHS, *RHS;
4440 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004441 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00004442 OpNum+1 > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004443 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004444
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004445 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00004446 if (Opc == -1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004447 return error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004448 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00004449 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00004450 if (OpNum < Record.size()) {
4451 if (Opc == Instruction::Add ||
4452 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00004453 Opc == Instruction::Mul ||
4454 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00004455 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00004456 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00004457 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00004458 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00004459 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00004460 Opc == Instruction::UDiv ||
4461 Opc == Instruction::LShr ||
4462 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00004463 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00004464 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004465 } else if (isa<FPMathOperator>(I)) {
James Molloy88eb5352015-07-10 12:52:00 +00004466 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004467 if (FMF.any())
4468 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00004469 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004470
Dan Gohman1b849082009-09-07 23:54:19 +00004471 }
Chris Lattner85b7b402007-05-01 05:52:21 +00004472 break;
4473 }
Chris Lattnere9759c22007-05-06 00:21:25 +00004474 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4475 unsigned OpNum = 0;
4476 Value *Op;
4477 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4478 OpNum+2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004479 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004480
Chris Lattner229907c2011-07-18 04:54:35 +00004481 Type *ResTy = getTypeByID(Record[OpNum]);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004482 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004483 if (Opc == -1 || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004484 return error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00004485 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004486 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4487 if (Temp) {
4488 InstructionList.push_back(Temp);
4489 CurBB->getInstList().push_back(Temp);
4490 }
4491 } else {
Filipe Cabecinhasb70fd872015-10-06 12:37:54 +00004492 auto CastOp = (Instruction::CastOps)Opc;
4493 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4494 return error("Invalid cast");
4495 I = CastInst::Create(CastOp, Op, ResTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004496 }
Devang Patelaf206b82009-09-18 19:26:43 +00004497 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004498 break;
4499 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00004500 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4501 case bitc::FUNC_CODE_INST_GEP_OLD:
4502 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004503 unsigned OpNum = 0;
David Blaikieb5b5efd2015-02-25 01:08:52 +00004504
4505 Type *Ty;
4506 bool InBounds;
4507
4508 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4509 InBounds = Record[OpNum++];
4510 Ty = getTypeByID(Record[OpNum++]);
4511 } else {
4512 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4513 Ty = nullptr;
4514 }
4515
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004516 Value *BasePtr;
4517 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004518 return error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00004519
David Blaikie60310f22015-05-08 00:42:26 +00004520 if (!Ty)
4521 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4522 ->getElementType();
4523 else if (Ty !=
4524 cast<SequentialType>(BasePtr->getType()->getScalarType())
4525 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004526 return error(
David Blaikie675e8cb2015-03-16 21:35:48 +00004527 "Explicit gep type does not match pointee type of pointer operand");
4528
Chris Lattner5285b5e2007-05-02 05:46:45 +00004529 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004530 while (OpNum != Record.size()) {
4531 Value *Op;
4532 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004533 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004534 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004535 }
4536
David Blaikie096b1da2015-03-14 19:53:33 +00004537 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
David Blaikie675e8cb2015-03-16 21:35:48 +00004538
Devang Patelaf206b82009-09-18 19:26:43 +00004539 InstructionList.push_back(I);
David Blaikieb5b5efd2015-02-25 01:08:52 +00004540 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004541 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004542 break;
4543 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004544
Dan Gohman1ecaf452008-05-31 00:58:22 +00004545 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4546 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00004547 unsigned OpNum = 0;
4548 Value *Agg;
4549 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004550 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004551
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004552 unsigned RecSize = Record.size();
4553 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004554 return error("EXTRACTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004555
Dan Gohman1ecaf452008-05-31 00:58:22 +00004556 SmallVector<unsigned, 4> EXTRACTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004557 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004558 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004559 bool IsArray = CurTy->isArrayTy();
4560 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00004561 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004562
4563 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004564 return error("EXTRACTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004565 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004566 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004567 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004568 return error("EXTRACTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004569 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004570 return error("EXTRACTVAL: Invalid array index");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004571 EXTRACTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004572
4573 if (IsStruct)
4574 CurTy = CurTy->subtypes()[Index];
4575 else
4576 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00004577 }
4578
Jay Foad57aa6362011-07-13 10:26:04 +00004579 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00004580 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00004581 break;
4582 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004583
Dan Gohman1ecaf452008-05-31 00:58:22 +00004584 case bitc::FUNC_CODE_INST_INSERTVAL: {
4585 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00004586 unsigned OpNum = 0;
4587 Value *Agg;
4588 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004589 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004590 Value *Val;
4591 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004592 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004593
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004594 unsigned RecSize = Record.size();
4595 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004596 return error("INSERTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004597
Dan Gohman1ecaf452008-05-31 00:58:22 +00004598 SmallVector<unsigned, 4> INSERTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004599 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004600 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004601 bool IsArray = CurTy->isArrayTy();
4602 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00004603 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004604
4605 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004606 return error("INSERTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004607 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004608 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004609 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004610 return error("INSERTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004611 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004612 return error("INSERTVAL: Invalid array index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004613
Dan Gohman1ecaf452008-05-31 00:58:22 +00004614 INSERTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004615 if (IsStruct)
4616 CurTy = CurTy->subtypes()[Index];
4617 else
4618 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00004619 }
4620
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00004621 if (CurTy != Val->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004622 return error("Inserted value type doesn't match aggregate type");
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00004623
Jay Foad57aa6362011-07-13 10:26:04 +00004624 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00004625 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00004626 break;
4627 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004628
Chris Lattnere9759c22007-05-06 00:21:25 +00004629 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00004630 // obsolete form of select
4631 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00004632 unsigned OpNum = 0;
4633 Value *TrueVal, *FalseVal, *Cond;
4634 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004635 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4636 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004637 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004638
Dan Gohmanc5d28922008-09-16 01:01:33 +00004639 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00004640 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00004641 break;
4642 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004643
Dan Gohmanc5d28922008-09-16 01:01:33 +00004644 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4645 // new form of select
4646 // handles select i1 or select [N x i1]
4647 unsigned OpNum = 0;
4648 Value *TrueVal, *FalseVal, *Cond;
4649 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004650 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00004651 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004652 return error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00004653
4654 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00004655 if (VectorType* vector_type =
4656 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00004657 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004658 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004659 return error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00004660 } else {
4661 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004662 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004663 return error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004664 }
4665
Gabor Greife9ecc682008-04-06 20:25:17 +00004666 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00004667 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004668 break;
4669 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004670
Chris Lattner1fc27f02007-05-02 05:16:49 +00004671 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00004672 unsigned OpNum = 0;
4673 Value *Vec, *Idx;
4674 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00004675 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004676 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004677 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004678 return error("Invalid type for value");
Eric Christopherc9742252009-07-25 02:28:41 +00004679 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00004680 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004681 break;
4682 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004683
Chris Lattner1fc27f02007-05-02 05:16:49 +00004684 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00004685 unsigned OpNum = 0;
4686 Value *Vec, *Elt, *Idx;
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004687 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004688 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004689 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004690 return error("Invalid type for value");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004691 if (popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00004692 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00004693 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004694 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00004695 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00004696 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004697 break;
4698 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004699
Chris Lattnere9759c22007-05-06 00:21:25 +00004700 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4701 unsigned OpNum = 0;
4702 Value *Vec1, *Vec2, *Mask;
4703 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004704 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004705 return error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00004706
Mon P Wang25f01062008-11-10 04:46:22 +00004707 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004708 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004709 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004710 return error("Invalid type for value");
Chris Lattner1fc27f02007-05-02 05:16:49 +00004711 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00004712 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004713 break;
4714 }
Mon P Wang25f01062008-11-10 04:46:22 +00004715
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004716 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4717 // Old form of ICmp/FCmp returning bool
4718 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4719 // both legal on vectors but had different behaviour.
4720 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4721 // FCmp/ICmp returning bool or vector of bool
4722
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004723 unsigned OpNum = 0;
4724 Value *LHS, *RHS;
4725 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
James Molloy88eb5352015-07-10 12:52:00 +00004726 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4727 return error("Invalid record");
4728
4729 unsigned PredVal = Record[OpNum];
4730 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4731 FastMathFlags FMF;
4732 if (IsFP && Record.size() > OpNum+1)
4733 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4734
4735 if (OpNum+1 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004736 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004737
Duncan Sands9dff9be2010-02-15 16:12:20 +00004738 if (LHS->getType()->isFPOrFPVectorTy())
James Molloy88eb5352015-07-10 12:52:00 +00004739 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004740 else
James Molloy88eb5352015-07-10 12:52:00 +00004741 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4742
4743 if (FMF.any())
4744 I->setFastMathFlags(FMF);
Devang Patelaf206b82009-09-18 19:26:43 +00004745 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00004746 break;
4747 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004748
Chris Lattnere53603e2007-05-02 04:27:25 +00004749 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00004750 {
4751 unsigned Size = Record.size();
4752 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00004753 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004754 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00004755 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004756 }
Devang Patelbbfd8742008-02-26 01:29:32 +00004757
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004758 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004759 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00004760 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004761 return error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00004762 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004763 return error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004764
Chris Lattnerf1c87102011-06-17 18:09:11 +00004765 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004766 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004767 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00004768 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004769 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00004770 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004771 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004772 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004773 if (!TrueDest)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004774 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004775
Devang Patelaf206b82009-09-18 19:26:43 +00004776 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00004777 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004778 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00004779 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004780 else {
4781 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004782 Value *Cond = getValue(Record, 2, NextValueNo,
4783 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00004784 if (!FalseDest || !Cond)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004785 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00004786 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004787 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004788 }
4789 break;
4790 }
David Majnemerb01aa9f2015-08-23 19:22:31 +00004791 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004792 if (Record.size() != 1 && Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00004793 return error("Invalid record");
4794 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004795 Value *CleanupPad =
4796 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004797 if (!CleanupPad)
David Majnemer654e1302015-07-31 17:58:14 +00004798 return error("Invalid record");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004799 BasicBlock *UnwindDest = nullptr;
4800 if (Record.size() == 2) {
David Majnemer654e1302015-07-31 17:58:14 +00004801 UnwindDest = getBasicBlock(Record[Idx++]);
4802 if (!UnwindDest)
4803 return error("Invalid record");
4804 }
4805
David Majnemer8a1c45d2015-12-12 05:38:55 +00004806 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
David Majnemer654e1302015-07-31 17:58:14 +00004807 InstructionList.push_back(I);
4808 break;
4809 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004810 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4811 if (Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00004812 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004813 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004814 Value *CatchPad =
4815 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004816 if (!CatchPad)
4817 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004818 BasicBlock *BB = getBasicBlock(Record[Idx++]);
David Majnemer654e1302015-07-31 17:58:14 +00004819 if (!BB)
4820 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004821
David Majnemer8a1c45d2015-12-12 05:38:55 +00004822 I = CatchReturnInst::Create(CatchPad, BB);
David Majnemer654e1302015-07-31 17:58:14 +00004823 InstructionList.push_back(I);
4824 break;
4825 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004826 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4827 // We must have, at minimum, the outer scope and the number of arguments.
4828 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00004829 return error("Invalid record");
4830
David Majnemer654e1302015-07-31 17:58:14 +00004831 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004832
4833 Value *ParentPad =
4834 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4835
4836 unsigned NumHandlers = Record[Idx++];
4837
4838 SmallVector<BasicBlock *, 2> Handlers;
4839 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4840 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4841 if (!BB)
David Majnemer654e1302015-07-31 17:58:14 +00004842 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004843 Handlers.push_back(BB);
4844 }
4845
4846 BasicBlock *UnwindDest = nullptr;
4847 if (Idx + 1 == Record.size()) {
David Majnemer654e1302015-07-31 17:58:14 +00004848 UnwindDest = getBasicBlock(Record[Idx++]);
4849 if (!UnwindDest)
4850 return error("Invalid record");
4851 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004852
4853 if (Record.size() != Idx)
4854 return error("Invalid record");
4855
4856 auto *CatchSwitch =
4857 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4858 for (BasicBlock *Handler : Handlers)
4859 CatchSwitch->addHandler(Handler);
4860 I = CatchSwitch;
4861 InstructionList.push_back(I);
4862 break;
4863 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004864 case bitc::FUNC_CODE_INST_CATCHPAD:
4865 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4866 // We must have, at minimum, the outer scope and the number of arguments.
4867 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00004868 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004869
David Majnemer654e1302015-07-31 17:58:14 +00004870 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004871
4872 Value *ParentPad =
4873 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4874
David Majnemer654e1302015-07-31 17:58:14 +00004875 unsigned NumArgOperands = Record[Idx++];
David Majnemer8a1c45d2015-12-12 05:38:55 +00004876
David Majnemer654e1302015-07-31 17:58:14 +00004877 SmallVector<Value *, 2> Args;
4878 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4879 Value *Val;
4880 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4881 return error("Invalid record");
4882 Args.push_back(Val);
4883 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004884
David Majnemer654e1302015-07-31 17:58:14 +00004885 if (Record.size() != Idx)
4886 return error("Invalid record");
4887
David Majnemer8a1c45d2015-12-12 05:38:55 +00004888 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4889 I = CleanupPadInst::Create(ParentPad, Args);
4890 else
4891 I = CatchPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00004892 InstructionList.push_back(I);
4893 break;
4894 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00004895 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004896 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004897 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00004898 // "New" SwitchInst format with case ranges. The changes to write this
4899 // format were reverted but we still recognize bitcode that uses it.
4900 // Hopefully someday we will have support for case ranges and can use
4901 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004902
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004903 Type *OpTy = getTypeByID(Record[1]);
4904 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4905
Jan Wen Voungafaced02012-10-11 20:20:40 +00004906 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004907 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004908 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004909 return error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004910
4911 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004912
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004913 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4914 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004915
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004916 unsigned CurIdx = 5;
4917 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00004918 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004919 unsigned NumItems = Record[CurIdx++];
4920 for (unsigned ci = 0; ci != NumItems; ++ci) {
4921 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004922
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004923 APInt Low;
4924 unsigned ActiveWords = 1;
4925 if (ValueBitWidth > 64)
4926 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004927 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
Benjamin Kramer9704ed02012-05-28 14:10:31 +00004928 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004929 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00004930
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004931 if (!isSingleNumber) {
4932 ActiveWords = 1;
4933 if (ValueBitWidth > 64)
4934 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004935 APInt High = readWideAPInt(
4936 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004937 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00004938
4939 // FIXME: It is not clear whether values in the range should be
4940 // compared as signed or unsigned values. The partially
4941 // implemented changes that used this format in the past used
4942 // unsigned comparisons.
4943 for ( ; Low.ule(High); ++Low)
4944 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004945 } else
Bob Wilsone4077362013-09-09 19:14:35 +00004946 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004947 }
4948 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00004949 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4950 cve = CaseVals.end(); cvi != cve; ++cvi)
4951 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004952 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004953 I = SI;
4954 break;
4955 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004956
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004957 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004958
Chris Lattner5285b5e2007-05-02 05:46:45 +00004959 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004960 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004961 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004962 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004963 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004964 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004965 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004966 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00004967 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00004968 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004969 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004970 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00004971 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4972 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004973 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00004974 delete SI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004975 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004976 }
4977 SI->addCase(CaseVal, DestBB);
4978 }
4979 I = SI;
4980 break;
4981 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004982 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00004983 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004984 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004985 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004986 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00004987 if (!OpTy || !Address)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004988 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004989 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004990 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00004991 InstructionList.push_back(IBI);
4992 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4993 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4994 IBI->addDestination(DestBB);
4995 } else {
4996 delete IBI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004997 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004998 }
4999 }
5000 I = IBI;
5001 break;
5002 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00005003
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00005004 case bitc::FUNC_CODE_INST_INVOKE: {
5005 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00005006 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005007 return error("Invalid record");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005008 unsigned OpNum = 0;
5009 AttributeSet PAL = getAttributes(Record[OpNum++]);
5010 unsigned CCInfo = Record[OpNum++];
5011 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5012 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005013
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005014 FunctionType *FTy = nullptr;
5015 if (CCInfo >> 13 & 1 &&
5016 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005017 return error("Explicit invoke type is not a function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005018
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005019 Value *Callee;
5020 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005021 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005022
Chris Lattner229907c2011-07-18 04:54:35 +00005023 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005024 if (!CalleeTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005025 return error("Callee is not a pointer");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005026 if (!FTy) {
5027 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
5028 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005029 return error("Callee is not of pointer to function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005030 } else if (CalleeTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005031 return error("Explicit invoke type does not match pointee type of "
David Blaikie5ea1f7b2015-04-24 18:06:06 +00005032 "callee operand");
5033 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005034 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005035
Chris Lattner5285b5e2007-05-02 05:46:45 +00005036 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005037 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00005038 Ops.push_back(getValue(Record, OpNum, NextValueNo,
5039 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00005040 if (!Ops.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005041 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00005042 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005043
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005044 if (!FTy->isVarArg()) {
5045 if (Record.size() != OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005046 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00005047 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005048 // Read type/value pairs for varargs params.
5049 while (OpNum != Record.size()) {
5050 Value *Op;
5051 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005052 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005053 Ops.push_back(Op);
5054 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00005055 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005056
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005057 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
5058 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00005059 InstructionList.push_back(I);
Vedant Kumarad6d6e72015-10-27 21:17:06 +00005060 cast<InvokeInst>(I)->setCallingConv(
5061 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00005062 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00005063 break;
5064 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00005065 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
5066 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00005067 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00005068 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005069 return error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00005070 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00005071 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00005072 break;
5073 }
Chris Lattnere53603e2007-05-02 04:27:25 +00005074 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00005075 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00005076 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00005077 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00005078 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00005079 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005080 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00005081 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005082 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005083 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005084
Jay Foad52131342011-03-30 11:28:46 +00005085 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00005086 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005087
Chris Lattnere14cb882007-05-04 19:11:41 +00005088 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00005089 Value *V;
5090 // With the new function encoding, it is possible that operands have
5091 // negative IDs (for forward references). Use a signed VBR
5092 // representation to keep the encoding small.
5093 if (UseRelativeIDs)
5094 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
5095 else
5096 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00005097 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005098 if (!V || !BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005099 return error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00005100 PN->addIncoming(V, BB);
5101 }
5102 I = PN;
5103 break;
5104 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005105
David Majnemer7fddecc2015-06-17 20:52:32 +00005106 case bitc::FUNC_CODE_INST_LANDINGPAD:
5107 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
Bill Wendlingfae14752011-08-12 20:24:12 +00005108 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
5109 unsigned Idx = 0;
David Majnemer7fddecc2015-06-17 20:52:32 +00005110 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
5111 if (Record.size() < 3)
5112 return error("Invalid record");
5113 } else {
5114 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
5115 if (Record.size() < 4)
5116 return error("Invalid record");
5117 }
Bill Wendlingfae14752011-08-12 20:24:12 +00005118 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005119 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005120 return error("Invalid record");
David Majnemer7fddecc2015-06-17 20:52:32 +00005121 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
5122 Value *PersFn = nullptr;
5123 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
5124 return error("Invalid record");
5125
5126 if (!F->hasPersonalityFn())
5127 F->setPersonalityFn(cast<Constant>(PersFn));
5128 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
5129 return error("Personality function mismatch");
5130 }
Bill Wendlingfae14752011-08-12 20:24:12 +00005131
5132 bool IsCleanup = !!Record[Idx++];
5133 unsigned NumClauses = Record[Idx++];
David Majnemer7fddecc2015-06-17 20:52:32 +00005134 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
Bill Wendlingfae14752011-08-12 20:24:12 +00005135 LP->setCleanup(IsCleanup);
5136 for (unsigned J = 0; J != NumClauses; ++J) {
5137 LandingPadInst::ClauseType CT =
5138 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
5139 Value *Val;
5140
5141 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
5142 delete LP;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005143 return error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00005144 }
5145
5146 assert((CT != LandingPadInst::Catch ||
5147 !isa<ArrayType>(Val->getType())) &&
5148 "Catch clause has a invalid type!");
5149 assert((CT != LandingPadInst::Filter ||
5150 isa<ArrayType>(Val->getType())) &&
5151 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00005152 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00005153 }
5154
5155 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00005156 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00005157 break;
5158 }
5159
Chris Lattnerf1c87102011-06-17 18:09:11 +00005160 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
5161 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005162 return error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00005163 uint64_t AlignRecord = Record[3];
5164 const uint64_t InAllocaMask = uint64_t(1) << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00005165 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00005166 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
5167 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
5168 SwiftErrorMask;
JF Bastien30bf96b2015-02-22 19:32:03 +00005169 bool InAlloca = AlignRecord & InAllocaMask;
Manman Ren9bfd0d02016-04-01 21:41:15 +00005170 bool SwiftError = AlignRecord & SwiftErrorMask;
David Blaikiebdb49102015-04-28 16:51:01 +00005171 Type *Ty = getTypeByID(Record[0]);
5172 if ((AlignRecord & ExplicitTypeMask) == 0) {
5173 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
5174 if (!PTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005175 return error("Old-style alloca with a non-pointer type");
David Blaikiebdb49102015-04-28 16:51:01 +00005176 Ty = PTy->getElementType();
5177 }
5178 Type *OpTy = getTypeByID(Record[1]);
5179 Value *Size = getFnValueByID(Record[2], OpTy);
JF Bastien30bf96b2015-02-22 19:32:03 +00005180 unsigned Align;
5181 if (std::error_code EC =
David Blaikiebdb49102015-04-28 16:51:01 +00005182 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
JF Bastien30bf96b2015-02-22 19:32:03 +00005183 return EC;
5184 }
Rafael Espindola48da4f42013-11-04 16:16:24 +00005185 if (!Ty || !Size)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005186 return error("Invalid record");
David Blaikiebdb49102015-04-28 16:51:01 +00005187 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00005188 AI->setUsedWithInAlloca(InAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00005189 AI->setSwiftError(SwiftError);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00005190 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00005191 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00005192 break;
5193 }
Chris Lattner9f600c52007-05-03 22:04:19 +00005194 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005195 unsigned OpNum = 0;
5196 Value *Op;
5197 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00005198 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005199 return error("Invalid record");
David Blaikie85035652015-02-25 01:07:20 +00005200
5201 Type *Ty = nullptr;
5202 if (OpNum + 3 == Record.size())
5203 Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005204 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005205 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00005206 if (!Ty)
5207 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00005208
JF Bastien30bf96b2015-02-22 19:32:03 +00005209 unsigned Align;
5210 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5211 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00005212 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
David Blaikie85035652015-02-25 01:07:20 +00005213
Devang Patelaf206b82009-09-18 19:26:43 +00005214 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00005215 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00005216 }
Eli Friedman59b66882011-08-09 23:02:53 +00005217 case bitc::FUNC_CODE_INST_LOADATOMIC: {
5218 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
5219 unsigned OpNum = 0;
5220 Value *Op;
5221 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00005222 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005223 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00005224
David Blaikie85035652015-02-25 01:07:20 +00005225 Type *Ty = nullptr;
5226 if (OpNum + 5 == Record.size())
5227 Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005228 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005229 return EC;
5230 if (!Ty)
5231 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00005232
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005233 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00005234 if (Ordering == AtomicOrdering::NotAtomic ||
5235 Ordering == AtomicOrdering::Release ||
5236 Ordering == AtomicOrdering::AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005237 return error("Invalid record");
JF Bastien800f87a2016-04-06 21:19:33 +00005238 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005239 return error("Invalid record");
5240 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00005241
JF Bastien30bf96b2015-02-22 19:32:03 +00005242 unsigned Align;
5243 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5244 return EC;
5245 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
David Blaikie85035652015-02-25 01:07:20 +00005246
Eli Friedman59b66882011-08-09 23:02:53 +00005247 InstructionList.push_back(I);
5248 break;
5249 }
David Blaikie612ddbf2015-04-22 04:14:42 +00005250 case bitc::FUNC_CODE_INST_STORE:
5251 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00005252 unsigned OpNum = 0;
5253 Value *Val, *Ptr;
5254 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie612ddbf2015-04-22 04:14:42 +00005255 (BitCode == bitc::FUNC_CODE_INST_STORE
5256 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5257 : popValue(Record, OpNum, NextValueNo,
5258 cast<PointerType>(Ptr->getType())->getElementType(),
5259 Val)) ||
5260 OpNum + 2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005261 return error("Invalid record");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005262
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005263 if (std::error_code EC =
5264 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005265 return EC;
JF Bastien30bf96b2015-02-22 19:32:03 +00005266 unsigned Align;
5267 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5268 return EC;
5269 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
Devang Patelaf206b82009-09-18 19:26:43 +00005270 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00005271 break;
5272 }
David Blaikie50a06152015-04-22 04:14:46 +00005273 case bitc::FUNC_CODE_INST_STOREATOMIC:
5274 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
Eli Friedman59b66882011-08-09 23:02:53 +00005275 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
5276 unsigned OpNum = 0;
5277 Value *Val, *Ptr;
5278 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Filipe Cabecinhas036e73c2016-06-05 18:43:33 +00005279 !isa<PointerType>(Ptr->getType()) ||
David Blaikie50a06152015-04-22 04:14:46 +00005280 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
5281 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5282 : popValue(Record, OpNum, NextValueNo,
5283 cast<PointerType>(Ptr->getType())->getElementType(),
5284 Val)) ||
5285 OpNum + 4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005286 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00005287
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005288 if (std::error_code EC =
5289 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005290 return EC;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005291 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00005292 if (Ordering == AtomicOrdering::NotAtomic ||
5293 Ordering == AtomicOrdering::Acquire ||
5294 Ordering == AtomicOrdering::AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005295 return error("Invalid record");
5296 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
JF Bastien800f87a2016-04-06 21:19:33 +00005297 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005298 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00005299
JF Bastien30bf96b2015-02-22 19:32:03 +00005300 unsigned Align;
5301 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5302 return EC;
5303 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
Eli Friedman59b66882011-08-09 23:02:53 +00005304 InstructionList.push_back(I);
5305 break;
5306 }
David Blaikie2a661cd2015-04-28 04:30:29 +00005307 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005308 case bitc::FUNC_CODE_INST_CMPXCHG: {
Tim Northovere94a5182014-03-11 10:48:52 +00005309 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
Tim Northover420a2162014-06-13 14:24:07 +00005310 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005311 unsigned OpNum = 0;
5312 Value *Ptr, *Cmp, *New;
5313 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie2a661cd2015-04-28 04:30:29 +00005314 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
5315 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
5316 : popValue(Record, OpNum, NextValueNo,
5317 cast<PointerType>(Ptr->getType())->getElementType(),
5318 Cmp)) ||
5319 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
5320 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005321 return error("Invalid record");
5322 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
JF Bastien800f87a2016-04-06 21:19:33 +00005323 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
5324 SuccessOrdering == AtomicOrdering::Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005325 return error("Invalid record");
5326 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
Tim Northovere94a5182014-03-11 10:48:52 +00005327
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005328 if (std::error_code EC =
5329 typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005330 return EC;
Tim Northovere94a5182014-03-11 10:48:52 +00005331 AtomicOrdering FailureOrdering;
5332 if (Record.size() < 7)
5333 FailureOrdering =
5334 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
5335 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005336 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
Tim Northovere94a5182014-03-11 10:48:52 +00005337
5338 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
5339 SynchScope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005340 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00005341
5342 if (Record.size() < 8) {
5343 // Before weak cmpxchgs existed, the instruction simply returned the
5344 // value loaded from memory, so bitcode files from that era will be
5345 // expecting the first component of a modern cmpxchg.
5346 CurBB->getInstList().push_back(I);
5347 I = ExtractValueInst::Create(I, 0);
5348 } else {
5349 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
5350 }
5351
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005352 InstructionList.push_back(I);
5353 break;
5354 }
5355 case bitc::FUNC_CODE_INST_ATOMICRMW: {
5356 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
5357 unsigned OpNum = 0;
5358 Value *Ptr, *Val;
5359 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Filipe Cabecinhas6328f8e2016-06-05 18:43:40 +00005360 !isa<PointerType>(Ptr->getType()) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00005361 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005362 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
5363 OpNum+4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005364 return error("Invalid record");
5365 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005366 if (Operation < AtomicRMWInst::FIRST_BINOP ||
5367 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005368 return error("Invalid record");
5369 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00005370 if (Ordering == AtomicOrdering::NotAtomic ||
5371 Ordering == AtomicOrdering::Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005372 return error("Invalid record");
5373 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005374 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
5375 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
5376 InstructionList.push_back(I);
5377 break;
5378 }
Eli Friedmanfee02c62011-07-25 23:16:38 +00005379 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
5380 if (2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005381 return error("Invalid record");
5382 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
JF Bastien800f87a2016-04-06 21:19:33 +00005383 if (Ordering == AtomicOrdering::NotAtomic ||
5384 Ordering == AtomicOrdering::Unordered ||
5385 Ordering == AtomicOrdering::Monotonic)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005386 return error("Invalid record");
5387 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005388 I = new FenceInst(Context, Ordering, SynchScope);
5389 InstructionList.push_back(I);
5390 break;
5391 }
Chris Lattnerc44070802011-06-17 18:17:37 +00005392 case bitc::FUNC_CODE_INST_CALL: {
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005393 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00005394 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005395 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005396
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005397 unsigned OpNum = 0;
5398 AttributeSet PAL = getAttributes(Record[OpNum++]);
5399 unsigned CCInfo = Record[OpNum++];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005400
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005401 FastMathFlags FMF;
5402 if ((CCInfo >> bitc::CALL_FMF) & 1) {
5403 FMF = getDecodedFastMathFlags(Record[OpNum++]);
5404 if (!FMF.any())
5405 return error("Fast math flags indicator set for call with no FMF");
5406 }
5407
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005408 FunctionType *FTy = nullptr;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005409 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005410 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005411 return error("Explicit call type is not a function type");
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005412
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005413 Value *Callee;
5414 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005415 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005416
Chris Lattner229907c2011-07-18 04:54:35 +00005417 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005418 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005419 return error("Callee is not a pointer type");
David Blaikie348de692015-04-23 21:36:23 +00005420 if (!FTy) {
5421 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5422 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005423 return error("Callee is not of pointer to function type");
David Blaikie348de692015-04-23 21:36:23 +00005424 } else if (OpTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005425 return error("Explicit call type does not match pointee type of "
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005426 "callee operand");
5427 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005428 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005429
Chris Lattner9f600c52007-05-03 22:04:19 +00005430 SmallVector<Value*, 16> Args;
5431 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005432 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005433 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00005434 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00005435 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00005436 Args.push_back(getValue(Record, OpNum, NextValueNo,
5437 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00005438 if (!Args.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005439 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005440 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005441
Chris Lattner9f600c52007-05-03 22:04:19 +00005442 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00005443 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005444 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005445 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005446 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005447 while (OpNum != Record.size()) {
5448 Value *Op;
5449 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005450 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005451 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00005452 }
5453 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005454
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005455 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5456 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00005457 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00005458 cast<CallInst>(I)->setCallingConv(
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005459 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
Reid Kleckner5772b772014-04-24 20:14:34 +00005460 CallInst::TailCallKind TCK = CallInst::TCK_None;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005461 if (CCInfo & 1 << bitc::CALL_TAIL)
Reid Kleckner5772b772014-04-24 20:14:34 +00005462 TCK = CallInst::TCK_Tail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005463 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
Reid Kleckner5772b772014-04-24 20:14:34 +00005464 TCK = CallInst::TCK_MustTail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005465 if (CCInfo & (1 << bitc::CALL_NOTAIL))
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005466 TCK = CallInst::TCK_NoTail;
Reid Kleckner5772b772014-04-24 20:14:34 +00005467 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00005468 cast<CallInst>(I)->setAttributes(PAL);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005469 if (FMF.any()) {
5470 if (!isa<FPMathOperator>(I))
5471 return error("Fast-math-flags specified for call without "
5472 "floating-point scalar or vector return type");
5473 I->setFastMathFlags(FMF);
5474 }
Chris Lattner9f600c52007-05-03 22:04:19 +00005475 break;
5476 }
5477 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5478 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005479 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00005480 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00005481 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00005482 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00005483 if (!OpTy || !Op || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005484 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005485 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00005486 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00005487 break;
5488 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005489
5490 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5491 // A call or an invoke can be optionally prefixed with some variable
5492 // number of operand bundle blocks. These blocks are read into
5493 // OperandBundles and consumed at the next call or invoke instruction.
5494
5495 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5496 return error("Invalid record");
5497
Sanjoy Dasf79d3442015-11-18 08:30:07 +00005498 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005499
5500 unsigned OpNum = 1;
5501 while (OpNum != Record.size()) {
5502 Value *Op;
5503 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5504 return error("Invalid record");
5505 Inputs.push_back(Op);
5506 }
5507
Sanjoy Dasf79d3442015-11-18 08:30:07 +00005508 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005509 continue;
5510 }
Chris Lattner83930552007-05-01 07:01:57 +00005511 }
5512
5513 // Add instruction to end of current BB. If there is no current BB, reject
5514 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00005515 if (!CurBB) {
Chris Lattner83930552007-05-01 07:01:57 +00005516 delete I;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005517 return error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00005518 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005519 if (!OperandBundles.empty()) {
5520 delete I;
5521 return error("Operand bundles found with no consumer");
5522 }
Chris Lattner83930552007-05-01 07:01:57 +00005523 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005524
Chris Lattner83930552007-05-01 07:01:57 +00005525 // If this was a terminator instruction, move to the next block.
5526 if (isa<TerminatorInst>(I)) {
5527 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00005528 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00005529 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005530
Chris Lattner83930552007-05-01 07:01:57 +00005531 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00005532 if (I && !I->getType()->isVoidTy())
David Majnemer8a1c45d2015-12-12 05:38:55 +00005533 ValueList.assignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00005534 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005535
Chris Lattner27d38752013-01-20 02:13:19 +00005536OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00005537
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005538 if (!OperandBundles.empty())
5539 return error("Operand bundles found with no consumer");
5540
Chris Lattner83930552007-05-01 07:01:57 +00005541 // Check the function list for unresolved values.
5542 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005543 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00005544 // We found at least one unresolved value. Nuke them all to avoid leaks.
5545 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00005546 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00005547 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00005548 delete A;
5549 }
5550 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005551 return error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00005552 }
Chris Lattner83930552007-05-01 07:01:57 +00005553 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005554
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00005555 // Unexpected unresolved metadata about to be dropped.
5556 if (MetadataList.hasFwdRefs())
5557 return error("Invalid function metadata: outgoing forward refs");
Dan Gohman9b9ff462010-08-25 20:23:38 +00005558
Chris Lattner85b7b402007-05-01 05:52:21 +00005559 // Trim the value list down to the size it was before we parsed this function.
5560 ValueList.shrinkTo(ModuleValueListSize);
Teresa Johnson61b406e2015-12-29 23:00:22 +00005561 MetadataList.shrinkTo(ModuleMetadataListSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00005562 std::vector<BasicBlock*>().swap(FunctionBBs);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005563 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00005564}
5565
Rafael Espindola7d712032013-11-05 17:16:08 +00005566/// Find the function body in the bitcode stream
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005567std::error_code BitcodeReader::findFunctionInStream(
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005568 Function *F,
5569 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005570 while (DeferredFunctionInfoIterator->second == 0) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00005571 // This is the fallback handling for the old format bitcode that
Teresa Johnson1493ad92015-10-10 14:18:36 +00005572 // didn't contain the function index in the VST, or when we have
5573 // an anonymous function which would not have a VST entry.
5574 // Assert that we have one of those two cases.
5575 assert(VSTOffset == 0 || !F->hasName());
5576 // Parse the next body in the stream and set its position in the
5577 // DeferredFunctionInfo map.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005578 if (std::error_code EC = rememberAndSkipFunctionBodies())
5579 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005580 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005581 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005582}
5583
Chris Lattner9eeada92007-05-18 04:02:46 +00005584//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005585// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00005586//===----------------------------------------------------------------------===//
5587
Rafael Espindolac3f9b5a2014-06-23 21:53:12 +00005588void BitcodeReader::releaseBuffer() { Buffer.release(); }
Chris Lattner9eeada92007-05-18 04:02:46 +00005589
Rafael Espindola5a52e6d2014-10-24 22:50:48 +00005590std::error_code BitcodeReader::materialize(GlobalValue *GV) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005591 Function *F = dyn_cast<Function>(GV);
5592 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005593 if (!F || !F->isMaterializable())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005594 return std::error_code();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005595
5596 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00005597 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005598 // If its position is recorded as 0, its body is somewhere in the stream
5599 // but we haven't seen it yet.
Rafael Espindola1c863ca2015-06-22 18:06:15 +00005600 if (DFII->second == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005601 if (std::error_code EC = findFunctionInStream(F, DFII))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005602 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005603
Duncan P. N. Exon Smith03a04a52016-04-24 15:04:28 +00005604 // Materialize metadata before parsing any function bodies.
5605 if (std::error_code EC = materializeMetadata())
5606 return EC;
5607
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005608 // Move the bit stream to the saved position of the deferred function body.
5609 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005610
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005611 if (std::error_code EC = parseFunctionBody(F))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005612 return EC;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00005613 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00005614
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00005615 if (StripDebugInfo)
5616 stripDebugInfo(*F);
5617
Chandler Carruth7132e002007-08-04 01:51:18 +00005618 // Upgrade any old intrinsic calls in the function.
Rafael Espindola86e33402015-07-02 15:55:09 +00005619 for (auto &I : UpgradedIntrinsics) {
Rafael Espindola257a3532016-01-15 19:00:20 +00005620 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5621 UI != UE;) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005622 User *U = *UI;
5623 ++UI;
5624 if (CallInst *CI = dyn_cast<CallInst>(U))
5625 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00005626 }
5627 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005628
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00005629 // Update calls to the remangled intrinsics
5630 for (auto &I : RemangledIntrinsics)
5631 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5632 UI != UE;)
5633 // Don't expect any other users than call sites
5634 CallSite(*UI++).setCalledFunction(I.second);
5635
Peter Collingbourned4bff302015-11-05 22:03:56 +00005636 // Finish fn->subprogram upgrade for materialized functions.
5637 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5638 F->setSubprogram(SP);
5639
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005640 // Bring in any functions that this function forward-referenced via
5641 // blockaddresses.
5642 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00005643}
5644
Rafael Espindola79753a02015-12-18 21:18:57 +00005645std::error_code BitcodeReader::materializeModule() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00005646 if (std::error_code EC = materializeMetadata())
5647 return EC;
5648
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005649 // Promise to materialize all forward references.
5650 WillMaterializeAllForwardRefs = true;
5651
Chris Lattner06310bf2009-06-16 05:15:21 +00005652 // Iterate over the module, deserializing any functions that are still on
5653 // disk.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00005654 for (Function &F : *TheModule) {
5655 if (std::error_code EC = materialize(&F))
Rafael Espindola246c4fb2014-11-01 16:46:18 +00005656 return EC;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005657 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00005658 // At this point, if there are any function bodies, parse the rest of
5659 // the bits in the module past the last function block we have recorded
5660 // through either lazy scanning or the VST.
5661 if (LastFunctionBlockBit || NextUnreadBit)
5662 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5663 : NextUnreadBit);
Derek Schuff92ef9752012-02-29 00:07:09 +00005664
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005665 // Check that all block address forward references got resolved (as we
5666 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00005667 if (!BasicBlockFwdRefs.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005668 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005669
Chris Bieneman671d0dd2016-03-16 23:17:54 +00005670 // Upgrading intrinsic calls before TBAA can cause TBAA metadata to be lost,
5671 // to prevent this instructions with TBAA tags should be upgraded first.
5672 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5673 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5674
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005675 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5676 // delete the old functions to clean up. We can't do this unless the entire
5677 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00005678 // with calls to the old function.
Rafael Espindola86e33402015-07-02 15:55:09 +00005679 for (auto &I : UpgradedIntrinsics) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005680 for (auto *U : I.first->users()) {
5681 if (CallInst *CI = dyn_cast<CallInst>(U))
5682 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00005683 }
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005684 if (!I.first->use_empty())
5685 I.first->replaceAllUsesWith(I.second);
5686 I.first->eraseFromParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00005687 }
Rafael Espindola4e721212015-07-02 16:22:40 +00005688 UpgradedIntrinsics.clear();
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00005689 // Do the same for remangled intrinsics
5690 for (auto &I : RemangledIntrinsics) {
5691 I.first->replaceAllUsesWith(I.second);
5692 I.first->eraseFromParent();
5693 }
5694 RemangledIntrinsics.clear();
Devang Patel80ae3492009-08-28 23:24:31 +00005695
Rafael Espindola79753a02015-12-18 21:18:57 +00005696 UpgradeDebugInfo(*TheModule);
Manman Renb5d7ff42016-05-25 23:14:48 +00005697
5698 UpgradeModuleFlags(*TheModule);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005699 return std::error_code();
Chris Lattner9eeada92007-05-18 04:02:46 +00005700}
5701
Rafael Espindola2fa1e432014-12-03 07:18:23 +00005702std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5703 return IdentifiedStructTypes;
5704}
5705
Rafael Espindola1aabf982015-06-16 23:29:49 +00005706std::error_code
5707BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
Rafael Espindola4223a1f2015-06-15 20:08:17 +00005708 if (Streamer)
Rafael Espindola1aabf982015-06-16 23:29:49 +00005709 return initLazyStream(std::move(Streamer));
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005710 return initStreamFromBuffer();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005711}
5712
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005713std::error_code BitcodeReader::initStreamFromBuffer() {
Roman Divacky4717a8d2012-09-06 15:42:13 +00005714 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005715 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5716
Rafael Espindola27435252014-07-29 21:01:24 +00005717 if (Buffer->getBufferSize() & 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005718 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005719
5720 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5721 // The magic number is 0x0B17C0DE stored in little endian.
5722 if (isBitcodeWrapper(BufPtr, BufEnd))
5723 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005724 return error("Invalid bitcode wrapper header");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005725
5726 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00005727 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005728
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005729 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005730}
5731
Rafael Espindola1aabf982015-06-16 23:29:49 +00005732std::error_code
5733BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005734 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5735 // see it.
Rafael Espindola1aabf982015-06-16 23:29:49 +00005736 auto OwnedBytes =
5737 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
Rafael Espindola7d727b52014-12-18 05:08:43 +00005738 StreamingMemoryObject &Bytes = *OwnedBytes;
Yaron Keren06d69302014-12-18 10:03:35 +00005739 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00005740 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005741
5742 unsigned char buf[16];
Rafael Espindola7d727b52014-12-18 05:08:43 +00005743 if (Bytes.readBytes(buf, 16, 0) != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005744 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005745
5746 if (!isBitcode(buf, buf + 16))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005747 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005748
5749 if (isBitcodeWrapper(buf, buf + 4)) {
5750 const unsigned char *bitcodeStart = buf;
5751 const unsigned char *bitcodeEnd = buf + 16;
5752 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
Rafael Espindola7d727b52014-12-18 05:08:43 +00005753 Bytes.dropLeadingBytes(bitcodeStart - buf);
5754 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005755 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005756 return std::error_code();
Rafael Espindola48da4f42013-11-04 16:16:24 +00005757}
5758
Teresa Johnson26ab5772016-03-15 00:04:37 +00005759std::error_code ModuleSummaryIndexBitcodeReader::error(const Twine &Message) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005760 return ::error(DiagnosticHandler,
5761 make_error_code(BitcodeError::CorruptedBitcode), Message);
5762}
5763
Teresa Johnson26ab5772016-03-15 00:04:37 +00005764ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
Mehdi Amini354f5202015-11-19 05:52:29 +00005765 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson6fb3f192016-04-22 01:52:00 +00005766 bool CheckGlobalValSummaryPresenceOnly)
Benjamin Kramer82de7d32016-05-27 14:27:24 +00005767 : DiagnosticHandler(std::move(DiagnosticHandler)), Buffer(Buffer),
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005768 CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
Teresa Johnson403a7872015-10-04 14:33:43 +00005769
Teresa Johnson26ab5772016-03-15 00:04:37 +00005770void ModuleSummaryIndexBitcodeReader::freeState() { Buffer = nullptr; }
Teresa Johnson403a7872015-10-04 14:33:43 +00005771
Teresa Johnson26ab5772016-03-15 00:04:37 +00005772void ModuleSummaryIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
Teresa Johnson403a7872015-10-04 14:33:43 +00005773
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005774std::pair<GlobalValue::GUID, GlobalValue::GUID>
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005775ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005776 auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId);
5777 assert(VGI != ValueIdToCallGraphGUIDMap.end());
5778 return VGI->second;
5779}
5780
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005781// Specialized value symbol table parser used when reading module index
Teresa Johnson28e457b2016-04-24 14:57:11 +00005782// blocks where we don't actually create global values. The parsed information
5783// is saved in the bitcode reader for use when later parsing summaries.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005784std::error_code ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005785 uint64_t Offset,
5786 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
5787 assert(Offset > 0 && "Expected non-zero VST offset");
5788 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
5789
Teresa Johnson403a7872015-10-04 14:33:43 +00005790 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5791 return error("Invalid record");
5792
5793 SmallVector<uint64_t, 64> Record;
5794
5795 // Read all the records for this value table.
5796 SmallString<128> ValueName;
5797 while (1) {
5798 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5799
5800 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005801 case BitstreamEntry::SubBlock: // Handled for us already.
5802 case BitstreamEntry::Error:
5803 return error("Malformed block");
5804 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005805 // Done parsing VST, jump back to wherever we came from.
5806 Stream.JumpToBit(CurrentBit);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005807 return std::error_code();
5808 case BitstreamEntry::Record:
5809 // The interesting case.
5810 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005811 }
5812
5813 // Read a record.
5814 Record.clear();
5815 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005816 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5817 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005818 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
5819 if (convertToString(Record, 1, ValueName))
5820 return error("Invalid record");
5821 unsigned ValueID = Record[0];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005822 assert(!SourceFileName.empty());
5823 auto VLI = ValueIdToLinkageMap.find(ValueID);
5824 assert(VLI != ValueIdToLinkageMap.end() &&
5825 "No linkage found for VST entry?");
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005826 auto Linkage = VLI->second;
5827 std::string GlobalId =
5828 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
Teresa Johnson916495d2016-04-04 18:52:58 +00005829 auto ValueGUID = GlobalValue::getGUID(GlobalId);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005830 auto OriginalNameID = ValueGUID;
5831 if (GlobalValue::isLocalLinkage(Linkage))
5832 OriginalNameID = GlobalValue::getGUID(ValueName);
Teresa Johnson916495d2016-04-04 18:52:58 +00005833 if (PrintSummaryGUIDs)
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005834 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
5835 << ValueName << "\n";
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005836 ValueIdToCallGraphGUIDMap[ValueID] =
5837 std::make_pair(ValueGUID, OriginalNameID);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005838 ValueName.clear();
5839 break;
5840 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005841 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00005842 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005843 if (convertToString(Record, 2, ValueName))
5844 return error("Invalid record");
5845 unsigned ValueID = Record[0];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005846 assert(!SourceFileName.empty());
5847 auto VLI = ValueIdToLinkageMap.find(ValueID);
5848 assert(VLI != ValueIdToLinkageMap.end() &&
5849 "No linkage found for VST entry?");
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005850 auto Linkage = VLI->second;
Teresa Johnsonb43027d2016-03-15 02:13:19 +00005851 std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier(
5852 ValueName, VLI->second, SourceFileName);
Teresa Johnson916495d2016-04-04 18:52:58 +00005853 auto FunctionGUID = GlobalValue::getGUID(FunctionGlobalId);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005854 auto OriginalNameID = FunctionGUID;
5855 if (GlobalValue::isLocalLinkage(Linkage))
5856 OriginalNameID = GlobalValue::getGUID(ValueName);
Teresa Johnson916495d2016-04-04 18:52:58 +00005857 if (PrintSummaryGUIDs)
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005858 dbgs() << "GUID " << FunctionGUID << "(" << OriginalNameID << ") is "
5859 << ValueName << "\n";
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005860 ValueIdToCallGraphGUIDMap[ValueID] =
5861 std::make_pair(FunctionGUID, OriginalNameID);
Teresa Johnson403a7872015-10-04 14:33:43 +00005862
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005863 ValueName.clear();
5864 break;
5865 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005866 case bitc::VST_CODE_COMBINED_ENTRY: {
5867 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
5868 unsigned ValueID = Record[0];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005869 GlobalValue::GUID RefGUID = Record[1];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005870 // The "original name", which is the second value of the pair will be
5871 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
5872 ValueIdToCallGraphGUIDMap[ValueID] = std::make_pair(RefGUID, RefGUID);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005873 break;
5874 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005875 }
5876 }
5877}
5878
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005879// Parse just the blocks needed for building the index out of the module.
5880// At the end of this routine the module Index is populated with a map
Teresa Johnson28e457b2016-04-24 14:57:11 +00005881// from global value id to GlobalValueSummary objects.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005882std::error_code ModuleSummaryIndexBitcodeReader::parseModule() {
Teresa Johnson403a7872015-10-04 14:33:43 +00005883 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5884 return error("Invalid record");
5885
Teresa Johnsone1164de2016-02-10 21:55:02 +00005886 SmallVector<uint64_t, 64> Record;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005887 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
5888 unsigned ValueId = 0;
Teresa Johnsone1164de2016-02-10 21:55:02 +00005889
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005890 // Read the index for this module.
Teresa Johnson403a7872015-10-04 14:33:43 +00005891 while (1) {
5892 BitstreamEntry Entry = Stream.advance();
5893
5894 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005895 case BitstreamEntry::Error:
5896 return error("Malformed block");
5897 case BitstreamEntry::EndBlock:
5898 return std::error_code();
5899
5900 case BitstreamEntry::SubBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005901 if (CheckGlobalValSummaryPresenceOnly) {
5902 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
5903 SeenGlobalValSummary = true;
Teresa Johnson6290dbc2015-11-21 21:55:48 +00005904 // No need to parse the rest since we found the summary.
5905 return std::error_code();
5906 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005907 if (Stream.SkipBlock())
5908 return error("Invalid record");
Teresa Johnson6290dbc2015-11-21 21:55:48 +00005909 continue;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005910 }
5911 switch (Entry.ID) {
5912 default: // Skip unknown content.
5913 if (Stream.SkipBlock())
5914 return error("Invalid record");
5915 break;
5916 case bitc::BLOCKINFO_BLOCK_ID:
5917 // Need to parse these to get abbrev ids (e.g. for VST)
5918 if (Stream.ReadBlockInfoBlock())
5919 return error("Malformed block");
5920 break;
5921 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005922 // Should have been parsed earlier via VSTOffset, unless there
5923 // is no summary section.
5924 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
5925 !SeenGlobalValSummary) &&
5926 "Expected early VST parse via VSTOffset record");
5927 if (Stream.SkipBlock())
5928 return error("Invalid record");
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005929 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005930 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
5931 assert(VSTOffset > 0 && "Expected non-zero VST offset");
5932 assert(!SeenValueSymbolTable &&
5933 "Already read VST when parsing summary block?");
5934 if (std::error_code EC =
5935 parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
5936 return EC;
5937 SeenValueSymbolTable = true;
5938 SeenGlobalValSummary = true;
Teresa Johnson6fb3f192016-04-22 01:52:00 +00005939 if (std::error_code EC = parseEntireSummary())
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005940 return EC;
5941 break;
5942 case bitc::MODULE_STRTAB_BLOCK_ID:
5943 if (std::error_code EC = parseModuleStringTable())
5944 return EC;
5945 break;
5946 }
5947 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00005948
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005949 case BitstreamEntry::Record: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00005950 Record.clear();
5951 auto BitCode = Stream.readRecord(Entry.ID, Record);
5952 switch (BitCode) {
5953 default:
5954 break; // Default behavior, ignore unknown content.
5955 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005956 case bitc::MODULE_CODE_SOURCE_FILENAME: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00005957 SmallString<128> ValueName;
5958 if (convertToString(Record, 0, ValueName))
5959 return error("Invalid record");
5960 SourceFileName = ValueName.c_str();
5961 break;
5962 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005963 /// MODULE_CODE_HASH: [5*i32]
5964 case bitc::MODULE_CODE_HASH: {
5965 if (Record.size() != 5)
5966 return error("Invalid hash length " + Twine(Record.size()).str());
5967 if (!TheIndex)
5968 break;
5969 if (TheIndex->modulePaths().empty())
5970 // Does not have any summary emitted.
5971 break;
5972 if (TheIndex->modulePaths().size() != 1)
5973 return error("Don't expect multiple modules defined?");
5974 auto &Hash = TheIndex->modulePaths().begin()->second.second;
5975 int Pos = 0;
5976 for (auto &Val : Record) {
5977 assert(!(Val >> 32) && "Unexpected high bits set");
5978 Hash[Pos++] = Val;
5979 }
5980 break;
5981 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005982 /// MODULE_CODE_VSTOFFSET: [offset]
5983 case bitc::MODULE_CODE_VSTOFFSET:
5984 if (Record.size() < 1)
5985 return error("Invalid record");
5986 VSTOffset = Record[0];
5987 break;
5988 // GLOBALVAR: [pointer type, isconst, initid,
5989 // linkage, alignment, section, visibility, threadlocal,
5990 // unnamed_addr, externally_initialized, dllstorageclass,
5991 // comdat]
5992 case bitc::MODULE_CODE_GLOBALVAR: {
5993 if (Record.size() < 6)
5994 return error("Invalid record");
5995 uint64_t RawLinkage = Record[3];
5996 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5997 ValueIdToLinkageMap[ValueId++] = Linkage;
5998 break;
5999 }
6000 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
6001 // alignment, section, visibility, gc, unnamed_addr,
6002 // prologuedata, dllstorageclass, comdat, prefixdata]
6003 case bitc::MODULE_CODE_FUNCTION: {
6004 if (Record.size() < 8)
6005 return error("Invalid record");
6006 uint64_t RawLinkage = Record[3];
6007 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6008 ValueIdToLinkageMap[ValueId++] = Linkage;
6009 break;
6010 }
6011 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
6012 // dllstorageclass]
6013 case bitc::MODULE_CODE_ALIAS: {
6014 if (Record.size() < 6)
6015 return error("Invalid record");
6016 uint64_t RawLinkage = Record[3];
6017 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6018 ValueIdToLinkageMap[ValueId++] = Linkage;
6019 break;
6020 }
6021 }
Teresa Johnsone1164de2016-02-10 21:55:02 +00006022 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006023 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00006024 }
6025 }
6026}
6027
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006028// Eagerly parse the entire summary block. This populates the GlobalValueSummary
6029// objects in the index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006030std::error_code ModuleSummaryIndexBitcodeReader::parseEntireSummary() {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006031 if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID))
Teresa Johnson403a7872015-10-04 14:33:43 +00006032 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00006033 SmallVector<uint64_t, 64> Record;
Mehdi Amini8fe69362016-04-24 03:18:11 +00006034
6035 // Parse version
6036 {
6037 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6038 if (Entry.Kind != BitstreamEntry::Record)
6039 return error("Invalid Summary Block: record for version expected");
6040 if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
6041 return error("Invalid Summary Block: version expected");
6042 }
6043 const uint64_t Version = Record[0];
6044 if (Version != 1)
6045 return error("Invalid summary version " + Twine(Version) + ", 1 expected");
6046 Record.clear();
6047
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006048 // Keep around the last seen summary to be used when we see an optional
6049 // "OriginalName" attachement.
6050 GlobalValueSummary *LastSeenSummary = nullptr;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006051 bool Combined = false;
Teresa Johnson403a7872015-10-04 14:33:43 +00006052 while (1) {
6053 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6054
6055 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006056 case BitstreamEntry::SubBlock: // Handled for us already.
6057 case BitstreamEntry::Error:
6058 return error("Malformed block");
6059 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006060 // For a per-module index, remove any entries that still have empty
6061 // summaries. The VST parsing creates entries eagerly for all symbols,
6062 // but not all have associated summaries (e.g. it doesn't know how to
6063 // distinguish between VST_CODE_ENTRY for function declarations vs global
6064 // variables with initializers that end up with a summary). Remove those
6065 // entries now so that we don't need to rely on the combined index merger
6066 // to clean them up (especially since that may not run for the first
6067 // module's index if we merge into that).
6068 if (!Combined)
6069 TheIndex->removeEmptySummaryEntries();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006070 return std::error_code();
6071 case BitstreamEntry::Record:
6072 // The interesting case.
6073 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00006074 }
6075
6076 // Read a record. The record format depends on whether this
6077 // is a per-module index or a combined index file. In the per-module
6078 // case the records contain the associated value's ID for correlation
6079 // with VST entries. In the combined index the correlation is done
6080 // via the bitcode offset of the summary records (which were saved
6081 // in the combined index VST entries). The records also contain
6082 // information used for ThinLTO renaming and importing.
6083 Record.clear();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006084 auto BitCode = Stream.readRecord(Entry.ID, Record);
6085 switch (BitCode) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006086 default: // Default behavior: ignore.
6087 break;
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006088 // FS_PERMODULE: [valueid, flags, instcount, numrefs, numrefs x valueid,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006089 // n x (valueid, callsitecount)]
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006090 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, numrefs,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006091 // numrefs x valueid,
6092 // n x (valueid, callsitecount, profilecount)]
6093 case bitc::FS_PERMODULE:
6094 case bitc::FS_PERMODULE_PROFILE: {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006095 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006096 uint64_t RawFlags = Record[1];
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006097 unsigned InstCount = Record[2];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006098 unsigned NumRefs = Record[3];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006099 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6100 std::unique_ptr<FunctionSummary> FS =
6101 llvm::make_unique<FunctionSummary>(Flags, InstCount);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006102 // The module path string ref set in the summary must be owned by the
6103 // index's module string table. Since we don't have a module path
6104 // string table section in the per-module index, we create a single
6105 // module path string table entry with an empty (0) ID to take
6106 // ownership.
6107 FS->setModulePath(
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006108 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006109 static int RefListStartIndex = 4;
6110 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6111 assert(Record.size() >= RefListStartIndex + NumRefs &&
6112 "Record size inconsistent with number of references");
6113 for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) {
6114 unsigned RefValueId = Record[I];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006115 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006116 FS->addRefEdge(RefGUID);
6117 }
6118 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
6119 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
6120 ++I) {
6121 unsigned CalleeValueId = Record[I];
6122 unsigned CallsiteCount = Record[++I];
6123 uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006124 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006125 FS->addCallGraphEdge(CalleeGUID,
6126 CalleeInfo(CallsiteCount, ProfileCount));
6127 }
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006128 auto GUID = getGUIDFromValueId(ValueID);
6129 FS->setOriginalName(GUID.second);
Teresa Johnson28e457b2016-04-24 14:57:11 +00006130 TheIndex->addGlobalValueSummary(GUID.first, std::move(FS));
Teresa Johnsonbbe05452016-02-24 17:57:28 +00006131 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006132 }
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006133 // FS_ALIAS: [valueid, flags, valueid]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006134 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
6135 // they expect all aliasee summaries to be available.
6136 case bitc::FS_ALIAS: {
6137 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006138 uint64_t RawFlags = Record[1];
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006139 unsigned AliaseeID = Record[2];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006140 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6141 std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006142 // The module path string ref set in the summary must be owned by the
6143 // index's module string table. Since we don't have a module path
6144 // string table section in the per-module index, we create a single
6145 // module path string table entry with an empty (0) ID to take
6146 // ownership.
6147 AS->setModulePath(
6148 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
6149
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006150 GlobalValue::GUID AliaseeGUID = getGUIDFromValueId(AliaseeID).first;
Teresa Johnson28e457b2016-04-24 14:57:11 +00006151 auto *AliaseeSummary = TheIndex->getGlobalValueSummary(AliaseeGUID);
6152 if (!AliaseeSummary)
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006153 return error("Alias expects aliasee summary to be parsed");
Teresa Johnson28e457b2016-04-24 14:57:11 +00006154 AS->setAliasee(AliaseeSummary);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006155
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006156 auto GUID = getGUIDFromValueId(ValueID);
6157 AS->setOriginalName(GUID.second);
Teresa Johnson28e457b2016-04-24 14:57:11 +00006158 TheIndex->addGlobalValueSummary(GUID.first, std::move(AS));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006159 break;
6160 }
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006161 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006162 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
6163 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006164 uint64_t RawFlags = Record[1];
6165 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006166 std::unique_ptr<GlobalVarSummary> FS =
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006167 llvm::make_unique<GlobalVarSummary>(Flags);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006168 FS->setModulePath(
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006169 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006170 for (unsigned I = 2, E = Record.size(); I != E; ++I) {
6171 unsigned RefValueId = Record[I];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006172 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006173 FS->addRefEdge(RefGUID);
6174 }
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006175 auto GUID = getGUIDFromValueId(ValueID);
6176 FS->setOriginalName(GUID.second);
Teresa Johnson28e457b2016-04-24 14:57:11 +00006177 TheIndex->addGlobalValueSummary(GUID.first, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006178 break;
6179 }
Teresa Johnson02e98332016-04-27 13:28:35 +00006180 // FS_COMBINED: [valueid, modid, flags, instcount, numrefs,
6181 // numrefs x valueid, n x (valueid, callsitecount)]
6182 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, numrefs,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006183 // numrefs x valueid,
6184 // n x (valueid, callsitecount, profilecount)]
6185 case bitc::FS_COMBINED:
6186 case bitc::FS_COMBINED_PROFILE: {
Teresa Johnson02e98332016-04-27 13:28:35 +00006187 unsigned ValueID = Record[0];
6188 uint64_t ModuleId = Record[1];
6189 uint64_t RawFlags = Record[2];
6190 unsigned InstCount = Record[3];
6191 unsigned NumRefs = Record[4];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006192 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6193 std::unique_ptr<FunctionSummary> FS =
6194 llvm::make_unique<FunctionSummary>(Flags, InstCount);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006195 LastSeenSummary = FS.get();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006196 FS->setModulePath(ModuleIdMap[ModuleId]);
Teresa Johnson02e98332016-04-27 13:28:35 +00006197 static int RefListStartIndex = 5;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006198 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6199 assert(Record.size() >= RefListStartIndex + NumRefs &&
6200 "Record size inconsistent with number of references");
Teresa Johnson02e98332016-04-27 13:28:35 +00006201 for (unsigned I = RefListStartIndex, E = CallGraphEdgeStartIndex; I != E;
6202 ++I) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006203 unsigned RefValueId = Record[I];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006204 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006205 FS->addRefEdge(RefGUID);
6206 }
6207 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
6208 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
6209 ++I) {
6210 unsigned CalleeValueId = Record[I];
6211 unsigned CallsiteCount = Record[++I];
6212 uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006213 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006214 FS->addCallGraphEdge(CalleeGUID,
6215 CalleeInfo(CallsiteCount, ProfileCount));
6216 }
Teresa Johnson02e98332016-04-27 13:28:35 +00006217 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
Teresa Johnson28e457b2016-04-24 14:57:11 +00006218 TheIndex->addGlobalValueSummary(GUID, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006219 Combined = true;
6220 break;
6221 }
Teresa Johnson02e98332016-04-27 13:28:35 +00006222 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006223 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
6224 // they expect all aliasee summaries to be available.
6225 case bitc::FS_COMBINED_ALIAS: {
Teresa Johnson02e98332016-04-27 13:28:35 +00006226 unsigned ValueID = Record[0];
6227 uint64_t ModuleId = Record[1];
6228 uint64_t RawFlags = Record[2];
6229 unsigned AliaseeValueId = Record[3];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006230 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6231 std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006232 LastSeenSummary = AS.get();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006233 AS->setModulePath(ModuleIdMap[ModuleId]);
6234
Teresa Johnson02e98332016-04-27 13:28:35 +00006235 auto AliaseeGUID = getGUIDFromValueId(AliaseeValueId).first;
6236 auto AliaseeInModule =
6237 TheIndex->findSummaryInModule(AliaseeGUID, AS->modulePath());
6238 if (!AliaseeInModule)
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006239 return error("Alias expects aliasee summary to be parsed");
Teresa Johnson02e98332016-04-27 13:28:35 +00006240 AS->setAliasee(AliaseeInModule);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006241
Teresa Johnson02e98332016-04-27 13:28:35 +00006242 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
Teresa Johnson28e457b2016-04-24 14:57:11 +00006243 TheIndex->addGlobalValueSummary(GUID, std::move(AS));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00006244 Combined = true;
6245 break;
6246 }
Teresa Johnson02e98332016-04-27 13:28:35 +00006247 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006248 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
Teresa Johnson02e98332016-04-27 13:28:35 +00006249 unsigned ValueID = Record[0];
6250 uint64_t ModuleId = Record[1];
6251 uint64_t RawFlags = Record[2];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006252 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006253 std::unique_ptr<GlobalVarSummary> FS =
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00006254 llvm::make_unique<GlobalVarSummary>(Flags);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006255 LastSeenSummary = FS.get();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006256 FS->setModulePath(ModuleIdMap[ModuleId]);
Teresa Johnson02e98332016-04-27 13:28:35 +00006257 for (unsigned I = 3, E = Record.size(); I != E; ++I) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006258 unsigned RefValueId = Record[I];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006259 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006260 FS->addRefEdge(RefGUID);
6261 }
Teresa Johnson02e98332016-04-27 13:28:35 +00006262 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
Teresa Johnson28e457b2016-04-24 14:57:11 +00006263 TheIndex->addGlobalValueSummary(GUID, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006264 Combined = true;
Teresa Johnsonbbe05452016-02-24 17:57:28 +00006265 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006266 }
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00006267 // FS_COMBINED_ORIGINAL_NAME: [original_name]
6268 case bitc::FS_COMBINED_ORIGINAL_NAME: {
6269 uint64_t OriginalName = Record[0];
6270 if (!LastSeenSummary)
6271 return error("Name attachment that does not follow a combined record");
6272 LastSeenSummary->setOriginalName(OriginalName);
6273 // Reset the LastSeenSummary
6274 LastSeenSummary = nullptr;
6275 }
Teresa Johnson403a7872015-10-04 14:33:43 +00006276 }
6277 }
6278 llvm_unreachable("Exit infinite loop");
6279}
6280
6281// Parse the module string table block into the Index.
6282// This populates the ModulePathStringTable map in the index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006283std::error_code ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
Teresa Johnson403a7872015-10-04 14:33:43 +00006284 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
6285 return error("Invalid record");
6286
6287 SmallVector<uint64_t, 64> Record;
6288
6289 SmallString<128> ModulePath;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006290 ModulePathStringTableTy::iterator LastSeenModulePath;
Teresa Johnson403a7872015-10-04 14:33:43 +00006291 while (1) {
6292 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6293
6294 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006295 case BitstreamEntry::SubBlock: // Handled for us already.
6296 case BitstreamEntry::Error:
6297 return error("Malformed block");
6298 case BitstreamEntry::EndBlock:
6299 return std::error_code();
6300 case BitstreamEntry::Record:
6301 // The interesting case.
6302 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00006303 }
6304
6305 Record.clear();
6306 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006307 default: // Default behavior: ignore.
6308 break;
6309 case bitc::MST_CODE_ENTRY: {
6310 // MST_ENTRY: [modid, namechar x N]
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006311 uint64_t ModuleId = Record[0];
6312
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006313 if (convertToString(Record, 1, ModulePath))
6314 return error("Invalid record");
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006315
6316 LastSeenModulePath = TheIndex->addModulePath(ModulePath, ModuleId);
6317 ModuleIdMap[ModuleId] = LastSeenModulePath->first();
6318
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006319 ModulePath.clear();
6320 break;
6321 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00006322 /// MST_CODE_HASH: [5*i32]
6323 case bitc::MST_CODE_HASH: {
6324 if (Record.size() != 5)
6325 return error("Invalid hash length " + Twine(Record.size()).str());
6326 if (LastSeenModulePath == TheIndex->modulePaths().end())
6327 return error("Invalid hash that does not follow a module path");
6328 int Pos = 0;
6329 for (auto &Val : Record) {
6330 assert(!(Val >> 32) && "Unexpected high bits set");
6331 LastSeenModulePath->second.second[Pos++] = Val;
6332 }
6333 // Reset LastSeenModulePath to avoid overriding the hash unexpectedly.
6334 LastSeenModulePath = TheIndex->modulePaths().end();
6335 break;
6336 }
Teresa Johnson403a7872015-10-04 14:33:43 +00006337 }
6338 }
6339 llvm_unreachable("Exit infinite loop");
6340}
6341
6342// Parse the function info index from the bitcode streamer into the given index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006343std::error_code ModuleSummaryIndexBitcodeReader::parseSummaryIndexInto(
6344 std::unique_ptr<DataStreamer> Streamer, ModuleSummaryIndex *I) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006345 TheIndex = I;
6346
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006347 if (std::error_code EC = initStream(std::move(Streamer)))
6348 return EC;
Teresa Johnson403a7872015-10-04 14:33:43 +00006349
6350 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006351 if (!hasValidBitcodeHeader(Stream))
6352 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006353
6354 // We expect a number of well-defined blocks, though we don't necessarily
6355 // need to understand them all.
6356 while (1) {
6357 if (Stream.AtEndOfStream()) {
6358 // We didn't really read a proper Module block.
6359 return error("Malformed block");
6360 }
6361
6362 BitstreamEntry Entry =
6363 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
6364
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006365 if (Entry.Kind != BitstreamEntry::SubBlock)
6366 return error("Malformed block");
Teresa Johnson403a7872015-10-04 14:33:43 +00006367
6368 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
6369 // building the function summary index.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006370 if (Entry.ID == bitc::MODULE_BLOCK_ID)
6371 return parseModule();
Teresa Johnson403a7872015-10-04 14:33:43 +00006372
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006373 if (Stream.SkipBlock())
6374 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00006375 }
6376}
6377
Teresa Johnson26ab5772016-03-15 00:04:37 +00006378std::error_code ModuleSummaryIndexBitcodeReader::initStream(
6379 std::unique_ptr<DataStreamer> Streamer) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006380 if (Streamer)
6381 return initLazyStream(std::move(Streamer));
Teresa Johnson403a7872015-10-04 14:33:43 +00006382 return initStreamFromBuffer();
6383}
6384
Teresa Johnson26ab5772016-03-15 00:04:37 +00006385std::error_code ModuleSummaryIndexBitcodeReader::initStreamFromBuffer() {
Teresa Johnson403a7872015-10-04 14:33:43 +00006386 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
6387 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
6388
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006389 if (Buffer->getBufferSize() & 3)
6390 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006391
6392 // If we have a wrapper header, parse it and ignore the non-bc file contents.
6393 // The magic number is 0x0B17C0DE stored in little endian.
6394 if (isBitcodeWrapper(BufPtr, BufEnd))
6395 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
6396 return error("Invalid bitcode wrapper header");
6397
6398 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
6399 Stream.init(&*StreamFile);
6400
6401 return std::error_code();
6402}
6403
Teresa Johnson26ab5772016-03-15 00:04:37 +00006404std::error_code ModuleSummaryIndexBitcodeReader::initLazyStream(
Teresa Johnson403a7872015-10-04 14:33:43 +00006405 std::unique_ptr<DataStreamer> Streamer) {
6406 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
6407 // see it.
6408 auto OwnedBytes =
6409 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
6410 StreamingMemoryObject &Bytes = *OwnedBytes;
6411 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
6412 Stream.init(&*StreamFile);
6413
6414 unsigned char buf[16];
6415 if (Bytes.readBytes(buf, 16, 0) != 16)
6416 return error("Invalid bitcode signature");
6417
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006418 if (!isBitcode(buf, buf + 16))
6419 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006420
6421 if (isBitcodeWrapper(buf, buf + 4)) {
6422 const unsigned char *bitcodeStart = buf;
6423 const unsigned char *bitcodeEnd = buf + 16;
6424 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
6425 Bytes.dropLeadingBytes(bitcodeStart - buf);
6426 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
6427 }
6428 return std::error_code();
6429}
6430
Rafael Espindola48da4f42013-11-04 16:16:24 +00006431namespace {
Peter Collingbourne4718f8b2016-05-24 20:13:46 +00006432// FIXME: This class is only here to support the transition to llvm::Error. It
6433// will be removed once this transition is complete. Clients should prefer to
6434// deal with the Error value directly, rather than converting to error_code.
Rafael Espindola25188c92014-06-12 01:45:43 +00006435class BitcodeErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +00006436 const char *name() const LLVM_NOEXCEPT override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00006437 return "llvm.bitcode";
6438 }
Craig Topper73156022014-03-02 09:09:27 +00006439 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006440 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00006441 switch (E) {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006442 case BitcodeError::InvalidBitcodeSignature:
Rafael Espindola48da4f42013-11-04 16:16:24 +00006443 return "Invalid bitcode signature";
Rafael Espindolad0b23be2015-01-10 00:07:30 +00006444 case BitcodeError::CorruptedBitcode:
6445 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00006446 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00006447 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00006448 }
6449};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00006450} // end anonymous namespace
Rafael Espindola48da4f42013-11-04 16:16:24 +00006451
Chris Bieneman770163e2014-09-19 20:29:02 +00006452static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
6453
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006454const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00006455 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006456}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00006457
Chris Lattner6694f602007-04-29 07:54:31 +00006458//===----------------------------------------------------------------------===//
6459// External interface
6460//===----------------------------------------------------------------------===//
6461
Rafael Espindola456baad2015-06-17 01:15:47 +00006462static ErrorOr<std::unique_ptr<Module>>
6463getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
6464 BitcodeReader *R, LLVMContext &Context,
6465 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
6466 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
6467 M->setMaterializer(R);
6468
6469 auto cleanupOnError = [&](std::error_code EC) {
6470 R->releaseBuffer(); // Never take ownership on error.
6471 return EC;
6472 };
6473
6474 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
6475 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
6476 ShouldLazyLoadMetadata))
6477 return cleanupOnError(EC);
6478
6479 if (MaterializeAll) {
6480 // Read in the entire module, and destroy the BitcodeReader.
Rafael Espindolac4a03482015-12-18 20:13:39 +00006481 if (std::error_code EC = M->materializeAll())
Rafael Espindola456baad2015-06-17 01:15:47 +00006482 return cleanupOnError(EC);
6483 } else {
6484 // Resolve forward references from blockaddresses.
6485 if (std::error_code EC = R->materializeForwardReferencedFunctions())
6486 return cleanupOnError(EC);
6487 }
6488 return std::move(M);
6489}
6490
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006491/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00006492///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006493/// This isn't always used in a lazy context. In particular, it's also used by
6494/// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
6495/// in forward-referenced functions from block address references.
6496///
Rafael Espindola728074b2015-06-17 00:40:56 +00006497/// \param[in] MaterializeAll Set to \c true if we should materialize
6498/// everything.
Rafael Espindoladcd1dca2015-06-16 22:27:55 +00006499static ErrorOr<std::unique_ptr<Module>>
Rafael Espindola68812152014-09-03 17:31:46 +00006500getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindola728074b2015-06-17 00:40:56 +00006501 LLVMContext &Context, bool MaterializeAll,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00006502 bool ShouldLazyLoadMetadata = false) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006503 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00006504
Rafael Espindola456baad2015-06-17 01:15:47 +00006505 ErrorOr<std::unique_ptr<Module>> Ret =
6506 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
6507 MaterializeAll, ShouldLazyLoadMetadata);
6508 if (!Ret)
6509 return Ret;
Rafael Espindolab7993462012-01-02 07:49:53 +00006510
Rafael Espindolae2c1d772014-08-26 22:00:09 +00006511 Buffer.release(); // The BitcodeReader owns it now.
Rafael Espindola456baad2015-06-17 01:15:47 +00006512 return Ret;
Chris Lattner6694f602007-04-29 07:54:31 +00006513}
6514
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006515ErrorOr<std::unique_ptr<Module>>
6516llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
6517 LLVMContext &Context, bool ShouldLazyLoadMetadata) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00006518 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006519 ShouldLazyLoadMetadata);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006520}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006521
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006522ErrorOr<std::unique_ptr<Module>>
6523llvm::getStreamedBitcodeModule(StringRef Name,
6524 std::unique_ptr<DataStreamer> Streamer,
6525 LLVMContext &Context) {
Rafael Espindola7d727b52014-12-18 05:08:43 +00006526 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006527 BitcodeReader *R = new BitcodeReader(Context);
Rafael Espindola456baad2015-06-17 01:15:47 +00006528
6529 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
6530 false);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006531}
6532
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006533ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
6534 LLVMContext &Context) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00006535 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006536 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
Chad Rosierca2567b2011-12-07 21:44:12 +00006537 // TODO: Restore the use-lists to the in-memory state when the bitcode was
6538 // written. We must defer until the Module has been fully materialized.
Chris Lattner6694f602007-04-29 07:54:31 +00006539}
Bill Wendling0198ce02010-10-06 01:22:42 +00006540
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006541std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
6542 LLVMContext &Context) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00006543 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006544 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00006545 ErrorOr<std::string> Triple = R->parseTriple();
Rafael Espindolad346cc82014-07-04 13:52:01 +00006546 if (Triple.getError())
6547 return "";
6548 return Triple.get();
Bill Wendling0198ce02010-10-06 01:22:42 +00006549}
Teresa Johnson403a7872015-10-04 14:33:43 +00006550
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006551std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
6552 LLVMContext &Context) {
Mehdi Amini3383ccc2015-11-09 02:46:41 +00006553 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006554 BitcodeReader R(Buf.release(), Context);
Mehdi Amini3383ccc2015-11-09 02:46:41 +00006555 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
6556 if (ProducerString.getError())
6557 return "";
6558 return ProducerString.get();
6559}
6560
Teresa Johnson403a7872015-10-04 14:33:43 +00006561// Parse the specified bitcode buffer, returning the function info index.
Benjamin Kramer1afc1de2016-06-17 20:41:14 +00006562ErrorOr<std::unique_ptr<ModuleSummaryIndex>> llvm::getModuleSummaryIndex(
6563 MemoryBufferRef Buffer,
6564 const DiagnosticHandlerFunction &DiagnosticHandler) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006565 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Teresa Johnson6fb3f192016-04-22 01:52:00 +00006566 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler);
Teresa Johnson403a7872015-10-04 14:33:43 +00006567
Teresa Johnson26ab5772016-03-15 00:04:37 +00006568 auto Index = llvm::make_unique<ModuleSummaryIndex>();
Teresa Johnson403a7872015-10-04 14:33:43 +00006569
6570 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006571 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00006572 return EC;
6573 };
6574
6575 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
6576 return cleanupOnError(EC);
6577
Teresa Johnson26ab5772016-03-15 00:04:37 +00006578 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
Teresa Johnson403a7872015-10-04 14:33:43 +00006579 return std::move(Index);
6580}
6581
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006582// Check if the given bitcode buffer contains a global value summary block.
Benjamin Kramer1afc1de2016-06-17 20:41:14 +00006583bool llvm::hasGlobalValueSummary(
6584 MemoryBufferRef Buffer,
6585 const DiagnosticHandlerFunction &DiagnosticHandler) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006586 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Teresa Johnson6fb3f192016-04-22 01:52:00 +00006587 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler, true);
Teresa Johnson403a7872015-10-04 14:33:43 +00006588
6589 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006590 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00006591 return false;
6592 };
6593
6594 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
6595 return cleanupOnError(EC);
6596
Teresa Johnson26ab5772016-03-15 00:04:37 +00006597 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006598 return R.foundGlobalValSummary();
Teresa Johnson403a7872015-10-04 14:33:43 +00006599}