blob: f8cdbcf530c094c7fb2218105b41a62f78097a2a [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
Teresa Johnsonad176792016-11-11 05:34:58 +000010#include "llvm/Bitcode/BitcodeReader.h"
Mehdi Aminief27db82016-12-12 19:34:26 +000011#include "MetadataLoader.h"
12#include "ValueList.h"
13
Eugene Zelenko1804a772016-08-25 00:45:04 +000014#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/None.h"
Benjamin Kramer0a446fd2015-03-01 21:28:53 +000019#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/SmallString.h"
21#include "llvm/ADT/SmallVector.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000022#include "llvm/ADT/StringRef.h"
David Majnemer3087b222015-01-20 05:58:07 +000023#include "llvm/ADT/Triple.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000024#include "llvm/ADT/Twine.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000025#include "llvm/Bitcode/BitstreamReader.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000026#include "llvm/Bitcode/LLVMBitCodes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000027#include "llvm/IR/Argument.h"
28#include "llvm/IR/Attributes.h"
Chandler Carruth91065212014-03-05 10:34:14 +000029#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000030#include "llvm/IR/BasicBlock.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000031#include "llvm/IR/CallSite.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000032#include "llvm/IR/CallingConv.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000033#include "llvm/IR/Comdat.h"
34#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Constants.h"
Rafael Espindola0d68b4c2015-03-30 21:36:43 +000036#include "llvm/IR/DebugInfo.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000037#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000038#include "llvm/IR/DebugLoc.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000040#include "llvm/IR/DiagnosticInfo.h"
Rafael Espindolad0b23be2015-01-10 00:07:30 +000041#include "llvm/IR/DiagnosticPrinter.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000042#include "llvm/IR/Function.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000043#include "llvm/IR/GVMaterializer.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000044#include "llvm/IR/GlobalAlias.h"
45#include "llvm/IR/GlobalIFunc.h"
46#include "llvm/IR/GlobalIndirectSymbol.h"
47#include "llvm/IR/GlobalObject.h"
48#include "llvm/IR/GlobalValue.h"
49#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000050#include "llvm/IR/InlineAsm.h"
Mehdi Amini86623052016-12-16 19:16:29 +000051#include "llvm/IR/InstIterator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000052#include "llvm/IR/InstrTypes.h"
53#include "llvm/IR/Instruction.h"
54#include "llvm/IR/Instructions.h"
55#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000056#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000057#include "llvm/IR/Module.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000058#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000059#include "llvm/IR/OperandTraits.h"
60#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000061#include "llvm/IR/TrackingMDRef.h"
62#include "llvm/IR/Type.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000063#include "llvm/IR/ValueHandle.h"
Mehdi Amini86623052016-12-16 19:16:29 +000064#include "llvm/IR/Verifier.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000065#include "llvm/Support/AtomicOrdering.h"
66#include "llvm/Support/Casting.h"
Teresa Johnson916495d2016-04-04 18:52:58 +000067#include "llvm/Support/CommandLine.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000068#include "llvm/Support/Compiler.h"
Teresa Johnson916495d2016-04-04 18:52:58 +000069#include "llvm/Support/Debug.h"
Peter Collingbourne58f7f072016-11-09 00:51:04 +000070#include "llvm/Support/Error.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000071#include "llvm/Support/ErrorHandling.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000072#include "llvm/Support/ManagedStatic.h"
Chris Lattner6694f602007-04-29 07:54:31 +000073#include "llvm/Support/MemoryBuffer.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000074#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000075#include <algorithm>
76#include <cassert>
77#include <cstddef>
78#include <cstdint>
Benjamin Kramercced8be2015-03-17 20:40:24 +000079#include <deque>
Eugene Zelenko1804a772016-08-25 00:45:04 +000080#include <limits>
81#include <map>
82#include <memory>
83#include <string>
84#include <system_error>
85#include <tuple>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000086#include <utility>
Eugene Zelenko1804a772016-08-25 00:45:04 +000087#include <vector>
Eugene Zelenko6ac3f732016-01-26 18:48:36 +000088
Chris Lattner1314b992007-04-22 06:23:29 +000089using namespace llvm;
90
Teresa Johnson916495d2016-04-04 18:52:58 +000091static cl::opt<bool> PrintSummaryGUIDs(
92 "print-summary-global-ids", cl::init(false), cl::Hidden,
93 cl::desc(
94 "Print the global id for each value when reading the module summary"));
95
Benjamin Kramercced8be2015-03-17 20:40:24 +000096namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +000097
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +000098enum {
99 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
100};
101
Peter Collingbournec0032b72016-11-11 19:50:10 +0000102Error error(const Twine &Message) {
103 return make_error<StringError>(
104 Message, make_error_code(BitcodeError::CorruptedBitcode));
105}
106
107/// Helper to read the header common to all bitcode files.
108bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
109 // Sniff for the signature.
110 if (!Stream.canSkipToPos(4) ||
111 Stream.Read(8) != 'B' ||
112 Stream.Read(8) != 'C' ||
113 Stream.Read(4) != 0x0 ||
114 Stream.Read(4) != 0xC ||
115 Stream.Read(4) != 0xE ||
116 Stream.Read(4) != 0xD)
117 return false;
118 return true;
119}
120
121Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
122 const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
123 const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
124
125 if (Buffer.getBufferSize() & 3)
126 return error("Invalid bitcode signature");
127
128 // If we have a wrapper header, parse it and ignore the non-bc file contents.
129 // The magic number is 0x0B17C0DE stored in little endian.
130 if (isBitcodeWrapper(BufPtr, BufEnd))
131 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
132 return error("Invalid bitcode wrapper header");
133
134 BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
135 if (!hasValidBitcodeHeader(Stream))
136 return error("Invalid bitcode signature");
137
138 return std::move(Stream);
139}
140
Peter Collingbournecd513a42016-11-11 19:50:24 +0000141/// Convert a string from a record into an std::string, return true on failure.
142template <typename StrTy>
143static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
144 StrTy &Result) {
145 if (Idx > Record.size())
146 return true;
147
148 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
149 Result += (char)Record[i];
150 return false;
151}
152
Mehdi Amini86623052016-12-16 19:16:29 +0000153// Strip all the TBAA attachment for the module.
154void stripTBAA(Module *M) {
155 for (auto &F : *M) {
156 if (F.isMaterializable())
157 continue;
158 for (auto &I : instructions(F))
159 I.setMetadata(LLVMContext::MD_tbaa, nullptr);
160 }
161}
162
Peter Collingbournecd513a42016-11-11 19:50:24 +0000163/// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
164/// "epoch" encoded in the bitcode, and return the producer name if any.
165Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
166 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
167 return error("Invalid record");
168
169 // Read all the records.
170 SmallVector<uint64_t, 64> Record;
171
172 std::string ProducerIdentification;
173
174 while (true) {
175 BitstreamEntry Entry = Stream.advance();
176
177 switch (Entry.Kind) {
178 default:
179 case BitstreamEntry::Error:
180 return error("Malformed block");
181 case BitstreamEntry::EndBlock:
182 return ProducerIdentification;
183 case BitstreamEntry::Record:
184 // The interesting case.
185 break;
186 }
187
188 // Read a record.
189 Record.clear();
190 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
191 switch (BitCode) {
192 default: // Default behavior: reject
193 return error("Invalid value");
194 case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
195 convertToString(Record, 0, ProducerIdentification);
196 break;
197 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
198 unsigned epoch = (unsigned)Record[0];
199 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
200 return error(
201 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
202 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
203 }
204 }
205 }
206 }
207}
208
209Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
210 // We expect a number of well-defined blocks, though we don't necessarily
211 // need to understand them all.
212 while (true) {
213 if (Stream.AtEndOfStream())
214 return "";
215
216 BitstreamEntry Entry = Stream.advance();
217 switch (Entry.Kind) {
218 case BitstreamEntry::EndBlock:
219 case BitstreamEntry::Error:
220 return error("Malformed block");
221
222 case BitstreamEntry::SubBlock:
223 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
224 return readIdentificationBlock(Stream);
225
226 // Ignore other sub-blocks.
227 if (Stream.SkipBlock())
228 return error("Malformed block");
229 continue;
230 case BitstreamEntry::Record:
231 Stream.skipRecord(Entry.ID);
232 continue;
233 }
234 }
235}
236
237Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
238 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
239 return error("Invalid record");
240
241 SmallVector<uint64_t, 64> Record;
242 // Read all the records for this module.
243
244 while (true) {
245 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
246
247 switch (Entry.Kind) {
248 case BitstreamEntry::SubBlock: // Handled for us already.
249 case BitstreamEntry::Error:
250 return error("Malformed block");
251 case BitstreamEntry::EndBlock:
252 return false;
253 case BitstreamEntry::Record:
254 // The interesting case.
255 break;
256 }
257
258 // Read a record.
259 switch (Stream.readRecord(Entry.ID, Record)) {
260 default:
261 break; // Default behavior, ignore unknown content.
262 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
263 std::string S;
264 if (convertToString(Record, 0, S))
265 return error("Invalid record");
266 // Check for the i386 and other (x86_64, ARM) conventions
267 if (S.find("__DATA, __objc_catlist") != std::string::npos ||
268 S.find("__OBJC,__category") != std::string::npos)
269 return true;
270 break;
271 }
272 }
273 Record.clear();
274 }
275 llvm_unreachable("Exit infinite loop");
276}
277
278Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
279 // We expect a number of well-defined blocks, though we don't necessarily
280 // need to understand them all.
281 while (true) {
282 BitstreamEntry Entry = Stream.advance();
283
284 switch (Entry.Kind) {
285 case BitstreamEntry::Error:
286 return error("Malformed block");
287 case BitstreamEntry::EndBlock:
288 return false;
289
290 case BitstreamEntry::SubBlock:
291 if (Entry.ID == bitc::MODULE_BLOCK_ID)
292 return hasObjCCategoryInModule(Stream);
293
294 // Ignore other sub-blocks.
295 if (Stream.SkipBlock())
296 return error("Malformed block");
297 continue;
298
299 case BitstreamEntry::Record:
300 Stream.skipRecord(Entry.ID);
301 continue;
302 }
303 }
304}
305
306Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
307 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
308 return error("Invalid record");
309
310 SmallVector<uint64_t, 64> Record;
311
312 std::string Triple;
313
314 // Read all the records for this module.
315 while (true) {
316 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
317
318 switch (Entry.Kind) {
319 case BitstreamEntry::SubBlock: // Handled for us already.
320 case BitstreamEntry::Error:
321 return error("Malformed block");
322 case BitstreamEntry::EndBlock:
323 return Triple;
324 case BitstreamEntry::Record:
325 // The interesting case.
326 break;
327 }
328
329 // Read a record.
330 switch (Stream.readRecord(Entry.ID, Record)) {
331 default: break; // Default behavior, ignore unknown content.
332 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
333 std::string S;
334 if (convertToString(Record, 0, S))
335 return error("Invalid record");
336 Triple = S;
337 break;
338 }
339 }
340 Record.clear();
341 }
342 llvm_unreachable("Exit infinite loop");
343}
344
345Expected<std::string> readTriple(BitstreamCursor &Stream) {
346 // We expect a number of well-defined blocks, though we don't necessarily
347 // need to understand them all.
348 while (true) {
349 BitstreamEntry Entry = Stream.advance();
350
351 switch (Entry.Kind) {
352 case BitstreamEntry::Error:
353 return error("Malformed block");
354 case BitstreamEntry::EndBlock:
355 return "";
356
357 case BitstreamEntry::SubBlock:
358 if (Entry.ID == bitc::MODULE_BLOCK_ID)
359 return readModuleTriple(Stream);
360
361 // Ignore other sub-blocks.
362 if (Stream.SkipBlock())
363 return error("Malformed block");
364 continue;
365
366 case BitstreamEntry::Record:
367 Stream.skipRecord(Entry.ID);
368 continue;
369 }
370 }
371}
372
Peter Collingbourne6e860752016-09-23 18:27:42 +0000373class BitcodeReaderBase {
374protected:
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000375 BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
376 : Stream(std::move(Stream)), Strtab(Strtab) {
Peter Collingbournec0032b72016-11-11 19:50:10 +0000377 this->Stream.setBlockInfo(&BlockInfo);
378 }
Peter Collingbourne6e860752016-09-23 18:27:42 +0000379
Peter Collingbourne77c89b62016-11-08 04:17:11 +0000380 BitstreamBlockInfo BlockInfo;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000381 BitstreamCursor Stream;
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000382 StringRef Strtab;
383
384 /// In version 2 of the bitcode we store names of global values and comdats in
385 /// a string table rather than in the VST.
386 bool UseStrtab = false;
Peter Collingbourne6e860752016-09-23 18:27:42 +0000387
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000388 Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
389
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000390 /// If this module uses a string table, pop the reference to the string table
391 /// and return the referenced string and the rest of the record. Otherwise
392 /// just return the record itself.
393 std::pair<StringRef, ArrayRef<uint64_t>>
394 readNameFromStrtab(ArrayRef<uint64_t> Record);
395
Peter Collingbourne939c7d92016-11-08 04:16:57 +0000396 bool readBlockInfo();
Peter Collingbourne6e860752016-09-23 18:27:42 +0000397
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000398 // Contains an arbitrary and optional string identifying the bitcode producer
399 std::string ProducerIdentification;
400
401 Error error(const Twine &Message);
Peter Collingbourne6e860752016-09-23 18:27:42 +0000402};
403
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000404Error BitcodeReaderBase::error(const Twine &Message) {
405 std::string FullMsg = Message.str();
406 if (!ProducerIdentification.empty())
407 FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
408 LLVM_VERSION_STRING "')";
Peter Collingbournec0032b72016-11-11 19:50:10 +0000409 return ::error(FullMsg);
Peter Collingbourne6e860752016-09-23 18:27:42 +0000410}
411
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000412Expected<unsigned>
413BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
414 if (Record.size() < 1)
415 return error("Invalid record");
416 unsigned ModuleVersion = Record[0];
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000417 if (ModuleVersion > 2)
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000418 return error("Invalid value");
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000419 UseStrtab = ModuleVersion >= 2;
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000420 return ModuleVersion;
421}
422
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000423std::pair<StringRef, ArrayRef<uint64_t>>
424BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
425 if (!UseStrtab)
426 return {"", Record};
427 // Invalid reference. Let the caller complain about the record being empty.
428 if (Record[0] + Record[1] > Strtab.size())
429 return {"", {}};
430 return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
431}
432
Peter Collingbourne6e860752016-09-23 18:27:42 +0000433class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
434 LLVMContext &Context;
435 Module *TheModule = nullptr;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000436 // Next offset to start scanning for lazy parsing of function bodies.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000437 uint64_t NextUnreadBit = 0;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000438 // Last function offset found in the VST.
439 uint64_t LastFunctionBlockBit = 0;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000440 bool SeenValueSymbolTable = false;
Peter Collingbourne128a9762015-10-27 23:01:25 +0000441 uint64_t VSTOffset = 0;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000442
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000443 std::vector<std::string> SectionTable;
444 std::vector<std::string> GCTable;
445
Benjamin Kramercced8be2015-03-17 20:40:24 +0000446 std::vector<Type*> TypeList;
447 BitcodeReaderValueList ValueList;
Mehdi Aminief27db82016-12-12 19:34:26 +0000448 Optional<MetadataLoader> MDLoader;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000449 std::vector<Comdat *> ComdatList;
450 SmallVector<Instruction *, 64> InstructionList;
451
452 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000453 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > IndirectSymbolInits;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000454 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
455 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
David Majnemer7fddecc2015-06-17 20:52:32 +0000456 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000457
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000458 /// The set of attributes by index. Index zero in the file is for null, and
459 /// is thus not represented here. As such all indices are off by one.
Reid Klecknerb5180542017-03-21 16:57:19 +0000460 std::vector<AttributeList> MAttributes;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000461
Karl Schimpf36440082015-08-31 16:43:55 +0000462 /// The set of attribute groups.
Reid Klecknerb5180542017-03-21 16:57:19 +0000463 std::map<unsigned, AttributeList> MAttributeGroups;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000464
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000465 /// While parsing a function body, this is a list of the basic blocks for the
466 /// function.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000467 std::vector<BasicBlock*> FunctionBBs;
468
469 // When reading the module header, this list is populated with functions that
470 // have bodies later in the file.
471 std::vector<Function*> FunctionsWithBodies;
472
473 // When intrinsic functions are encountered which require upgrading they are
474 // stored here with their replacement function.
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000475 typedef DenseMap<Function*, Function*> UpdatedIntrinsicMap;
476 UpdatedIntrinsicMap UpgradedIntrinsics;
477 // Intrinsics which were remangled because of types rename
478 UpdatedIntrinsicMap RemangledIntrinsics;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000479
Benjamin Kramercced8be2015-03-17 20:40:24 +0000480 // Several operations happen after the module header has been read, but
481 // before function bodies are processed. This keeps track of whether
482 // we've done this yet.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000483 bool SeenFirstFunctionBody = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000484
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000485 /// When function bodies are initially scanned, this map contains info about
486 /// where to find deferred function body in the stream.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000487 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
488
489 /// When Metadata block is initially scanned when parsing the module, we may
490 /// choose to defer parsing of the metadata. This vector contains info about
491 /// which Metadata blocks are deferred.
492 std::vector<uint64_t> DeferredMetadataInfo;
493
494 /// These are basic blocks forward-referenced by block addresses. They are
495 /// inserted lazily into functions when they're loaded. The basic block ID is
496 /// its index into the vector.
497 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
498 std::deque<Function *> BasicBlockFwdRefQueue;
499
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000500 /// Indicates that we are using a new encoding for instruction operands where
501 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
502 /// instruction number, for a more compact encoding. Some instruction
503 /// operands are not relative to the instruction ID: basic block numbers, and
504 /// types. Once the old style function blocks have been phased out, we would
Benjamin Kramercced8be2015-03-17 20:40:24 +0000505 /// not need this flag.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000506 bool UseRelativeIDs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000507
508 /// True if all functions will be materialized, negating the need to process
509 /// (e.g.) blockaddress forward references.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000510 bool WillMaterializeAllForwardRefs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000511
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000512 bool StripDebugInfo = false;
Mehdi Amini86623052016-12-16 19:16:29 +0000513 TBAAVerifier TBAAVerifyHelper;
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000514
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000515 std::vector<std::string> BundleTags;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000516 SmallVector<SyncScope::ID, 8> SSIDs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000517
Benjamin Kramercced8be2015-03-17 20:40:24 +0000518public:
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000519 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
520 StringRef ProducerIdentification, LLVMContext &Context);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000521
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000522 Error materializeForwardReferencedFunctions();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000523
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000524 Error materialize(GlobalValue *GV) override;
525 Error materializeModule() override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000526 std::vector<StructType *> getIdentifiedStructTypes() const override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000527
Rafael Espindola6ace6852015-06-15 21:02:49 +0000528 /// \brief Main interface to parsing a bitcode buffer.
529 /// \returns true if an error occurred.
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000530 Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false,
531 bool IsImporting = false);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000532
Benjamin Kramercced8be2015-03-17 20:40:24 +0000533 static uint64_t decodeSignRotatedValue(uint64_t V);
534
535 /// Materialize any deferred Metadata block.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000536 Error materializeMetadata() override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000537
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000538 void setStripDebugInfo() override;
539
Benjamin Kramercced8be2015-03-17 20:40:24 +0000540private:
541 std::vector<StructType *> IdentifiedStructTypes;
542 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
543 StructType *createIdentifiedStructType(LLVMContext &Context);
544
545 Type *getTypeByID(unsigned ID);
Eugene Zelenko1804a772016-08-25 00:45:04 +0000546
David Majnemer8a1c45d2015-12-12 05:38:55 +0000547 Value *getFnValueByID(unsigned ID, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000548 if (Ty && Ty->isMetadataTy())
549 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
David Majnemer8a1c45d2015-12-12 05:38:55 +0000550 return ValueList.getValueFwdRef(ID, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000551 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000552
Benjamin Kramercced8be2015-03-17 20:40:24 +0000553 Metadata *getFnMetadataByID(unsigned ID) {
Mehdi Amini3bb4d012017-01-20 20:29:16 +0000554 return MDLoader->getMetadataFwdRefOrLoad(ID);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000555 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000556
Benjamin Kramercced8be2015-03-17 20:40:24 +0000557 BasicBlock *getBasicBlock(unsigned ID) const {
558 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
559 return FunctionBBs[ID];
560 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000561
Reid Klecknerb5180542017-03-21 16:57:19 +0000562 AttributeList getAttributes(unsigned i) const {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000563 if (i-1 < MAttributes.size())
564 return MAttributes[i-1];
Reid Klecknerb5180542017-03-21 16:57:19 +0000565 return AttributeList();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000566 }
567
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000568 /// Read a value/type pair out of the specified record from slot 'Slot'.
569 /// Increment Slot past the number of slots used in the record. Return true on
570 /// failure.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000571 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
572 unsigned InstNum, Value *&ResVal) {
573 if (Slot == Record.size()) return true;
574 unsigned ValNo = (unsigned)Record[Slot++];
575 // Adjust the ValNo, if it was encoded relative to the InstNum.
576 if (UseRelativeIDs)
577 ValNo = InstNum - ValNo;
578 if (ValNo < InstNum) {
579 // If this is not a forward reference, just return the value we already
580 // have.
581 ResVal = getFnValueByID(ValNo, nullptr);
582 return ResVal == nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000583 }
David Blaikiedbe6e0f2015-04-17 06:40:14 +0000584 if (Slot == Record.size())
585 return true;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000586
587 unsigned TypeNo = (unsigned)Record[Slot++];
588 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
589 return ResVal == nullptr;
590 }
591
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000592 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
593 /// past the number of slots used by the value in the record. Return true if
594 /// there is an error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000595 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000596 unsigned InstNum, Type *Ty, Value *&ResVal) {
597 if (getValue(Record, Slot, InstNum, Ty, ResVal))
Benjamin Kramercced8be2015-03-17 20:40:24 +0000598 return true;
599 // All values currently take a single record slot.
600 ++Slot;
601 return false;
602 }
603
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000604 /// Like popValue, but does not increment the Slot number.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000605 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000606 unsigned InstNum, Type *Ty, Value *&ResVal) {
607 ResVal = getValue(Record, Slot, InstNum, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000608 return ResVal == nullptr;
609 }
610
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000611 /// Version of getValue that returns ResVal directly, or 0 if there is an
612 /// error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000613 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000614 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000615 if (Slot == Record.size()) return nullptr;
616 unsigned ValNo = (unsigned)Record[Slot];
617 // Adjust the ValNo, if it was encoded relative to the InstNum.
618 if (UseRelativeIDs)
619 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000620 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000621 }
622
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000623 /// Like getValue, but decodes signed VBRs.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000624 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000625 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000626 if (Slot == Record.size()) return nullptr;
627 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
628 // Adjust the ValNo, if it was encoded relative to the InstNum.
629 if (UseRelativeIDs)
630 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000631 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000632 }
633
634 /// Converts alignment exponent (i.e. power of two (or zero)) to the
635 /// corresponding alignment to use. If alignment is too large, returns
636 /// a corresponding error code.
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000637 Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
638 Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
639 Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false);
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000640
641 Error parseComdatRecord(ArrayRef<uint64_t> Record);
642 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
643 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
644 Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
645 ArrayRef<uint64_t> Record);
646
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000647 Error parseAttributeBlock();
648 Error parseAttributeGroupBlock();
649 Error parseTypeTable();
650 Error parseTypeTableBody();
651 Error parseOperandBundleTags();
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000652 Error parseSyncScopeNames();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000653
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000654 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
655 unsigned NameIndex, Triple &TT);
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000656 void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
657 ArrayRef<uint64_t> Record);
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000658 Error parseValueSymbolTable(uint64_t Offset = 0);
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000659 Error parseGlobalValueSymbolTable();
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000660 Error parseConstants();
661 Error rememberAndSkipFunctionBodies();
662 Error rememberAndSkipFunctionBody();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000663 /// Save the positions of the Metadata blocks and skip parsing the blocks.
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000664 Error rememberAndSkipMetadata();
665 Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
666 Error parseFunctionBody(Function *F);
667 Error globalCleanup();
668 Error resolveGlobalAndIndirectSymbolInits();
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000669 Error parseUseLists();
670 Error findFunctionInStream(
Benjamin Kramercced8be2015-03-17 20:40:24 +0000671 Function *F,
672 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000673
674 SyncScope::ID getDecodedSyncScopeID(unsigned Val);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000675};
Teresa Johnson403a7872015-10-04 14:33:43 +0000676
677/// Class to manage reading and parsing function summary index bitcode
678/// files/sections.
Peter Collingbourne6e860752016-09-23 18:27:42 +0000679class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +0000680 /// The module index built during parsing.
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +0000681 ModuleSummaryIndex &TheIndex;
Teresa Johnson403a7872015-10-04 14:33:43 +0000682
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000683 /// Indicates whether we have encountered a global value summary section
Peter Collingbournea46ec9f2016-12-01 06:00:53 +0000684 /// yet during parsing.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000685 bool SeenGlobalValSummary = false;
Teresa Johnson403a7872015-10-04 14:33:43 +0000686
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000687 /// Indicates whether we have already parsed the VST, used for error checking.
688 bool SeenValueSymbolTable = false;
689
690 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
691 /// Used to enable on-demand parsing of the VST.
692 uint64_t VSTOffset = 0;
693
Peter Collingbourne9667b912017-05-04 18:03:25 +0000694 // Map to save ValueId to ValueInfo association that was recorded in the
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000695 // ValueSymbolTable. It is used after the VST is parsed to convert
696 // call graph edges read from the function summary from referencing
Peter Collingbourne9667b912017-05-04 18:03:25 +0000697 // callees by their ValueId to using the ValueInfo instead, which is how
Teresa Johnson26ab5772016-03-15 00:04:37 +0000698 // they are recorded in the summary index being built.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000699 // We save a GUID which refers to the same global as the ValueInfo, but
700 // ignoring the linkage, i.e. for values other than local linkage they are
701 // identical.
702 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
703 ValueIdToValueInfoMap;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000704
Teresa Johnson403a7872015-10-04 14:33:43 +0000705 /// Map populated during module path string table parsing, from the
706 /// module ID to a string reference owned by the index's module
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000707 /// path string table, used to correlate with combined index
Teresa Johnson403a7872015-10-04 14:33:43 +0000708 /// summary records.
709 DenseMap<uint64_t, StringRef> ModuleIdMap;
710
Teresa Johnsone1164de2016-02-10 21:55:02 +0000711 /// Original source file name recorded in a bitcode record.
712 std::string SourceFileName;
713
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000714 /// The string identifier given to this module by the client, normally the
715 /// path to the bitcode file.
716 StringRef ModulePath;
717
718 /// For per-module summary indexes, the unique numerical identifier given to
719 /// this module by the client.
720 unsigned ModuleId;
721
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000722public:
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000723 ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab,
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000724 ModuleSummaryIndex &TheIndex,
725 StringRef ModulePath, unsigned ModuleId);
Teresa Johnson403a7872015-10-04 14:33:43 +0000726
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000727 Error parseModule();
Teresa Johnson403a7872015-10-04 14:33:43 +0000728
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000729private:
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000730 void setValueGUID(uint64_t ValueID, StringRef ValueName,
731 GlobalValue::LinkageTypes Linkage,
732 StringRef SourceFileName);
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000733 Error parseValueSymbolTable(
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000734 uint64_t Offset,
735 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000736 std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
737 std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
738 bool IsOldProfileFormat,
739 bool HasProfile);
Peter Collingbournedbd2fed2017-06-15 17:26:13 +0000740 Error parseEntireSummary(unsigned ID);
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000741 Error parseModuleStringTable();
Eugene Zelenko1804a772016-08-25 00:45:04 +0000742
Peter Collingbourne9667b912017-05-04 18:03:25 +0000743 std::pair<ValueInfo, GlobalValue::GUID>
744 getValueInfoFromValueId(unsigned ValueId);
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000745
Peter Collingbourne5aa56d22017-06-14 22:35:27 +0000746 ModuleSummaryIndex::ModuleInfo *addThisModule();
Teresa Johnson403a7872015-10-04 14:33:43 +0000747};
Eugene Zelenko1804a772016-08-25 00:45:04 +0000748
Peter Collingbournecd513a42016-11-11 19:50:24 +0000749} // end anonymous namespace
750
751std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
752 Error Err) {
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000753 if (Err) {
754 std::error_code EC;
755 handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
756 EC = EIB.convertToErrorCode();
757 Ctx.emitError(EIB.message());
758 });
759 return EC;
760 }
761 return std::error_code();
762}
763
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000764BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
Peter Collingbourne7a748032016-11-16 21:44:45 +0000765 StringRef ProducerIdentification,
766 LLVMContext &Context)
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000767 : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
Mehdi Aminief27db82016-12-12 19:34:26 +0000768 ValueList(Context) {
Peter Collingbourne7a748032016-11-16 21:44:45 +0000769 this->ProducerIdentification = ProducerIdentification;
770}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000771
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000772Error BitcodeReader::materializeForwardReferencedFunctions() {
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000773 if (WillMaterializeAllForwardRefs)
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000774 return Error::success();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000775
776 // Prevent recursion.
777 WillMaterializeAllForwardRefs = true;
778
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000779 while (!BasicBlockFwdRefQueue.empty()) {
780 Function *F = BasicBlockFwdRefQueue.front();
781 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000782 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000783 if (!BasicBlockFwdRefs.count(F))
784 // Already materialized.
785 continue;
786
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000787 // Check for a function that isn't materializable to prevent an infinite
788 // loop. When parsing a blockaddress stored in a global variable, there
789 // isn't a trivial way to check if a function will have a body without a
790 // linear search through FunctionsWithBodies, so just check it here.
791 if (!F->isMaterializable())
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000792 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000793
794 // Try to materialize F.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000795 if (Error Err = materialize(F))
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000796 return Err;
Rafael Espindolab7993462012-01-02 07:49:53 +0000797 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000798 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000799
800 // Reset state.
801 WillMaterializeAllForwardRefs = false;
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000802 return Error::success();
Rafael Espindolab7993462012-01-02 07:49:53 +0000803}
804
Chris Lattnerfee5a372007-05-04 03:30:17 +0000805//===----------------------------------------------------------------------===//
806// Helper functions to implement forward reference resolution, etc.
807//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +0000808
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000809static bool hasImplicitComdat(size_t Val) {
810 switch (Val) {
811 default:
812 return false;
813 case 1: // Old WeakAnyLinkage
814 case 4: // Old LinkOnceAnyLinkage
815 case 10: // Old WeakODRLinkage
816 case 11: // Old LinkOnceODRLinkage
817 return true;
818 }
819}
820
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000821static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000822 switch (Val) {
823 default: // Map unknown/new linkages to external
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000824 case 0:
825 return GlobalValue::ExternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000826 case 2:
827 return GlobalValue::AppendingLinkage;
828 case 3:
829 return GlobalValue::InternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000830 case 5:
831 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
832 case 6:
833 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
834 case 7:
835 return GlobalValue::ExternalWeakLinkage;
836 case 8:
837 return GlobalValue::CommonLinkage;
838 case 9:
839 return GlobalValue::PrivateLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000840 case 12:
841 return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000842 case 13:
843 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
844 case 14:
845 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Rafael Espindolabec6af62015-01-08 15:39:50 +0000846 case 15:
847 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000848 case 1: // Old value with implicit comdat.
849 case 16:
850 return GlobalValue::WeakAnyLinkage;
851 case 10: // Old value with implicit comdat.
852 case 17:
853 return GlobalValue::WeakODRLinkage;
854 case 4: // Old value with implicit comdat.
855 case 18:
856 return GlobalValue::LinkOnceAnyLinkage;
857 case 11: // Old value with implicit comdat.
858 case 19:
859 return GlobalValue::LinkOnceODRLinkage;
Chris Lattner1314b992007-04-22 06:23:29 +0000860 }
861}
862
Charles Saternos75da10d2017-08-04 16:00:58 +0000863static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
864 FunctionSummary::FFlags Flags;
865 Flags.ReadNone = RawFlags & 0x1;
866 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
867 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
868 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
869 return Flags;
870}
871
Piotr Padlewski332b3b22016-08-11 22:13:57 +0000872/// Decode the flags for GlobalValue in the summary.
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000873static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
874 uint64_t Version) {
875 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
876 // like getDecodedLinkage() above. Any future change to the linkage enum and
877 // to getDecodedLinkage() will need to be taken into account here as above.
878 auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
Mehdi Amini1380edf2017-02-03 07:41:43 +0000879 RawFlags = RawFlags >> 4;
880 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000881 // The Live flag wasn't introduced until version 3. For dead stripping
Teresa Johnson6c475a72017-01-05 21:34:18 +0000882 // to work correctly on earlier versions, we must conservatively treat all
883 // values as live.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000884 bool Live = (RawFlags & 0x2) || Version < 3;
885 return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, Live);
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000886}
887
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000888static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000889 switch (Val) {
890 default: // Map unknown visibilities to default.
891 case 0: return GlobalValue::DefaultVisibility;
892 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000893 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000894 }
895}
896
Nico Rieck7157bb72014-01-14 15:22:47 +0000897static GlobalValue::DLLStorageClassTypes
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000898getDecodedDLLStorageClass(unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000899 switch (Val) {
900 default: // Map unknown values to default.
901 case 0: return GlobalValue::DefaultStorageClass;
902 case 1: return GlobalValue::DLLImportStorageClass;
903 case 2: return GlobalValue::DLLExportStorageClass;
904 }
905}
906
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000907static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000908 switch (Val) {
909 case 0: return GlobalVariable::NotThreadLocal;
910 default: // Map unknown non-zero value to general dynamic.
911 case 1: return GlobalVariable::GeneralDynamicTLSModel;
912 case 2: return GlobalVariable::LocalDynamicTLSModel;
913 case 3: return GlobalVariable::InitialExecTLSModel;
914 case 4: return GlobalVariable::LocalExecTLSModel;
915 }
916}
917
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000918static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
919 switch (Val) {
920 default: // Map unknown to UnnamedAddr::None.
921 case 0: return GlobalVariable::UnnamedAddr::None;
922 case 1: return GlobalVariable::UnnamedAddr::Global;
923 case 2: return GlobalVariable::UnnamedAddr::Local;
924 }
925}
926
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000927static int getDecodedCastOpcode(unsigned Val) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000928 switch (Val) {
929 default: return -1;
930 case bitc::CAST_TRUNC : return Instruction::Trunc;
931 case bitc::CAST_ZEXT : return Instruction::ZExt;
932 case bitc::CAST_SEXT : return Instruction::SExt;
933 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
934 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
935 case bitc::CAST_UITOFP : return Instruction::UIToFP;
936 case bitc::CAST_SITOFP : return Instruction::SIToFP;
937 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
938 case bitc::CAST_FPEXT : return Instruction::FPExt;
939 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
940 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
941 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000942 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000943 }
944}
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000945
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000946static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000947 bool IsFP = Ty->isFPOrFPVectorTy();
948 // BinOps are only valid for int/fp or vector of int/fp types
949 if (!IsFP && !Ty->isIntOrIntVectorTy())
950 return -1;
951
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000952 switch (Val) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000953 default:
954 return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000955 case bitc::BINOP_ADD:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000956 return IsFP ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000957 case bitc::BINOP_SUB:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000958 return IsFP ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000959 case bitc::BINOP_MUL:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000960 return IsFP ? Instruction::FMul : Instruction::Mul;
961 case bitc::BINOP_UDIV:
962 return IsFP ? -1 : Instruction::UDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000963 case bitc::BINOP_SDIV:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000964 return IsFP ? Instruction::FDiv : Instruction::SDiv;
965 case bitc::BINOP_UREM:
966 return IsFP ? -1 : Instruction::URem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000967 case bitc::BINOP_SREM:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000968 return IsFP ? Instruction::FRem : Instruction::SRem;
969 case bitc::BINOP_SHL:
970 return IsFP ? -1 : Instruction::Shl;
971 case bitc::BINOP_LSHR:
972 return IsFP ? -1 : Instruction::LShr;
973 case bitc::BINOP_ASHR:
974 return IsFP ? -1 : Instruction::AShr;
975 case bitc::BINOP_AND:
976 return IsFP ? -1 : Instruction::And;
977 case bitc::BINOP_OR:
978 return IsFP ? -1 : Instruction::Or;
979 case bitc::BINOP_XOR:
980 return IsFP ? -1 : Instruction::Xor;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000981 }
982}
983
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000984static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000985 switch (Val) {
986 default: return AtomicRMWInst::BAD_BINOP;
987 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
988 case bitc::RMW_ADD: return AtomicRMWInst::Add;
989 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
990 case bitc::RMW_AND: return AtomicRMWInst::And;
991 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
992 case bitc::RMW_OR: return AtomicRMWInst::Or;
993 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
994 case bitc::RMW_MAX: return AtomicRMWInst::Max;
995 case bitc::RMW_MIN: return AtomicRMWInst::Min;
996 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
997 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
998 }
999}
1000
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001001static AtomicOrdering getDecodedOrdering(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001002 switch (Val) {
JF Bastien800f87a2016-04-06 21:19:33 +00001003 case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
1004 case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
1005 case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
1006 case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
1007 case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
1008 case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001009 default: // Map unknown orderings to sequentially-consistent.
JF Bastien800f87a2016-04-06 21:19:33 +00001010 case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001011 }
1012}
1013
David Majnemerdad0a642014-06-27 18:19:56 +00001014static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
1015 switch (Val) {
1016 default: // Map unknown selection kinds to any.
1017 case bitc::COMDAT_SELECTION_KIND_ANY:
1018 return Comdat::Any;
1019 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
1020 return Comdat::ExactMatch;
1021 case bitc::COMDAT_SELECTION_KIND_LARGEST:
1022 return Comdat::Largest;
1023 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
1024 return Comdat::NoDuplicates;
1025 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
1026 return Comdat::SameSize;
1027 }
1028}
1029
James Molloy88eb5352015-07-10 12:52:00 +00001030static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
1031 FastMathFlags FMF;
1032 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
1033 FMF.setUnsafeAlgebra();
1034 if (0 != (Val & FastMathFlags::NoNaNs))
1035 FMF.setNoNaNs();
1036 if (0 != (Val & FastMathFlags::NoInfs))
1037 FMF.setNoInfs();
1038 if (0 != (Val & FastMathFlags::NoSignedZeros))
1039 FMF.setNoSignedZeros();
1040 if (0 != (Val & FastMathFlags::AllowReciprocal))
1041 FMF.setAllowReciprocal();
Adam Nemetcd847a82017-03-28 20:11:52 +00001042 if (0 != (Val & FastMathFlags::AllowContract))
1043 FMF.setAllowContract(true);
James Molloy88eb5352015-07-10 12:52:00 +00001044 return FMF;
1045}
1046
Eugene Zelenko1804a772016-08-25 00:45:04 +00001047static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001048 switch (Val) {
1049 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
1050 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
1051 }
1052}
1053
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +00001054
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001055Type *BitcodeReader::getTypeByID(unsigned ID) {
1056 // The type table size is always specified correctly.
1057 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +00001058 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +00001059
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001060 if (Type *Ty = TypeList[ID])
1061 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001062
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001063 // If we have a forward reference, the only possible case is when it is to a
1064 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001065 return TypeList[ID] = createIdentifiedStructType(Context);
1066}
1067
1068StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1069 StringRef Name) {
1070 auto *Ret = StructType::create(Context, Name);
1071 IdentifiedStructTypes.push_back(Ret);
1072 return Ret;
1073}
1074
1075StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1076 auto *Ret = StructType::create(Context);
1077 IdentifiedStructTypes.push_back(Ret);
1078 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +00001079}
1080
Chris Lattnerfee5a372007-05-04 03:30:17 +00001081//===----------------------------------------------------------------------===//
1082// Functions for parsing blocks from the bitcode file
1083//===----------------------------------------------------------------------===//
1084
Amaury Sechet74084c42016-11-06 07:48:46 +00001085static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1086 switch (Val) {
1087 case Attribute::EndAttrKinds:
1088 llvm_unreachable("Synthetic enumerators which should never get here");
1089
1090 case Attribute::None: return 0;
1091 case Attribute::ZExt: return 1 << 0;
1092 case Attribute::SExt: return 1 << 1;
1093 case Attribute::NoReturn: return 1 << 2;
1094 case Attribute::InReg: return 1 << 3;
1095 case Attribute::StructRet: return 1 << 4;
1096 case Attribute::NoUnwind: return 1 << 5;
1097 case Attribute::NoAlias: return 1 << 6;
1098 case Attribute::ByVal: return 1 << 7;
1099 case Attribute::Nest: return 1 << 8;
1100 case Attribute::ReadNone: return 1 << 9;
1101 case Attribute::ReadOnly: return 1 << 10;
1102 case Attribute::NoInline: return 1 << 11;
1103 case Attribute::AlwaysInline: return 1 << 12;
1104 case Attribute::OptimizeForSize: return 1 << 13;
1105 case Attribute::StackProtect: return 1 << 14;
1106 case Attribute::StackProtectReq: return 1 << 15;
1107 case Attribute::Alignment: return 31 << 16;
1108 case Attribute::NoCapture: return 1 << 21;
1109 case Attribute::NoRedZone: return 1 << 22;
1110 case Attribute::NoImplicitFloat: return 1 << 23;
1111 case Attribute::Naked: return 1 << 24;
1112 case Attribute::InlineHint: return 1 << 25;
1113 case Attribute::StackAlignment: return 7 << 26;
1114 case Attribute::ReturnsTwice: return 1 << 29;
1115 case Attribute::UWTable: return 1 << 30;
1116 case Attribute::NonLazyBind: return 1U << 31;
1117 case Attribute::SanitizeAddress: return 1ULL << 32;
1118 case Attribute::MinSize: return 1ULL << 33;
1119 case Attribute::NoDuplicate: return 1ULL << 34;
1120 case Attribute::StackProtectStrong: return 1ULL << 35;
1121 case Attribute::SanitizeThread: return 1ULL << 36;
1122 case Attribute::SanitizeMemory: return 1ULL << 37;
1123 case Attribute::NoBuiltin: return 1ULL << 38;
1124 case Attribute::Returned: return 1ULL << 39;
1125 case Attribute::Cold: return 1ULL << 40;
1126 case Attribute::Builtin: return 1ULL << 41;
1127 case Attribute::OptimizeNone: return 1ULL << 42;
1128 case Attribute::InAlloca: return 1ULL << 43;
1129 case Attribute::NonNull: return 1ULL << 44;
1130 case Attribute::JumpTable: return 1ULL << 45;
1131 case Attribute::Convergent: return 1ULL << 46;
1132 case Attribute::SafeStack: return 1ULL << 47;
1133 case Attribute::NoRecurse: return 1ULL << 48;
1134 case Attribute::InaccessibleMemOnly: return 1ULL << 49;
1135 case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1136 case Attribute::SwiftSelf: return 1ULL << 51;
1137 case Attribute::SwiftError: return 1ULL << 52;
1138 case Attribute::WriteOnly: return 1ULL << 53;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001139 case Attribute::Speculatable: return 1ULL << 54;
Amaury Sechet74084c42016-11-06 07:48:46 +00001140 case Attribute::Dereferenceable:
1141 llvm_unreachable("dereferenceable attribute not supported in raw format");
1142 break;
1143 case Attribute::DereferenceableOrNull:
1144 llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
1145 "format");
1146 break;
1147 case Attribute::ArgMemOnly:
1148 llvm_unreachable("argmemonly attribute not supported in raw format");
1149 break;
1150 case Attribute::AllocSize:
1151 llvm_unreachable("allocsize not supported in raw format");
1152 break;
1153 }
1154 llvm_unreachable("Unsupported attribute type");
1155}
1156
1157static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1158 if (!Val) return;
1159
1160 for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1161 I = Attribute::AttrKind(I + 1)) {
1162 if (I == Attribute::Dereferenceable ||
1163 I == Attribute::DereferenceableOrNull ||
1164 I == Attribute::ArgMemOnly ||
1165 I == Attribute::AllocSize)
1166 continue;
1167 if (uint64_t A = (Val & getRawAttributeMask(I))) {
1168 if (I == Attribute::Alignment)
1169 B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1170 else if (I == Attribute::StackAlignment)
1171 B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1172 else
1173 B.addAttribute(I);
1174 }
1175 }
1176}
1177
Bill Wendling56aeccc2013-02-04 23:32:23 +00001178/// \brief This fills an AttrBuilder object with the LLVM attributes that have
1179/// been decoded from the given integer. This function must stay in sync with
1180/// 'encodeLLVMAttributesForBitcode'.
1181static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1182 uint64_t EncodedAttrs) {
1183 // FIXME: Remove in 4.0.
1184
1185 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1186 // the bits above 31 down by 11 bits.
1187 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1188 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1189 "Alignment must be a power of two.");
1190
1191 if (Alignment)
1192 B.addAlignmentAttr(Alignment);
Amaury Sechet74084c42016-11-06 07:48:46 +00001193 addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1194 (EncodedAttrs & 0xffff));
Bill Wendling56aeccc2013-02-04 23:32:23 +00001195}
1196
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001197Error BitcodeReader::parseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001198 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001199 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001200
Devang Patela05633e2008-09-26 22:53:05 +00001201 if (!MAttributes.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001202 return error("Invalid multiple blocks");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001203
Chris Lattnerfee5a372007-05-04 03:30:17 +00001204 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001205
Reid Klecknerb5180542017-03-21 16:57:19 +00001206 SmallVector<AttributeList, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001207
Chris Lattnerfee5a372007-05-04 03:30:17 +00001208 // Read all the records.
Eugene Zelenko1804a772016-08-25 00:45:04 +00001209 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00001210 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001211
Chris Lattner27d38752013-01-20 02:13:19 +00001212 switch (Entry.Kind) {
1213 case BitstreamEntry::SubBlock: // Handled for us already.
1214 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001215 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001216 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001217 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00001218 case BitstreamEntry::Record:
1219 // The interesting case.
1220 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001221 }
Joe Abbey97b7a172013-02-06 22:14:06 +00001222
Chris Lattnerfee5a372007-05-04 03:30:17 +00001223 // Read a record.
1224 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001225 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +00001226 default: // Default behavior: ignore.
1227 break;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001228 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1229 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +00001230 if (Record.size() & 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001231 return error("Invalid record");
Chris Lattnerfee5a372007-05-04 03:30:17 +00001232
Chris Lattnerfee5a372007-05-04 03:30:17 +00001233 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +00001234 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001235 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Reid Klecknerb5180542017-03-21 16:57:19 +00001236 Attrs.push_back(AttributeList::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +00001237 }
Devang Patela05633e2008-09-26 22:53:05 +00001238
Reid Klecknerb5180542017-03-21 16:57:19 +00001239 MAttributes.push_back(AttributeList::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +00001240 Attrs.clear();
1241 break;
1242 }
Bill Wendling0dc08912013-02-12 08:13:50 +00001243 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1244 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1245 Attrs.push_back(MAttributeGroups[Record[i]]);
1246
Reid Klecknerb5180542017-03-21 16:57:19 +00001247 MAttributes.push_back(AttributeList::get(Context, Attrs));
Bill Wendling0dc08912013-02-12 08:13:50 +00001248 Attrs.clear();
1249 break;
1250 }
Duncan Sands04eb67e2007-11-20 14:09:29 +00001251 }
Chris Lattnerfee5a372007-05-04 03:30:17 +00001252 }
1253}
1254
Reid Klecknere9f36af2013-11-12 01:31:00 +00001255// Returns Attribute::None on unrecognized codes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001256static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
Reid Klecknere9f36af2013-11-12 01:31:00 +00001257 switch (Code) {
1258 default:
1259 return Attribute::None;
1260 case bitc::ATTR_KIND_ALIGNMENT:
1261 return Attribute::Alignment;
1262 case bitc::ATTR_KIND_ALWAYS_INLINE:
1263 return Attribute::AlwaysInline;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001264 case bitc::ATTR_KIND_ARGMEMONLY:
1265 return Attribute::ArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001266 case bitc::ATTR_KIND_BUILTIN:
1267 return Attribute::Builtin;
1268 case bitc::ATTR_KIND_BY_VAL:
1269 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +00001270 case bitc::ATTR_KIND_IN_ALLOCA:
1271 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001272 case bitc::ATTR_KIND_COLD:
1273 return Attribute::Cold;
Owen Anderson85fa7d52015-05-26 23:48:40 +00001274 case bitc::ATTR_KIND_CONVERGENT:
1275 return Attribute::Convergent;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001276 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1277 return Attribute::InaccessibleMemOnly;
1278 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1279 return Attribute::InaccessibleMemOrArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001280 case bitc::ATTR_KIND_INLINE_HINT:
1281 return Attribute::InlineHint;
1282 case bitc::ATTR_KIND_IN_REG:
1283 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +00001284 case bitc::ATTR_KIND_JUMP_TABLE:
1285 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001286 case bitc::ATTR_KIND_MIN_SIZE:
1287 return Attribute::MinSize;
1288 case bitc::ATTR_KIND_NAKED:
1289 return Attribute::Naked;
1290 case bitc::ATTR_KIND_NEST:
1291 return Attribute::Nest;
1292 case bitc::ATTR_KIND_NO_ALIAS:
1293 return Attribute::NoAlias;
1294 case bitc::ATTR_KIND_NO_BUILTIN:
1295 return Attribute::NoBuiltin;
1296 case bitc::ATTR_KIND_NO_CAPTURE:
1297 return Attribute::NoCapture;
1298 case bitc::ATTR_KIND_NO_DUPLICATE:
1299 return Attribute::NoDuplicate;
1300 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1301 return Attribute::NoImplicitFloat;
1302 case bitc::ATTR_KIND_NO_INLINE:
1303 return Attribute::NoInline;
James Molloye6f87ca2015-11-06 10:32:53 +00001304 case bitc::ATTR_KIND_NO_RECURSE:
1305 return Attribute::NoRecurse;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001306 case bitc::ATTR_KIND_NON_LAZY_BIND:
1307 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001308 case bitc::ATTR_KIND_NON_NULL:
1309 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001310 case bitc::ATTR_KIND_DEREFERENCEABLE:
1311 return Attribute::Dereferenceable;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001312 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1313 return Attribute::DereferenceableOrNull;
George Burgess IV278199f2016-04-12 01:05:35 +00001314 case bitc::ATTR_KIND_ALLOC_SIZE:
1315 return Attribute::AllocSize;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001316 case bitc::ATTR_KIND_NO_RED_ZONE:
1317 return Attribute::NoRedZone;
1318 case bitc::ATTR_KIND_NO_RETURN:
1319 return Attribute::NoReturn;
1320 case bitc::ATTR_KIND_NO_UNWIND:
1321 return Attribute::NoUnwind;
1322 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1323 return Attribute::OptimizeForSize;
1324 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1325 return Attribute::OptimizeNone;
1326 case bitc::ATTR_KIND_READ_NONE:
1327 return Attribute::ReadNone;
1328 case bitc::ATTR_KIND_READ_ONLY:
1329 return Attribute::ReadOnly;
1330 case bitc::ATTR_KIND_RETURNED:
1331 return Attribute::Returned;
1332 case bitc::ATTR_KIND_RETURNS_TWICE:
1333 return Attribute::ReturnsTwice;
1334 case bitc::ATTR_KIND_S_EXT:
1335 return Attribute::SExt;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001336 case bitc::ATTR_KIND_SPECULATABLE:
1337 return Attribute::Speculatable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001338 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1339 return Attribute::StackAlignment;
1340 case bitc::ATTR_KIND_STACK_PROTECT:
1341 return Attribute::StackProtect;
1342 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1343 return Attribute::StackProtectReq;
1344 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1345 return Attribute::StackProtectStrong;
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001346 case bitc::ATTR_KIND_SAFESTACK:
1347 return Attribute::SafeStack;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001348 case bitc::ATTR_KIND_STRUCT_RET:
1349 return Attribute::StructRet;
1350 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1351 return Attribute::SanitizeAddress;
1352 case bitc::ATTR_KIND_SANITIZE_THREAD:
1353 return Attribute::SanitizeThread;
1354 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1355 return Attribute::SanitizeMemory;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001356 case bitc::ATTR_KIND_SWIFT_ERROR:
1357 return Attribute::SwiftError;
Manman Renf46262e2016-03-29 17:37:21 +00001358 case bitc::ATTR_KIND_SWIFT_SELF:
1359 return Attribute::SwiftSelf;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001360 case bitc::ATTR_KIND_UW_TABLE:
1361 return Attribute::UWTable;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001362 case bitc::ATTR_KIND_WRITEONLY:
1363 return Attribute::WriteOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001364 case bitc::ATTR_KIND_Z_EXT:
1365 return Attribute::ZExt;
1366 }
1367}
1368
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001369Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1370 unsigned &Alignment) {
JF Bastien30bf96b2015-02-22 19:32:03 +00001371 // Note: Alignment in bitcode files is incremented by 1, so that zero
1372 // can be used for default alignment.
1373 if (Exponent > Value::MaxAlignmentExponent + 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001374 return error("Invalid alignment value");
JF Bastien30bf96b2015-02-22 19:32:03 +00001375 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001376 return Error::success();
JF Bastien30bf96b2015-02-22 19:32:03 +00001377}
1378
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001379Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001380 *Kind = getAttrFromCode(Code);
Reid Klecknere9f36af2013-11-12 01:31:00 +00001381 if (*Kind == Attribute::None)
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001382 return error("Unknown attribute kind (" + Twine(Code) + ")");
1383 return Error::success();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001384}
1385
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001386Error BitcodeReader::parseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +00001387 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001388 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001389
1390 if (!MAttributeGroups.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001391 return error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +00001392
1393 SmallVector<uint64_t, 64> Record;
1394
1395 // Read all the records.
Eugene Zelenko1804a772016-08-25 00:45:04 +00001396 while (true) {
Bill Wendlingba629332013-02-10 23:24:25 +00001397 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1398
1399 switch (Entry.Kind) {
1400 case BitstreamEntry::SubBlock: // Handled for us already.
1401 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001402 return error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +00001403 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001404 return Error::success();
Bill Wendlingba629332013-02-10 23:24:25 +00001405 case BitstreamEntry::Record:
1406 // The interesting case.
1407 break;
1408 }
1409
1410 // Read a record.
1411 Record.clear();
1412 switch (Stream.readRecord(Entry.ID, Record)) {
1413 default: // Default behavior: ignore.
1414 break;
1415 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1416 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001417 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001418
Bill Wendlinge46707e2013-02-11 22:32:29 +00001419 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +00001420 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1421
1422 AttrBuilder B;
1423 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1424 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001425 Attribute::AttrKind Kind;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001426 if (Error Err = parseAttrKind(Record[++i], &Kind))
1427 return Err;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001428
1429 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +00001430 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001431 Attribute::AttrKind Kind;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001432 if (Error Err = parseAttrKind(Record[++i], &Kind))
1433 return Err;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001434 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001435 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001436 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001437 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001438 else if (Kind == Attribute::Dereferenceable)
1439 B.addDereferenceableAttr(Record[++i]);
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001440 else if (Kind == Attribute::DereferenceableOrNull)
1441 B.addDereferenceableOrNullAttr(Record[++i]);
George Burgess IV278199f2016-04-12 01:05:35 +00001442 else if (Kind == Attribute::AllocSize)
1443 B.addAllocSizeAttrFromRawRepr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +00001444 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +00001445 assert((Record[i] == 3 || Record[i] == 4) &&
1446 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +00001447 bool HasValue = (Record[i++] == 4);
1448 SmallString<64> KindStr;
1449 SmallString<64> ValStr;
1450
1451 while (Record[i] != 0 && i != e)
1452 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001453 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001454
1455 if (HasValue) {
1456 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +00001457 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +00001458 while (Record[i] != 0 && i != e)
1459 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001460 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001461 }
1462
1463 B.addAttribute(KindStr.str(), ValStr.str());
1464 }
1465 }
1466
Reid Klecknerb5180542017-03-21 16:57:19 +00001467 MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +00001468 break;
1469 }
1470 }
1471 }
1472}
1473
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001474Error BitcodeReader::parseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001475 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001476 return error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +00001477
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001478 return parseTypeTableBody();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001479}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001480
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001481Error BitcodeReader::parseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +00001482 if (!TypeList.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001483 return error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +00001484
1485 SmallVector<uint64_t, 64> Record;
1486 unsigned NumRecords = 0;
1487
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001488 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +00001489
Chris Lattner1314b992007-04-22 06:23:29 +00001490 // Read all the records for this type table.
Eugene Zelenko1804a772016-08-25 00:45:04 +00001491 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00001492 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001493
Chris Lattner27d38752013-01-20 02:13:19 +00001494 switch (Entry.Kind) {
1495 case BitstreamEntry::SubBlock: // Handled for us already.
1496 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001497 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001498 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +00001499 if (NumRecords != TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001500 return error("Malformed block");
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001501 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00001502 case BitstreamEntry::Record:
1503 // The interesting case.
1504 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001505 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001506
Chris Lattner1314b992007-04-22 06:23:29 +00001507 // Read a record.
1508 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001509 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001510 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001511 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001512 return error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +00001513 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1514 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1515 // type list. This allows us to reserve space.
1516 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001517 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001518 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001519 continue;
Chris Lattner1314b992007-04-22 06:23:29 +00001520 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +00001521 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001522 break;
Dan Gohman518cda42011-12-17 00:04:22 +00001523 case bitc::TYPE_CODE_HALF: // HALF
1524 ResultTy = Type::getHalfTy(Context);
1525 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001526 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +00001527 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001528 break;
1529 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +00001530 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001531 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001532 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +00001533 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001534 break;
1535 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001536 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001537 break;
1538 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001539 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001540 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001541 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +00001542 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001543 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001544 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +00001545 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001546 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +00001547 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1548 ResultTy = Type::getX86_MMXTy(Context);
1549 break;
David Majnemerb611e3f2015-08-14 05:09:07 +00001550 case bitc::TYPE_CODE_TOKEN: // TOKEN
1551 ResultTy = Type::getTokenTy(Context);
1552 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001553 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
Chris Lattner1314b992007-04-22 06:23:29 +00001554 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001555 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001556
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001557 uint64_t NumBits = Record[0];
1558 if (NumBits < IntegerType::MIN_INT_BITS ||
1559 NumBits > IntegerType::MAX_INT_BITS)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001560 return error("Bitwidth for integer type out of range");
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001561 ResultTy = IntegerType::get(Context, NumBits);
Chris Lattner1314b992007-04-22 06:23:29 +00001562 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001563 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001564 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001565 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +00001566 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001567 return error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001568 unsigned AddressSpace = 0;
1569 if (Record.size() == 2)
1570 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001571 ResultTy = getTypeByID(Record[0]);
Filipe Cabecinhasd8a1bcd2015-04-29 02:27:28 +00001572 if (!ResultTy ||
1573 !PointerType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001574 return error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001575 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +00001576 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001577 }
Nuno Lopes561dae02012-05-23 15:19:39 +00001578 case bitc::TYPE_CODE_FUNCTION_OLD: {
1579 // FIXME: attrid is dead, remove it in LLVM 4.0
1580 // FUNCTION: [vararg, attrid, retty, paramty x N]
1581 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001582 return error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +00001583 SmallVector<Type*, 8> ArgTys;
1584 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1585 if (Type *T = getTypeByID(Record[i]))
1586 ArgTys.push_back(T);
1587 else
1588 break;
1589 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001590
Nuno Lopes561dae02012-05-23 15:19:39 +00001591 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001592 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001593 return error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +00001594
1595 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1596 break;
1597 }
Chad Rosier95898722011-11-03 00:14:01 +00001598 case bitc::TYPE_CODE_FUNCTION: {
1599 // FUNCTION: [vararg, retty, paramty x N]
1600 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001601 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001602 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +00001603 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001604 if (Type *T = getTypeByID(Record[i])) {
1605 if (!FunctionType::isValidArgumentType(T))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001606 return error("Invalid function argument type");
Chad Rosier95898722011-11-03 00:14:01 +00001607 ArgTys.push_back(T);
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001608 }
Chad Rosier95898722011-11-03 00:14:01 +00001609 else
1610 break;
1611 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001612
Chad Rosier95898722011-11-03 00:14:01 +00001613 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001614 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001615 return error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +00001616
1617 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1618 break;
1619 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001620 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +00001621 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001622 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001623 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001624 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1625 if (Type *T = getTypeByID(Record[i]))
1626 EltTys.push_back(T);
1627 else
1628 break;
1629 }
1630 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001631 return error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001632 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001633 break;
1634 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001635 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001636 if (convertToString(Record, 0, TypeName))
1637 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001638 continue;
1639
1640 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1641 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001642 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001643
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001644 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001645 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001646
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001647 // Check to see if this was forward referenced, if so fill in the temp.
1648 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1649 if (Res) {
1650 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001651 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001652 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001653 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001654 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001655
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001656 SmallVector<Type*, 8> EltTys;
1657 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1658 if (Type *T = getTypeByID(Record[i]))
1659 EltTys.push_back(T);
1660 else
1661 break;
1662 }
1663 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001664 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001665 Res->setBody(EltTys, Record[0]);
1666 ResultTy = Res;
1667 break;
1668 }
1669 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1670 if (Record.size() != 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001671 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001672
1673 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001674 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001675
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001676 // Check to see if this was forward referenced, if so fill in the temp.
1677 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1678 if (Res) {
1679 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001680 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001681 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001682 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001683 TypeName.clear();
1684 ResultTy = Res;
1685 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001686 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001687 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1688 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001689 return error("Invalid record");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001690 ResultTy = getTypeByID(Record[1]);
1691 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001692 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001693 ResultTy = ArrayType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001694 break;
1695 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1696 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001697 return error("Invalid record");
Filipe Cabecinhas8e421902015-06-03 00:05:30 +00001698 if (Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001699 return error("Invalid vector length");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001700 ResultTy = getTypeByID(Record[1]);
1701 if (!ResultTy || !StructType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001702 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001703 ResultTy = VectorType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001704 break;
1705 }
1706
1707 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001708 return error("Invalid TYPE table");
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001709 if (TypeList[NumRecords])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001710 return error(
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001711 "Invalid TYPE table: Only named structs can be forward referenced");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001712 assert(ResultTy && "Didn't read a type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001713 TypeList[NumRecords++] = ResultTy;
1714 }
1715}
1716
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001717Error BitcodeReader::parseOperandBundleTags() {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001718 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1719 return error("Invalid record");
1720
1721 if (!BundleTags.empty())
1722 return error("Invalid multiple blocks");
1723
1724 SmallVector<uint64_t, 64> Record;
1725
Eugene Zelenko1804a772016-08-25 00:45:04 +00001726 while (true) {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001727 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1728
1729 switch (Entry.Kind) {
1730 case BitstreamEntry::SubBlock: // Handled for us already.
1731 case BitstreamEntry::Error:
1732 return error("Malformed block");
1733 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001734 return Error::success();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001735 case BitstreamEntry::Record:
1736 // The interesting case.
1737 break;
1738 }
1739
1740 // Tags are implicitly mapped to integers by their order.
1741
1742 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1743 return error("Invalid record");
1744
1745 // OPERAND_BUNDLE_TAG: [strchr x N]
1746 BundleTags.emplace_back();
1747 if (convertToString(Record, 0, BundleTags.back()))
1748 return error("Invalid record");
1749 Record.clear();
1750 }
1751}
1752
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001753Error BitcodeReader::parseSyncScopeNames() {
1754 if (Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
1755 return error("Invalid record");
1756
1757 if (!SSIDs.empty())
1758 return error("Invalid multiple synchronization scope names blocks");
1759
1760 SmallVector<uint64_t, 64> Record;
1761 while (true) {
1762 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1763 switch (Entry.Kind) {
1764 case BitstreamEntry::SubBlock: // Handled for us already.
1765 case BitstreamEntry::Error:
1766 return error("Malformed block");
1767 case BitstreamEntry::EndBlock:
1768 if (SSIDs.empty())
1769 return error("Invalid empty synchronization scope names block");
1770 return Error::success();
1771 case BitstreamEntry::Record:
1772 // The interesting case.
1773 break;
1774 }
1775
1776 // Synchronization scope names are implicitly mapped to synchronization
1777 // scope IDs by their order.
1778
1779 if (Stream.readRecord(Entry.ID, Record) != bitc::SYNC_SCOPE_NAME)
1780 return error("Invalid record");
1781
1782 SmallString<16> SSN;
1783 if (convertToString(Record, 0, SSN))
1784 return error("Invalid record");
1785
1786 SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
1787 Record.clear();
1788 }
1789}
1790
Teresa Johnsonff642b92015-09-17 20:12:00 +00001791/// Associate a value with its name from the given index in the provided record.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001792Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1793 unsigned NameIndex, Triple &TT) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001794 SmallString<128> ValueName;
1795 if (convertToString(Record, NameIndex, ValueName))
1796 return error("Invalid record");
1797 unsigned ValueID = Record[0];
1798 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1799 return error("Invalid record");
1800 Value *V = ValueList[ValueID];
1801
Filipe Cabecinhasa2b0ac42015-11-04 14:53:36 +00001802 StringRef NameStr(ValueName.data(), ValueName.size());
1803 if (NameStr.find_first_of(0) != StringRef::npos)
1804 return error("Invalid value name");
1805 V->setName(NameStr);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001806 auto *GO = dyn_cast<GlobalObject>(V);
1807 if (GO) {
1808 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1809 if (TT.isOSBinFormatMachO())
1810 GO->setComdat(nullptr);
1811 else
1812 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1813 }
1814 }
1815 return V;
1816}
1817
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001818/// Helper to note and return the current location, and jump to the given
1819/// offset.
1820static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1821 BitstreamCursor &Stream) {
1822 // Save the current parsing location so we can jump back at the end
1823 // of the VST read.
1824 uint64_t CurrentBit = Stream.GetCurrentBitNo();
1825 Stream.JumpToBit(Offset * 32);
1826#ifndef NDEBUG
1827 // Do some checking if we are in debug mode.
1828 BitstreamEntry Entry = Stream.advance();
1829 assert(Entry.Kind == BitstreamEntry::SubBlock);
1830 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1831#else
1832 // In NDEBUG mode ignore the output so we don't get an unused variable
1833 // warning.
1834 Stream.advance();
1835#endif
1836 return CurrentBit;
1837}
1838
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001839void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
1840 Function *F,
1841 ArrayRef<uint64_t> Record) {
1842 // Note that we subtract 1 here because the offset is relative to one word
1843 // before the start of the identification or module block, which was
1844 // historically always the start of the regular bitcode header.
1845 uint64_t FuncWordOffset = Record[1] - 1;
1846 uint64_t FuncBitOffset = FuncWordOffset * 32;
1847 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1848 // Set the LastFunctionBlockBit to point to the last function block.
1849 // Later when parsing is resumed after function materialization,
1850 // we can simply skip that last function block.
1851 if (FuncBitOffset > LastFunctionBlockBit)
1852 LastFunctionBlockBit = FuncBitOffset;
1853}
1854
1855/// Read a new-style GlobalValue symbol table.
1856Error BitcodeReader::parseGlobalValueSymbolTable() {
1857 unsigned FuncBitcodeOffsetDelta =
1858 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1859
1860 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1861 return error("Invalid record");
1862
1863 SmallVector<uint64_t, 64> Record;
1864 while (true) {
1865 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1866
1867 switch (Entry.Kind) {
1868 case BitstreamEntry::SubBlock:
1869 case BitstreamEntry::Error:
1870 return error("Malformed block");
1871 case BitstreamEntry::EndBlock:
1872 return Error::success();
1873 case BitstreamEntry::Record:
1874 break;
1875 }
1876
1877 Record.clear();
1878 switch (Stream.readRecord(Entry.ID, Record)) {
1879 case bitc::VST_CODE_FNENTRY: // [valueid, offset]
1880 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
1881 cast<Function>(ValueList[Record[0]]), Record);
1882 break;
1883 }
1884 }
1885}
1886
Teresa Johnsonff642b92015-09-17 20:12:00 +00001887/// Parse the value symbol table at either the current parsing location or
1888/// at the given bit offset if provided.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001889Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001890 uint64_t CurrentBit;
1891 // Pass in the Offset to distinguish between calling for the module-level
1892 // VST (where we want to jump to the VST offset) and the function-level
1893 // VST (where we don't).
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001894 if (Offset > 0) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001895 CurrentBit = jumpToValueSymbolTable(Offset, Stream);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001896 // If this module uses a string table, read this as a module-level VST.
1897 if (UseStrtab) {
1898 if (Error Err = parseGlobalValueSymbolTable())
1899 return Err;
1900 Stream.JumpToBit(CurrentBit);
1901 return Error::success();
1902 }
1903 // Otherwise, the VST will be in a similar format to a function-level VST,
1904 // and will contain symbol names.
1905 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001906
1907 // Compute the delta between the bitcode indices in the VST (the word offset
1908 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1909 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1910 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1911 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1912 // just before entering the VST subblock because: 1) the EnterSubBlock
1913 // changes the AbbrevID width; 2) the VST block is nested within the same
1914 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1915 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1916 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1917 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1918 unsigned FuncBitcodeOffsetDelta =
1919 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1920
Chris Lattner982ec1e2007-05-05 00:17:00 +00001921 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001922 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001923
1924 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001925
David Majnemer3087b222015-01-20 05:58:07 +00001926 Triple TT(TheModule->getTargetTriple());
1927
Chris Lattnerccaa4482007-04-23 21:26:05 +00001928 // Read all the records for this value table.
1929 SmallString<128> ValueName;
Eugene Zelenko1804a772016-08-25 00:45:04 +00001930
1931 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00001932 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001933
Chris Lattner27d38752013-01-20 02:13:19 +00001934 switch (Entry.Kind) {
1935 case BitstreamEntry::SubBlock: // Handled for us already.
1936 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001937 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001938 case BitstreamEntry::EndBlock:
Teresa Johnsonff642b92015-09-17 20:12:00 +00001939 if (Offset > 0)
1940 Stream.JumpToBit(CurrentBit);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001941 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00001942 case BitstreamEntry::Record:
1943 // The interesting case.
1944 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001945 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001946
Chris Lattnerccaa4482007-04-23 21:26:05 +00001947 // Read a record.
1948 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001949 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001950 default: // Default behavior: unknown type.
1951 break;
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001952 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001953 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
1954 if (Error Err = ValOrErr.takeError())
1955 return Err;
Teresa Johnsonff642b92015-09-17 20:12:00 +00001956 ValOrErr.get();
1957 break;
1958 }
1959 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001960 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001961 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
1962 if (Error Err = ValOrErr.takeError())
1963 return Err;
Teresa Johnsonff642b92015-09-17 20:12:00 +00001964 Value *V = ValOrErr.get();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001965
Peter Collingbournedb4cafa2017-04-06 19:39:24 +00001966 // Ignore function offsets emitted for aliases of functions in older
1967 // versions of LLVM.
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001968 if (auto *F = dyn_cast<Function>(V))
1969 setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
Chris Lattnerccaa4482007-04-23 21:26:05 +00001970 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00001971 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00001972 case bitc::VST_CODE_BBENTRY: {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001973 if (convertToString(Record, 1, ValueName))
1974 return error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00001975 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001976 if (!BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001977 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001978
Daniel Dunbard786b512009-07-26 00:34:27 +00001979 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00001980 ValueName.clear();
1981 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001982 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00001983 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001984 }
1985}
1986
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001987/// Decode a signed value stored with the sign bit in the LSB for dense VBR
1988/// encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00001989uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00001990 if ((V & 1) == 0)
1991 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001992 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00001993 return -(V >> 1);
1994 // There is no such thing as -0 with integers. "-0" really means MININT.
1995 return 1ULL << 63;
1996}
1997
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001998/// Resolve all of the initializers for global values and aliases that we can.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001999Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00002000 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002001 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
2002 IndirectSymbolInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002003 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002004 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
David Majnemer7fddecc2015-06-17 20:52:32 +00002005 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002006
Chris Lattner44c17072007-04-26 02:46:40 +00002007 GlobalInitWorklist.swap(GlobalInits);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002008 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002009 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002010 FunctionPrologueWorklist.swap(FunctionPrologues);
David Majnemer7fddecc2015-06-17 20:52:32 +00002011 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
Chris Lattner44c17072007-04-26 02:46:40 +00002012
2013 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00002014 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002015 if (ValID >= ValueList.size()) {
2016 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00002017 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002018 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002019 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00002020 GlobalInitWorklist.back().first->setInitializer(C);
2021 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002022 return error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00002023 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002024 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002025 }
2026
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002027 while (!IndirectSymbolInitWorklist.empty()) {
2028 unsigned ValID = IndirectSymbolInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002029 if (ValID >= ValueList.size()) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002030 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002031 } else {
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002032 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2033 if (!C)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002034 return error("Expected a constant");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002035 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2036 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002037 return error("Alias and aliasee types don't match");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002038 GIS->setIndirectSymbol(C);
Chris Lattner44c17072007-04-26 02:46:40 +00002039 }
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002040 IndirectSymbolInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002041 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002042
2043 while (!FunctionPrefixWorklist.empty()) {
2044 unsigned ValID = FunctionPrefixWorklist.back().second;
2045 if (ValID >= ValueList.size()) {
2046 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2047 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002048 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002049 FunctionPrefixWorklist.back().first->setPrefixData(C);
2050 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002051 return error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002052 }
2053 FunctionPrefixWorklist.pop_back();
2054 }
2055
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002056 while (!FunctionPrologueWorklist.empty()) {
2057 unsigned ValID = FunctionPrologueWorklist.back().second;
2058 if (ValID >= ValueList.size()) {
2059 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2060 } else {
2061 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2062 FunctionPrologueWorklist.back().first->setPrologueData(C);
2063 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002064 return error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002065 }
2066 FunctionPrologueWorklist.pop_back();
2067 }
2068
David Majnemer7fddecc2015-06-17 20:52:32 +00002069 while (!FunctionPersonalityFnWorklist.empty()) {
2070 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2071 if (ValID >= ValueList.size()) {
2072 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2073 } else {
2074 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2075 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2076 else
2077 return error("Expected a constant");
2078 }
2079 FunctionPersonalityFnWorklist.pop_back();
2080 }
2081
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002082 return Error::success();
Chris Lattner44c17072007-04-26 02:46:40 +00002083}
2084
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002085static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002086 SmallVector<uint64_t, 8> Words(Vals.size());
David Majnemer2d006e72016-08-12 04:32:42 +00002087 transform(Vals, Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00002088 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002089
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002090 return APInt(TypeBits, Words);
2091}
2092
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002093Error BitcodeReader::parseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002094 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002095 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002096
2097 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002098
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002099 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00002100 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00002101 unsigned NextCstNo = ValueList.size();
Eugene Zelenko1804a772016-08-25 00:45:04 +00002102
2103 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00002104 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002105
Chris Lattner27d38752013-01-20 02:13:19 +00002106 switch (Entry.Kind) {
2107 case BitstreamEntry::SubBlock: // Handled for us already.
2108 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002109 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002110 case BitstreamEntry::EndBlock:
2111 if (NextCstNo != ValueList.size())
George Burgess IV1030d682016-01-20 22:15:23 +00002112 return error("Invalid constant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00002113
Chris Lattner27d38752013-01-20 02:13:19 +00002114 // Once all the constants have been read, go through and resolve forward
2115 // references.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002116 ValueList.resolveConstantForwardRefs();
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002117 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00002118 case BitstreamEntry::Record:
2119 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00002120 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002121 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002122
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002123 // Read a record.
2124 Record.clear();
Filipe Cabecinhas2849b482016-06-05 18:43:17 +00002125 Type *VoidType = Type::getVoidTy(Context);
Craig Topper2617dcc2014-04-15 06:32:26 +00002126 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002127 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002128 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002129 default: // Default behavior: unknown constant
2130 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00002131 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002132 break;
2133 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2134 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002135 return error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00002136 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002137 return error("Invalid record");
Filipe Cabecinhas2849b482016-06-05 18:43:17 +00002138 if (TypeList[Record[0]] == VoidType)
2139 return error("Invalid constant type");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002140 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00002141 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002142 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00002143 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002144 break;
2145 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002146 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002147 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002148 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00002149 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00002150 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002151 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002152 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002153
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002154 APInt VInt =
2155 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002156 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002157
Chris Lattner08feb1e2007-04-24 04:04:35 +00002158 break;
2159 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002160 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00002161 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002162 return error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00002163 if (CurTy->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002164 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
Tim Northover29178a32013-01-22 09:46:31 +00002165 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00002166 else if (CurTy->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002167 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
Tim Northover29178a32013-01-22 09:46:31 +00002168 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002169 else if (CurTy->isDoubleTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002170 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
Tim Northover29178a32013-01-22 09:46:31 +00002171 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002172 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00002173 // Bits are not stored the same way as a normal i80 APInt, compensate.
2174 uint64_t Rearrange[2];
2175 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2176 Rearrange[1] = Record[0] >> 48;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002177 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
Tim Northover29178a32013-01-22 09:46:31 +00002178 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002179 } else if (CurTy->isFP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002180 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
Tim Northover29178a32013-01-22 09:46:31 +00002181 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002182 else if (CurTy->isPPC_FP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002183 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
Tim Northover29178a32013-01-22 09:46:31 +00002184 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002185 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00002186 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002187 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00002188 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002189
Chris Lattnere14cb882007-05-04 19:11:41 +00002190 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2191 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002192 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002193
Chris Lattnere14cb882007-05-04 19:11:41 +00002194 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00002195 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002196
Chris Lattner229907c2011-07-18 04:54:35 +00002197 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00002198 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002199 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00002200 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00002201 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002202 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2203 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002204 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002205 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00002206 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002207 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2208 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002209 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002210 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00002211 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00002212 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002213 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00002214 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002215 break;
2216 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002217 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00002218 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2219 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002220 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002221
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002222 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002223 V = ConstantDataArray::getString(Context, Elts,
2224 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00002225 break;
2226 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002227 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2228 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002229 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002230
Chris Lattner372dd1e2012-01-30 00:51:16 +00002231 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
Chris Lattner372dd1e2012-01-30 00:51:16 +00002232 if (EltTy->isIntegerTy(8)) {
2233 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2234 if (isa<VectorType>(CurTy))
2235 V = ConstantDataVector::get(Context, Elts);
2236 else
2237 V = ConstantDataArray::get(Context, Elts);
2238 } else if (EltTy->isIntegerTy(16)) {
2239 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2240 if (isa<VectorType>(CurTy))
2241 V = ConstantDataVector::get(Context, Elts);
2242 else
2243 V = ConstantDataArray::get(Context, Elts);
2244 } else if (EltTy->isIntegerTy(32)) {
2245 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2246 if (isa<VectorType>(CurTy))
2247 V = ConstantDataVector::get(Context, Elts);
2248 else
2249 V = ConstantDataArray::get(Context, Elts);
2250 } else if (EltTy->isIntegerTy(64)) {
2251 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2252 if (isa<VectorType>(CurTy))
2253 V = ConstantDataVector::get(Context, Elts);
2254 else
2255 V = ConstantDataArray::get(Context, Elts);
Justin Bognera43eacb2016-01-06 22:31:32 +00002256 } else if (EltTy->isHalfTy()) {
2257 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2258 if (isa<VectorType>(CurTy))
2259 V = ConstantDataVector::getFP(Context, Elts);
2260 else
2261 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002262 } else if (EltTy->isFloatTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00002263 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002264 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00002265 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002266 else
Justin Bognera43eacb2016-01-06 22:31:32 +00002267 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002268 } else if (EltTy->isDoubleTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00002269 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002270 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00002271 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002272 else
Justin Bognera43eacb2016-01-06 22:31:32 +00002273 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002274 } else {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002275 return error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00002276 }
2277 break;
2278 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002279 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002280 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002281 return error("Invalid record");
2282 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002283 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002284 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00002285 } else {
2286 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2287 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00002288 unsigned Flags = 0;
2289 if (Record.size() >= 4) {
2290 if (Opc == Instruction::Add ||
2291 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002292 Opc == Instruction::Mul ||
2293 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00002294 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2295 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2296 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2297 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002298 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002299 Opc == Instruction::UDiv ||
2300 Opc == Instruction::LShr ||
2301 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00002302 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00002303 Flags |= SDivOperator::IsExact;
2304 }
2305 }
2306 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00002307 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002308 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002309 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002310 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002311 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002312 return error("Invalid record");
2313 int Opc = getDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00002314 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002315 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00002316 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002317 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002318 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002319 return error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00002320 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002321 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2322 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002323 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002324 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002325 }
Peter Collingbourned93620b2016-11-10 22:34:55 +00002326 case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2327 case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2328 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2329 // operands]
David Blaikieb9263572015-03-13 21:03:36 +00002330 unsigned OpNum = 0;
2331 Type *PointeeType = nullptr;
Peter Collingbourned93620b2016-11-10 22:34:55 +00002332 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
2333 Record.size() % 2)
David Blaikieb9263572015-03-13 21:03:36 +00002334 PointeeType = getTypeByID(Record[OpNum++]);
Peter Collingbourned93620b2016-11-10 22:34:55 +00002335
2336 bool InBounds = false;
2337 Optional<unsigned> InRangeIndex;
2338 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
2339 uint64_t Op = Record[OpNum++];
2340 InBounds = Op & 1;
2341 InRangeIndex = Op >> 1;
2342 } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2343 InBounds = true;
2344
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002345 SmallVector<Constant*, 16> Elts;
David Blaikieb9263572015-03-13 21:03:36 +00002346 while (OpNum != Record.size()) {
2347 Type *ElTy = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002348 if (!ElTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002349 return error("Invalid record");
David Blaikieb9263572015-03-13 21:03:36 +00002350 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002351 }
David Blaikieb9263572015-03-13 21:03:36 +00002352
David Blaikieb9263572015-03-13 21:03:36 +00002353 if (PointeeType &&
David Blaikie4a2e73b2015-04-02 18:55:32 +00002354 PointeeType !=
Peter Collingbourne9ef5a8c2016-11-13 06:59:28 +00002355 cast<PointerType>(Elts[0]->getType()->getScalarType())
David Blaikie4a2e73b2015-04-02 18:55:32 +00002356 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002357 return error("Explicit gep operator type does not match pointee type "
David Blaikie12cf5d702015-03-16 22:03:50 +00002358 "of pointer operand");
David Blaikie4a2e73b2015-04-02 18:55:32 +00002359
Filipe Cabecinhasfc2a3c92016-06-05 18:43:26 +00002360 if (Elts.size() < 1)
2361 return error("Invalid gep with no operands");
2362
David Blaikie4a2e73b2015-04-02 18:55:32 +00002363 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2364 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
Peter Collingbourned93620b2016-11-10 22:34:55 +00002365 InBounds, InRangeIndex);
Chris Lattner890683d2007-04-24 18:15:21 +00002366 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002367 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00002368 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002369 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002370 return error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00002371
2372 Type *SelectorTy = Type::getInt1Ty(Context);
2373
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00002374 // The selector might be an i1 or an <n x i1>
2375 // Get the type from the ValueList before getting a forward ref.
Joe Abbey1a6e7702013-09-12 22:02:31 +00002376 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00002377 if (Value *V = ValueList[Record[0]])
2378 if (SelectorTy != V->getType())
2379 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
Joe Abbey1a6e7702013-09-12 22:02:31 +00002380
2381 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2382 SelectorTy),
2383 ValueList.getConstantFwdRef(Record[1],CurTy),
2384 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002385 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00002386 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002387 case bitc::CST_CODE_CE_EXTRACTELT
2388 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002389 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002390 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002391 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002392 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002393 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002394 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002395 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002396 Constant *Op1 = nullptr;
2397 if (Record.size() == 4) {
2398 Type *IdxTy = getTypeByID(Record[2]);
2399 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002400 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002401 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2402 } else // TODO: Remove with llvm 4.0
2403 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2404 if (!Op1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002405 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002406 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002407 break;
2408 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002409 case bitc::CST_CODE_CE_INSERTELT
2410 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002411 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002412 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002413 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002414 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2415 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2416 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002417 Constant *Op2 = nullptr;
2418 if (Record.size() == 4) {
2419 Type *IdxTy = getTypeByID(Record[2]);
2420 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002421 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002422 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2423 } else // TODO: Remove with llvm 4.0
2424 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2425 if (!Op2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002426 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002427 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002428 break;
2429 }
2430 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002431 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002432 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002433 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002434 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2435 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002436 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002437 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002438 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002439 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002440 break;
2441 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00002442 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002443 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2444 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00002445 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002446 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002447 return error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002448 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2449 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002450 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002451 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00002452 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002453 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00002454 break;
2455 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002456 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002457 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002458 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002459 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002460 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002461 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002462 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2463 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2464
Duncan Sands9dff9be2010-02-15 16:12:20 +00002465 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002466 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00002467 else
Owen Anderson487375e2009-07-29 18:55:55 +00002468 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002469 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00002470 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002471 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00002472 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002473 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002474 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002475 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002476 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00002477 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002478 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002479 unsigned AsmStrSize = Record[1];
2480 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002481 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002482 unsigned ConstStrSize = Record[2+AsmStrSize];
2483 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002484 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002485
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002486 for (unsigned i = 0; i != AsmStrSize; ++i)
2487 AsmStr += (char)Record[2+i];
2488 for (unsigned i = 0; i != ConstStrSize; ++i)
2489 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00002490 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002491 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002492 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002493 break;
2494 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002495 // This version adds support for the asm dialect keywords (e.g.,
2496 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002497 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002498 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002499 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002500 std::string AsmStr, ConstrStr;
2501 bool HasSideEffects = Record[0] & 1;
2502 bool IsAlignStack = (Record[0] >> 1) & 1;
2503 unsigned AsmDialect = Record[0] >> 2;
2504 unsigned AsmStrSize = Record[1];
2505 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002506 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002507 unsigned ConstStrSize = Record[2+AsmStrSize];
2508 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002509 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002510
2511 for (unsigned i = 0; i != AsmStrSize; ++i)
2512 AsmStr += (char)Record[2+i];
2513 for (unsigned i = 0; i != ConstStrSize; ++i)
2514 ConstrStr += (char)Record[3+AsmStrSize+i];
2515 PointerType *PTy = cast<PointerType>(CurTy);
2516 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2517 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00002518 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002519 break;
2520 }
Chris Lattner5956dc82009-10-28 05:53:48 +00002521 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00002522 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002523 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002524 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002525 if (!FnTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002526 return error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00002527 Function *Fn =
2528 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00002529 if (!Fn)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002530 return error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002531
2532 // If the function is already parsed we can insert the block address right
2533 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002534 BasicBlock *BB;
2535 unsigned BBID = Record[2];
2536 if (!BBID)
2537 // Invalid reference to entry block.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002538 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002539 if (!Fn->empty()) {
2540 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002541 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002542 if (BBI == BBE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002543 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002544 ++BBI;
2545 }
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00002546 BB = &*BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002547 } else {
2548 // Otherwise insert a placeholder and remember it so it can be inserted
2549 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00002550 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2551 if (FwdBBs.empty())
2552 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00002553 if (FwdBBs.size() < BBID + 1)
2554 FwdBBs.resize(BBID + 1);
2555 if (!FwdBBs[BBID])
2556 FwdBBs[BBID] = BasicBlock::Create(Context);
2557 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002558 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002559 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00002560 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002561 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002562 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002563
David Majnemer8a1c45d2015-12-12 05:38:55 +00002564 ValueList.assignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00002565 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002566 }
2567}
Chris Lattner1314b992007-04-22 06:23:29 +00002568
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002569Error BitcodeReader::parseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00002570 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002571 return error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00002572
Chad Rosierca2567b2011-12-07 21:44:12 +00002573 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002574 SmallVector<uint64_t, 64> Record;
Eugene Zelenko1804a772016-08-25 00:45:04 +00002575
2576 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00002577 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002578
Chris Lattner27d38752013-01-20 02:13:19 +00002579 switch (Entry.Kind) {
2580 case BitstreamEntry::SubBlock: // Handled for us already.
2581 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002582 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002583 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002584 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00002585 case BitstreamEntry::Record:
2586 // The interesting case.
2587 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00002588 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002589
Chad Rosierca2567b2011-12-07 21:44:12 +00002590 // Read a use list record.
2591 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002592 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00002593 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00002594 default: // Default behavior: unknown type.
2595 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002596 case bitc::USELIST_CODE_BB:
2597 IsBB = true;
Justin Bognerb03fd122016-08-17 05:10:15 +00002598 LLVM_FALLTHROUGH;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002599 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00002600 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002601 if (RecordLength < 3)
2602 // Records should have at least an ID and two indexes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002603 return error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002604 unsigned ID = Record.back();
2605 Record.pop_back();
2606
2607 Value *V;
2608 if (IsBB) {
2609 assert(ID < FunctionBBs.size() && "Basic block not found");
2610 V = FunctionBBs[ID];
2611 } else
2612 V = ValueList[ID];
2613 unsigned NumUses = 0;
2614 SmallDenseMap<const Use *, unsigned, 16> Order;
Rafael Espindola257a3532016-01-15 19:00:20 +00002615 for (const Use &U : V->materialized_uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00002616 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002617 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00002618 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002619 }
2620 if (Order.size() != Record.size() || NumUses > Record.size())
2621 // Mismatches can happen if the functions are being materialized lazily
2622 // (out-of-order), or a value has been upgraded.
2623 break;
2624
2625 V->sortUseList([&](const Use &L, const Use &R) {
2626 return Order.lookup(&L) < Order.lookup(&R);
2627 });
Chad Rosierca2567b2011-12-07 21:44:12 +00002628 break;
2629 }
2630 }
2631 }
2632}
2633
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002634/// When we see the block for metadata, remember where it is and then skip it.
2635/// This lets us lazily deserialize the metadata.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002636Error BitcodeReader::rememberAndSkipMetadata() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002637 // Save the current stream state.
2638 uint64_t CurBit = Stream.GetCurrentBitNo();
2639 DeferredMetadataInfo.push_back(CurBit);
2640
2641 // Skip over the block for now.
2642 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002643 return error("Invalid record");
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002644 return Error::success();
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002645}
2646
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00002647Error BitcodeReader::materializeMetadata() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002648 for (uint64_t BitPos : DeferredMetadataInfo) {
2649 // Move the bit stream to the saved position.
2650 Stream.JumpToBit(BitPos);
Mehdi Aminief27db82016-12-12 19:34:26 +00002651 if (Error Err = MDLoader->parseModuleMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002652 return Err;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002653 }
Peter Collingbourne89061b22017-06-12 20:10:48 +00002654
2655 // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
2656 // metadata.
2657 if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
2658 NamedMDNode *LinkerOpts =
2659 TheModule->getOrInsertNamedMetadata("llvm.linker.options");
2660 for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
2661 LinkerOpts->addOperand(cast<MDNode>(MDOptions));
2662 }
2663
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002664 DeferredMetadataInfo.clear();
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002665 return Error::success();
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002666}
2667
Rafael Espindola468b8682015-04-01 14:44:59 +00002668void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00002669
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002670/// When we see the block for a function body, remember where it is and then
2671/// skip it. This lets us lazily deserialize the functions.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002672Error BitcodeReader::rememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002673 // Get the function we are talking about.
2674 if (FunctionsWithBodies.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002675 return error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002676
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002677 Function *Fn = FunctionsWithBodies.back();
2678 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002679
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002680 // Save the current stream state.
2681 uint64_t CurBit = Stream.GetCurrentBitNo();
Teresa Johnson1493ad92015-10-10 14:18:36 +00002682 assert(
2683 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
2684 "Mismatch between VST and scanned function offsets");
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00002685 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002686
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002687 // Skip over the function block for now.
2688 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002689 return error("Invalid record");
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002690 return Error::success();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002691}
2692
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002693Error BitcodeReader::globalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002694 // Patch the initializers for globals and aliases up.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002695 if (Error Err = resolveGlobalAndIndirectSymbolInits())
2696 return Err;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002697 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002698 return error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002699
2700 // Look for intrinsic functions which need to be upgraded at some point
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002701 for (Function &F : *TheModule) {
Adrian Prantl6825fb62017-04-18 01:21:53 +00002702 MDLoader->upgradeDebugIntrinsics(F);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002703 Function *NewFn;
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002704 if (UpgradeIntrinsicFunction(&F, NewFn))
Rafael Espindola4e721212015-07-02 16:22:40 +00002705 UpgradedIntrinsics[&F] = NewFn;
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00002706 else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
2707 // Some types could be renamed during loading if several modules are
2708 // loaded in the same LLVMContext (LTO scenario). In this case we should
2709 // remangle intrinsics names as well.
2710 RemangledIntrinsics[&F] = Remangled.getValue();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002711 }
2712
2713 // Look for global variables which need to be renamed.
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002714 for (GlobalVariable &GV : TheModule->globals())
2715 UpgradeGlobalVariable(&GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00002716
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002717 // Force deallocation of memory for these vectors to favor the client that
2718 // want lazy deserialization.
2719 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002720 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap(
2721 IndirectSymbolInits);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002722 return Error::success();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002723}
2724
Teresa Johnson1493ad92015-10-10 14:18:36 +00002725/// Support for lazy parsing of function bodies. This is required if we
2726/// either have an old bitcode file without a VST forward declaration record,
2727/// or if we have an anonymous function being materialized, since anonymous
2728/// functions do not have a name and are therefore not in the VST.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002729Error BitcodeReader::rememberAndSkipFunctionBodies() {
Teresa Johnson1493ad92015-10-10 14:18:36 +00002730 Stream.JumpToBit(NextUnreadBit);
2731
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002732 if (Stream.AtEndOfStream())
2733 return error("Could not find function in stream");
Teresa Johnson1493ad92015-10-10 14:18:36 +00002734
Filipe Cabecinhas7aae2f22015-11-03 13:48:26 +00002735 if (!SeenFirstFunctionBody)
2736 return error("Trying to materialize functions before seeing function blocks");
2737
Teresa Johnson1493ad92015-10-10 14:18:36 +00002738 // An old bitcode file with the symbol table at the end would have
2739 // finished the parse greedily.
2740 assert(SeenValueSymbolTable);
2741
2742 SmallVector<uint64_t, 64> Record;
2743
Eugene Zelenko1804a772016-08-25 00:45:04 +00002744 while (true) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00002745 BitstreamEntry Entry = Stream.advance();
2746 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002747 default:
2748 return error("Expect SubBlock");
2749 case BitstreamEntry::SubBlock:
2750 switch (Entry.ID) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00002751 default:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002752 return error("Expect function block");
2753 case bitc::FUNCTION_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002754 if (Error Err = rememberAndSkipFunctionBody())
2755 return Err;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002756 NextUnreadBit = Stream.GetCurrentBitNo();
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002757 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002758 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00002759 }
2760 }
2761}
2762
Peter Collingbourne939c7d92016-11-08 04:16:57 +00002763bool BitcodeReaderBase::readBlockInfo() {
Peter Collingbourne77c89b62016-11-08 04:17:11 +00002764 Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock();
2765 if (!NewBlockInfo)
2766 return true;
2767 BlockInfo = std::move(*NewBlockInfo);
2768 return false;
Peter Collingbourne939c7d92016-11-08 04:16:57 +00002769}
2770
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002771Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002772 // v1: [selection_kind, name]
2773 // v2: [strtab_offset, strtab_size, selection_kind]
2774 StringRef Name;
2775 std::tie(Name, Record) = readNameFromStrtab(Record);
2776
2777 if (Record.size() < 1)
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002778 return error("Invalid record");
2779 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002780 std::string OldFormatName;
2781 if (!UseStrtab) {
2782 if (Record.size() < 2)
2783 return error("Invalid record");
2784 unsigned ComdatNameSize = Record[1];
2785 OldFormatName.reserve(ComdatNameSize);
2786 for (unsigned i = 0; i != ComdatNameSize; ++i)
2787 OldFormatName += (char)Record[2 + i];
2788 Name = OldFormatName;
2789 }
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002790 Comdat *C = TheModule->getOrInsertComdat(Name);
2791 C->setSelectionKind(SK);
2792 ComdatList.push_back(C);
2793 return Error::success();
2794}
2795
2796Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002797 // v1: [pointer type, isconst, initid, linkage, alignment, section,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002798 // visibility, threadlocal, unnamed_addr, externally_initialized,
Javed Absarf3d79042017-05-11 12:28:08 +00002799 // dllstorageclass, comdat, attributes] (name in VST)
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002800 // v2: [strtab_offset, strtab_size, v1]
2801 StringRef Name;
2802 std::tie(Name, Record) = readNameFromStrtab(Record);
2803
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002804 if (Record.size() < 6)
2805 return error("Invalid record");
2806 Type *Ty = getTypeByID(Record[0]);
2807 if (!Ty)
2808 return error("Invalid record");
2809 bool isConstant = Record[1] & 1;
2810 bool explicitType = Record[1] & 2;
2811 unsigned AddressSpace;
2812 if (explicitType) {
2813 AddressSpace = Record[1] >> 2;
2814 } else {
2815 if (!Ty->isPointerTy())
2816 return error("Invalid type for value");
2817 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2818 Ty = cast<PointerType>(Ty)->getElementType();
2819 }
2820
2821 uint64_t RawLinkage = Record[3];
2822 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2823 unsigned Alignment;
2824 if (Error Err = parseAlignmentValue(Record[4], Alignment))
2825 return Err;
2826 std::string Section;
2827 if (Record[5]) {
2828 if (Record[5] - 1 >= SectionTable.size())
2829 return error("Invalid ID");
2830 Section = SectionTable[Record[5] - 1];
2831 }
2832 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2833 // Local linkage must have default visibility.
2834 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2835 // FIXME: Change to an error if non-default in 4.0.
2836 Visibility = getDecodedVisibility(Record[6]);
2837
2838 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2839 if (Record.size() > 7)
2840 TLM = getDecodedThreadLocalMode(Record[7]);
2841
2842 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
2843 if (Record.size() > 8)
2844 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
2845
2846 bool ExternallyInitialized = false;
2847 if (Record.size() > 9)
2848 ExternallyInitialized = Record[9];
2849
2850 GlobalVariable *NewGV =
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002851 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002852 nullptr, TLM, AddressSpace, ExternallyInitialized);
2853 NewGV->setAlignment(Alignment);
2854 if (!Section.empty())
2855 NewGV->setSection(Section);
2856 NewGV->setVisibility(Visibility);
2857 NewGV->setUnnamedAddr(UnnamedAddr);
2858
2859 if (Record.size() > 10)
2860 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
2861 else
2862 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
2863
2864 ValueList.push_back(NewGV);
2865
2866 // Remember which value to use for the global initializer.
2867 if (unsigned InitID = Record[2])
2868 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
2869
2870 if (Record.size() > 11) {
2871 if (unsigned ComdatID = Record[11]) {
2872 if (ComdatID > ComdatList.size())
2873 return error("Invalid global variable comdat ID");
2874 NewGV->setComdat(ComdatList[ComdatID - 1]);
2875 }
2876 } else if (hasImplicitComdat(RawLinkage)) {
2877 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2878 }
Javed Absarf3d79042017-05-11 12:28:08 +00002879
2880 if (Record.size() > 12) {
2881 auto AS = getAttributes(Record[12]).getFnAttributes();
2882 NewGV->setAttributes(AS);
2883 }
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002884 return Error::success();
2885}
2886
2887Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002888 // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002889 // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002890 // prefixdata] (name in VST)
2891 // v2: [strtab_offset, strtab_size, v1]
2892 StringRef Name;
2893 std::tie(Name, Record) = readNameFromStrtab(Record);
2894
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002895 if (Record.size() < 8)
2896 return error("Invalid record");
2897 Type *Ty = getTypeByID(Record[0]);
2898 if (!Ty)
2899 return error("Invalid record");
2900 if (auto *PTy = dyn_cast<PointerType>(Ty))
2901 Ty = PTy->getElementType();
2902 auto *FTy = dyn_cast<FunctionType>(Ty);
2903 if (!FTy)
2904 return error("Invalid type for value");
2905 auto CC = static_cast<CallingConv::ID>(Record[1]);
2906 if (CC & ~CallingConv::MaxID)
2907 return error("Invalid calling convention ID");
2908
2909 Function *Func =
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002910 Function::Create(FTy, GlobalValue::ExternalLinkage, Name, TheModule);
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002911
2912 Func->setCallingConv(CC);
2913 bool isProto = Record[2];
2914 uint64_t RawLinkage = Record[3];
2915 Func->setLinkage(getDecodedLinkage(RawLinkage));
2916 Func->setAttributes(getAttributes(Record[4]));
2917
2918 unsigned Alignment;
2919 if (Error Err = parseAlignmentValue(Record[5], Alignment))
2920 return Err;
2921 Func->setAlignment(Alignment);
2922 if (Record[6]) {
2923 if (Record[6] - 1 >= SectionTable.size())
2924 return error("Invalid ID");
2925 Func->setSection(SectionTable[Record[6] - 1]);
2926 }
2927 // Local linkage must have default visibility.
2928 if (!Func->hasLocalLinkage())
2929 // FIXME: Change to an error if non-default in 4.0.
2930 Func->setVisibility(getDecodedVisibility(Record[7]));
2931 if (Record.size() > 8 && Record[8]) {
2932 if (Record[8] - 1 >= GCTable.size())
2933 return error("Invalid ID");
2934 Func->setGC(GCTable[Record[8] - 1]);
2935 }
2936 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
2937 if (Record.size() > 9)
2938 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
2939 Func->setUnnamedAddr(UnnamedAddr);
2940 if (Record.size() > 10 && Record[10] != 0)
2941 FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
2942
2943 if (Record.size() > 11)
2944 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
2945 else
2946 upgradeDLLImportExportLinkage(Func, RawLinkage);
2947
2948 if (Record.size() > 12) {
2949 if (unsigned ComdatID = Record[12]) {
2950 if (ComdatID > ComdatList.size())
2951 return error("Invalid function comdat ID");
2952 Func->setComdat(ComdatList[ComdatID - 1]);
2953 }
2954 } else if (hasImplicitComdat(RawLinkage)) {
2955 Func->setComdat(reinterpret_cast<Comdat *>(1));
2956 }
2957
2958 if (Record.size() > 13 && Record[13] != 0)
2959 FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
2960
2961 if (Record.size() > 14 && Record[14] != 0)
2962 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
2963
2964 ValueList.push_back(Func);
2965
2966 // If this is a function with a body, remember the prototype we are
2967 // creating now, so that we can match up the body with them later.
2968 if (!isProto) {
2969 Func->setIsMaterializable(true);
2970 FunctionsWithBodies.push_back(Func);
2971 DeferredFunctionInfo[Func] = 0;
2972 }
2973 return Error::success();
2974}
2975
2976Error BitcodeReader::parseGlobalIndirectSymbolRecord(
2977 unsigned BitCode, ArrayRef<uint64_t> Record) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002978 // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
2979 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
2980 // dllstorageclass] (name in VST)
2981 // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
2982 // visibility, dllstorageclass] (name in VST)
2983 // v2: [strtab_offset, strtab_size, v1]
2984 StringRef Name;
2985 std::tie(Name, Record) = readNameFromStrtab(Record);
2986
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002987 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
2988 if (Record.size() < (3 + (unsigned)NewRecord))
2989 return error("Invalid record");
2990 unsigned OpNum = 0;
2991 Type *Ty = getTypeByID(Record[OpNum++]);
2992 if (!Ty)
2993 return error("Invalid record");
2994
2995 unsigned AddrSpace;
2996 if (!NewRecord) {
2997 auto *PTy = dyn_cast<PointerType>(Ty);
2998 if (!PTy)
2999 return error("Invalid type for value");
3000 Ty = PTy->getElementType();
3001 AddrSpace = PTy->getAddressSpace();
3002 } else {
3003 AddrSpace = Record[OpNum++];
3004 }
3005
3006 auto Val = Record[OpNum++];
3007 auto Linkage = Record[OpNum++];
3008 GlobalIndirectSymbol *NewGA;
3009 if (BitCode == bitc::MODULE_CODE_ALIAS ||
3010 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003011 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003012 TheModule);
3013 else
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003014 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003015 nullptr, TheModule);
3016 // Old bitcode files didn't have visibility field.
3017 // Local linkage must have default visibility.
3018 if (OpNum != Record.size()) {
3019 auto VisInd = OpNum++;
3020 if (!NewGA->hasLocalLinkage())
3021 // FIXME: Change to an error if non-default in 4.0.
3022 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3023 }
3024 if (OpNum != Record.size())
3025 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3026 else
3027 upgradeDLLImportExportLinkage(NewGA, Linkage);
3028 if (OpNum != Record.size())
3029 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3030 if (OpNum != Record.size())
3031 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
3032 ValueList.push_back(NewGA);
3033 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3034 return Error::success();
3035}
3036
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003037Error BitcodeReader::parseModule(uint64_t ResumeBit,
3038 bool ShouldLazyLoadMetadata) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003039 if (ResumeBit)
3040 Stream.JumpToBit(ResumeBit);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003041 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003042 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003043
Chris Lattner1314b992007-04-22 06:23:29 +00003044 SmallVector<uint64_t, 64> Record;
Chris Lattner1314b992007-04-22 06:23:29 +00003045
3046 // Read all the records for this module.
Eugene Zelenko1804a772016-08-25 00:45:04 +00003047 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00003048 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003049
Chris Lattner27d38752013-01-20 02:13:19 +00003050 switch (Entry.Kind) {
3051 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003052 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003053 case BitstreamEntry::EndBlock:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003054 return globalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00003055
Chris Lattner27d38752013-01-20 02:13:19 +00003056 case BitstreamEntry::SubBlock:
3057 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00003058 default: // Skip unknown content.
3059 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003060 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003061 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003062 case bitc::BLOCKINFO_BLOCK_ID:
Peter Collingbourne939c7d92016-11-08 04:16:57 +00003063 if (readBlockInfo())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003064 return error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003065 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003066 case bitc::PARAMATTR_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003067 if (Error Err = parseAttributeBlock())
3068 return Err;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003069 break;
Bill Wendlingba629332013-02-10 23:24:25 +00003070 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003071 if (Error Err = parseAttributeGroupBlock())
3072 return Err;
Bill Wendlingba629332013-02-10 23:24:25 +00003073 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003074 case bitc::TYPE_BLOCK_ID_NEW:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003075 if (Error Err = parseTypeTable())
3076 return Err;
Chris Lattner1314b992007-04-22 06:23:29 +00003077 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00003078 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnsonff642b92015-09-17 20:12:00 +00003079 if (!SeenValueSymbolTable) {
3080 // Either this is an old form VST without function index and an
3081 // associated VST forward declaration record (which would have caused
3082 // the VST to be jumped to and parsed before it was encountered
3083 // normally in the stream), or there were no function blocks to
3084 // trigger an earlier parsing of the VST.
3085 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003086 if (Error Err = parseValueSymbolTable())
3087 return Err;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003088 SeenValueSymbolTable = true;
3089 } else {
3090 // We must have had a VST forward declaration record, which caused
3091 // the parser to jump to and parse the VST earlier.
3092 assert(VSTOffset > 0);
3093 if (Stream.SkipBlock())
3094 return error("Invalid record");
3095 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00003096 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003097 case bitc::CONSTANTS_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003098 if (Error Err = parseConstants())
3099 return Err;
3100 if (Error Err = resolveGlobalAndIndirectSymbolInits())
3101 return Err;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003102 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00003103 case bitc::METADATA_BLOCK_ID:
Mehdi Aminibf2090e2016-12-12 19:23:39 +00003104 if (ShouldLazyLoadMetadata) {
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003105 if (Error Err = rememberAndSkipMetadata())
3106 return Err;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003107 break;
3108 }
3109 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
Mehdi Aminief27db82016-12-12 19:34:26 +00003110 if (Error Err = MDLoader->parseModuleMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003111 return Err;
Devang Patel7428d8a2009-07-22 17:43:22 +00003112 break;
Teresa Johnson12545072015-11-15 02:00:09 +00003113 case bitc::METADATA_KIND_BLOCK_ID:
Mehdi Aminief27db82016-12-12 19:34:26 +00003114 if (Error Err = MDLoader->parseMetadataKinds())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003115 return Err;
Teresa Johnson12545072015-11-15 02:00:09 +00003116 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003117 case bitc::FUNCTION_BLOCK_ID:
Mehdi Amini466a64e2016-08-13 23:39:14 +00003118 // If this is the first function body we've seen, reverse the
3119 // FunctionsWithBodies list.
3120 if (!SeenFirstFunctionBody) {
3121 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003122 if (Error Err = globalCleanup())
3123 return Err;
Mehdi Amini466a64e2016-08-13 23:39:14 +00003124 SeenFirstFunctionBody = true;
3125 }
3126
Teresa Johnsonff642b92015-09-17 20:12:00 +00003127 if (VSTOffset > 0) {
3128 // If we have a VST forward declaration record, make sure we
3129 // parse the VST now if we haven't already. It is needed to
3130 // set up the DeferredFunctionInfo vector for lazy reading.
3131 if (!SeenValueSymbolTable) {
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003132 if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3133 return Err;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003134 SeenValueSymbolTable = true;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003135 // Fall through so that we record the NextUnreadBit below.
3136 // This is necessary in case we have an anonymous function that
3137 // is later materialized. Since it will not have a VST entry we
3138 // need to fall back to the lazy parse to find its offset.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003139 } else {
3140 // If we have a VST forward declaration record, but have already
3141 // parsed the VST (just above, when the first function body was
3142 // encountered here), then we are resuming the parse after
Teresa Johnson1493ad92015-10-10 14:18:36 +00003143 // materializing functions. The ResumeBit points to the
3144 // start of the last function block recorded in the
3145 // DeferredFunctionInfo map. Skip it.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003146 if (Stream.SkipBlock())
3147 return error("Invalid record");
3148 continue;
3149 }
3150 }
3151
3152 // Support older bitcode files that did not have the function
Teresa Johnson1493ad92015-10-10 14:18:36 +00003153 // index in the VST, nor a VST forward declaration record, as
3154 // well as anonymous functions that do not have VST entries.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003155 // Build the DeferredFunctionInfo vector on the fly.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003156 if (Error Err = rememberAndSkipFunctionBody())
3157 return Err;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003158
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003159 // Suspend parsing when we reach the function bodies. Subsequent
3160 // materialization calls will resume it when necessary. If the bitcode
3161 // file is old, the symbol table will be at the end instead and will not
3162 // have been seen yet. In this case, just finish the parse now.
3163 if (SeenValueSymbolTable) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003164 NextUnreadBit = Stream.GetCurrentBitNo();
Mehdi Aminia71002e2016-08-14 00:01:27 +00003165 // After the VST has been parsed, we need to make sure intrinsic name
3166 // are auto-upgraded.
3167 return globalCleanup();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003168 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003169 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003170 case bitc::USELIST_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003171 if (Error Err = parseUseLists())
3172 return Err;
Chad Rosierca2567b2011-12-07 21:44:12 +00003173 break;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003174 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003175 if (Error Err = parseOperandBundleTags())
3176 return Err;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003177 break;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00003178 case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
3179 if (Error Err = parseSyncScopeNames())
3180 return Err;
3181 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003182 }
3183 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003184
Chris Lattner27d38752013-01-20 02:13:19 +00003185 case BitstreamEntry::Record:
3186 // The interesting case.
3187 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003188 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003189
Chris Lattner1314b992007-04-22 06:23:29 +00003190 // Read a record.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003191 auto BitCode = Stream.readRecord(Entry.ID, Record);
3192 switch (BitCode) {
Chris Lattner1314b992007-04-22 06:23:29 +00003193 default: break; // Default behavior, ignore unknown content.
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003194 case bitc::MODULE_CODE_VERSION: {
3195 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
3196 if (!VersionOrErr)
3197 return VersionOrErr.takeError();
3198 UseRelativeIDs = *VersionOrErr >= 1;
Chris Lattner1314b992007-04-22 06:23:29 +00003199 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00003200 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003201 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003202 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003203 if (convertToString(Record, 0, S))
3204 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003205 TheModule->setTargetTriple(S);
3206 break;
3207 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003208 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003209 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003210 if (convertToString(Record, 0, S))
3211 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003212 TheModule->setDataLayout(S);
3213 break;
3214 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003215 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003216 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003217 if (convertToString(Record, 0, S))
3218 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003219 TheModule->setModuleInlineAsm(S);
3220 break;
3221 }
Bill Wendling706d3d62012-11-28 08:41:48 +00003222 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3223 // FIXME: Remove in 4.0.
3224 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003225 if (convertToString(Record, 0, S))
3226 return error("Invalid record");
Bill Wendling706d3d62012-11-28 08:41:48 +00003227 // Ignore value.
3228 break;
3229 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003230 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003231 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003232 if (convertToString(Record, 0, S))
3233 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003234 SectionTable.push_back(S);
3235 break;
3236 }
Gordon Henriksend930f912008-08-17 18:44:35 +00003237 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00003238 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003239 if (convertToString(Record, 0, S))
3240 return error("Invalid record");
Gordon Henriksend930f912008-08-17 18:44:35 +00003241 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00003242 break;
3243 }
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003244 case bitc::MODULE_CODE_COMDAT: {
3245 if (Error Err = parseComdatRecord(Record))
3246 return Err;
David Majnemerdad0a642014-06-27 18:19:56 +00003247 break;
3248 }
Chris Lattner1314b992007-04-22 06:23:29 +00003249 case bitc::MODULE_CODE_GLOBALVAR: {
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003250 if (Error Err = parseGlobalVarRecord(Record))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003251 return Err;
Chris Lattner1314b992007-04-22 06:23:29 +00003252 break;
3253 }
Chris Lattner1314b992007-04-22 06:23:29 +00003254 case bitc::MODULE_CODE_FUNCTION: {
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003255 if (Error Err = parseFunctionRecord(Record))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003256 return Err;
Chris Lattner1314b992007-04-22 06:23:29 +00003257 break;
3258 }
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003259 case bitc::MODULE_CODE_IFUNC:
David Blaikie6a51dbd2015-09-17 22:18:59 +00003260 case bitc::MODULE_CODE_ALIAS:
3261 case bitc::MODULE_CODE_ALIAS_OLD: {
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003262 if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
3263 return Err;
Chris Lattner44c17072007-04-26 02:46:40 +00003264 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003265 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00003266 /// MODULE_CODE_VSTOFFSET: [offset]
3267 case bitc::MODULE_CODE_VSTOFFSET:
3268 if (Record.size() < 1)
3269 return error("Invalid record");
Peter Collingbournebfcf9802016-11-29 02:27:04 +00003270 // Note that we subtract 1 here because the offset is relative to one word
3271 // before the start of the identification or module block, which was
3272 // historically always the start of the regular bitcode header.
3273 VSTOffset = Record[0] - 1;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003274 break;
Teresa Johnsone1164de2016-02-10 21:55:02 +00003275 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3276 case bitc::MODULE_CODE_SOURCE_FILENAME:
3277 SmallString<128> ValueName;
3278 if (convertToString(Record, 0, ValueName))
3279 return error("Invalid record");
3280 TheModule->setSourceFileName(ValueName);
3281 break;
Chris Lattner831d4202007-04-26 03:27:58 +00003282 }
Chris Lattner1314b992007-04-22 06:23:29 +00003283 Record.clear();
3284 }
Chris Lattner1314b992007-04-22 06:23:29 +00003285}
3286
Teresa Johnsona61f5e32016-12-16 21:25:01 +00003287Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
3288 bool IsImporting) {
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003289 TheModule = M;
Teresa Johnsona61f5e32016-12-16 21:25:01 +00003290 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
Mehdi Aminief27db82016-12-12 19:34:26 +00003291 [&](unsigned ID) { return getTypeByID(ID); });
Peter Collingbourne7a748032016-11-16 21:44:45 +00003292 return parseModule(0, ShouldLazyLoadMetadata);
Chris Lattner1314b992007-04-22 06:23:29 +00003293}
Chris Lattner6694f602007-04-29 07:54:31 +00003294
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003295
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003296Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003297 if (!isa<PointerType>(PtrType))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003298 return error("Load/Store operand is not a pointer type");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003299 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3300
3301 if (ValType && ValType != ElemType)
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003302 return error("Explicit load/store type does not match pointee "
3303 "type of pointer operand");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003304 if (!PointerType::isLoadableOrStorableType(ElemType))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003305 return error("Cannot load/store from pointer");
3306 return Error::success();
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003307}
3308
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003309/// Lazily parse the specified function body block.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003310Error BitcodeReader::parseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00003311 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003312 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003313
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00003314 // Unexpected unresolved metadata when parsing function.
Mehdi Aminief27db82016-12-12 19:34:26 +00003315 if (MDLoader->hasFwdRefs())
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00003316 return error("Invalid function metadata: incoming forward references");
3317
Nick Lewyckya72e1af2010-02-25 08:30:17 +00003318 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00003319 unsigned ModuleValueListSize = ValueList.size();
Mehdi Aminief27db82016-12-12 19:34:26 +00003320 unsigned ModuleMDLoaderSize = MDLoader->size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003321
Chris Lattner85b7b402007-05-01 05:52:21 +00003322 // Add all the function arguments to the value table.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00003323 for (Argument &I : F->args())
3324 ValueList.push_back(&I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003325
Chris Lattner83930552007-05-01 07:01:57 +00003326 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00003327 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00003328 unsigned CurBBNo = 0;
3329
Chris Lattner07d09ed2010-04-03 02:17:50 +00003330 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003331 auto getLastInstruction = [&]() -> Instruction * {
3332 if (CurBB && !CurBB->empty())
3333 return &CurBB->back();
3334 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3335 !FunctionBBs[CurBBNo - 1]->empty())
3336 return &FunctionBBs[CurBBNo - 1]->back();
3337 return nullptr;
3338 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003339
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003340 std::vector<OperandBundleDef> OperandBundles;
3341
Chris Lattner85b7b402007-05-01 05:52:21 +00003342 // Read all the records.
3343 SmallVector<uint64_t, 64> Record;
Eugene Zelenko1804a772016-08-25 00:45:04 +00003344
3345 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00003346 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003347
Chris Lattner27d38752013-01-20 02:13:19 +00003348 switch (Entry.Kind) {
3349 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003350 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003351 case BitstreamEntry::EndBlock:
3352 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00003353
Chris Lattner27d38752013-01-20 02:13:19 +00003354 case BitstreamEntry::SubBlock:
3355 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00003356 default: // Skip unknown content.
3357 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003358 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00003359 break;
3360 case bitc::CONSTANTS_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003361 if (Error Err = parseConstants())
3362 return Err;
Chris Lattner83930552007-05-01 07:01:57 +00003363 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00003364 break;
3365 case bitc::VALUE_SYMTAB_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003366 if (Error Err = parseValueSymbolTable())
3367 return Err;
Chris Lattner85b7b402007-05-01 05:52:21 +00003368 break;
Devang Patelaf206b82009-09-18 19:26:43 +00003369 case bitc::METADATA_ATTACHMENT_ID:
Mehdi Aminief27db82016-12-12 19:34:26 +00003370 if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003371 return Err;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003372 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00003373 case bitc::METADATA_BLOCK_ID:
Mehdi Aminief27db82016-12-12 19:34:26 +00003374 assert(DeferredMetadataInfo.empty() &&
3375 "Must read all module-level metadata before function-level");
3376 if (Error Err = MDLoader->parseFunctionMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003377 return Err;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00003378 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003379 case bitc::USELIST_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003380 if (Error Err = parseUseLists())
3381 return Err;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003382 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00003383 }
3384 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003385
Chris Lattner27d38752013-01-20 02:13:19 +00003386 case BitstreamEntry::Record:
3387 // The interesting case.
3388 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00003389 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003390
Chris Lattner85b7b402007-05-01 05:52:21 +00003391 // Read a record.
3392 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00003393 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00003394 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00003395 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00003396 default: // Default behavior: reject
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003397 return error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003398 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00003399 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003400 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00003401 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00003402 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003403
3404 // See if anything took the address of blocks in this function.
3405 auto BBFRI = BasicBlockFwdRefs.find(F);
3406 if (BBFRI == BasicBlockFwdRefs.end()) {
3407 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3408 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3409 } else {
3410 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003411 // Check for invalid basic block references.
3412 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003413 return error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003414 assert(!BBRefs.empty() && "Unexpected empty array");
3415 assert(!BBRefs.front() && "Invalid reference to entry block");
3416 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3417 ++I)
3418 if (I < RE && BBRefs[I]) {
3419 BBRefs[I]->insertInto(F);
3420 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003421 } else {
3422 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3423 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003424
3425 // Erase from the table.
3426 BasicBlockFwdRefs.erase(BBFRI);
3427 }
3428
Chris Lattner83930552007-05-01 07:01:57 +00003429 CurBB = FunctionBBs[0];
3430 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003431 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003432
Chris Lattner07d09ed2010-04-03 02:17:50 +00003433 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3434 // This record indicates that the last instruction is at the same
3435 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003436 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003437
Craig Topper2617dcc2014-04-15 06:32:26 +00003438 if (!I)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003439 return error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00003440 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003441 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003442 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003443
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00003444 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003445 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00003446 if (!I || Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003447 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003448
Chris Lattner07d09ed2010-04-03 02:17:50 +00003449 unsigned Line = Record[0], Col = Record[1];
3450 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003451
Craig Topper2617dcc2014-04-15 06:32:26 +00003452 MDNode *Scope = nullptr, *IA = nullptr;
Justin Bognerae341c62016-03-17 20:12:06 +00003453 if (ScopeID) {
Mehdi Aminief27db82016-12-12 19:34:26 +00003454 Scope = MDLoader->getMDNodeFwdRefOrNull(ScopeID - 1);
Justin Bognerae341c62016-03-17 20:12:06 +00003455 if (!Scope)
3456 return error("Invalid record");
3457 }
3458 if (IAID) {
Mehdi Aminief27db82016-12-12 19:34:26 +00003459 IA = MDLoader->getMDNodeFwdRefOrNull(IAID - 1);
Justin Bognerae341c62016-03-17 20:12:06 +00003460 if (!IA)
3461 return error("Invalid record");
3462 }
Chris Lattner07d09ed2010-04-03 02:17:50 +00003463 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3464 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003465 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003466 continue;
3467 }
3468
Chris Lattnere9759c22007-05-06 00:21:25 +00003469 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3470 unsigned OpNum = 0;
3471 Value *LHS, *RHS;
3472 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003473 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00003474 OpNum+1 > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003475 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003476
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003477 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00003478 if (Opc == -1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003479 return error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003480 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00003481 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00003482 if (OpNum < Record.size()) {
3483 if (Opc == Instruction::Add ||
3484 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003485 Opc == Instruction::Mul ||
3486 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00003487 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00003488 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00003489 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00003490 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00003491 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003492 Opc == Instruction::UDiv ||
3493 Opc == Instruction::LShr ||
3494 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00003495 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00003496 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003497 } else if (isa<FPMathOperator>(I)) {
James Molloy88eb5352015-07-10 12:52:00 +00003498 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003499 if (FMF.any())
3500 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00003501 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003502
Dan Gohman1b849082009-09-07 23:54:19 +00003503 }
Chris Lattner85b7b402007-05-01 05:52:21 +00003504 break;
3505 }
Chris Lattnere9759c22007-05-06 00:21:25 +00003506 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3507 unsigned OpNum = 0;
3508 Value *Op;
3509 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3510 OpNum+2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003511 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003512
Chris Lattner229907c2011-07-18 04:54:35 +00003513 Type *ResTy = getTypeByID(Record[OpNum]);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003514 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003515 if (Opc == -1 || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003516 return error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00003517 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003518 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3519 if (Temp) {
3520 InstructionList.push_back(Temp);
3521 CurBB->getInstList().push_back(Temp);
3522 }
3523 } else {
Filipe Cabecinhasb70fd872015-10-06 12:37:54 +00003524 auto CastOp = (Instruction::CastOps)Opc;
3525 if (!CastInst::castIsValid(CastOp, Op, ResTy))
3526 return error("Invalid cast");
3527 I = CastInst::Create(CastOp, Op, ResTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003528 }
Devang Patelaf206b82009-09-18 19:26:43 +00003529 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00003530 break;
3531 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00003532 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3533 case bitc::FUNC_CODE_INST_GEP_OLD:
3534 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003535 unsigned OpNum = 0;
David Blaikieb5b5efd2015-02-25 01:08:52 +00003536
3537 Type *Ty;
3538 bool InBounds;
3539
3540 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3541 InBounds = Record[OpNum++];
3542 Ty = getTypeByID(Record[OpNum++]);
3543 } else {
3544 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3545 Ty = nullptr;
3546 }
3547
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003548 Value *BasePtr;
3549 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003550 return error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00003551
David Blaikie60310f22015-05-08 00:42:26 +00003552 if (!Ty)
Peter Collingbourne9ef5a8c2016-11-13 06:59:28 +00003553 Ty = cast<PointerType>(BasePtr->getType()->getScalarType())
David Blaikie60310f22015-05-08 00:42:26 +00003554 ->getElementType();
3555 else if (Ty !=
Peter Collingbourne9ef5a8c2016-11-13 06:59:28 +00003556 cast<PointerType>(BasePtr->getType()->getScalarType())
David Blaikie60310f22015-05-08 00:42:26 +00003557 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003558 return error(
David Blaikie675e8cb2015-03-16 21:35:48 +00003559 "Explicit gep type does not match pointee type of pointer operand");
3560
Chris Lattner5285b5e2007-05-02 05:46:45 +00003561 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003562 while (OpNum != Record.size()) {
3563 Value *Op;
3564 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003565 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003566 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003567 }
3568
David Blaikie096b1da2015-03-14 19:53:33 +00003569 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
David Blaikie675e8cb2015-03-16 21:35:48 +00003570
Devang Patelaf206b82009-09-18 19:26:43 +00003571 InstructionList.push_back(I);
David Blaikieb5b5efd2015-02-25 01:08:52 +00003572 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00003573 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003574 break;
3575 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003576
Dan Gohman1ecaf452008-05-31 00:58:22 +00003577 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3578 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00003579 unsigned OpNum = 0;
3580 Value *Agg;
3581 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003582 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003583
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003584 unsigned RecSize = Record.size();
3585 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003586 return error("EXTRACTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003587
Dan Gohman1ecaf452008-05-31 00:58:22 +00003588 SmallVector<unsigned, 4> EXTRACTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003589 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003590 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003591 bool IsArray = CurTy->isArrayTy();
3592 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003593 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003594
3595 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003596 return error("EXTRACTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003597 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003598 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003599 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003600 return error("EXTRACTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003601 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003602 return error("EXTRACTVAL: Invalid array index");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003603 EXTRACTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003604
3605 if (IsStruct)
3606 CurTy = CurTy->subtypes()[Index];
3607 else
3608 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00003609 }
3610
Jay Foad57aa6362011-07-13 10:26:04 +00003611 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003612 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00003613 break;
3614 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003615
Dan Gohman1ecaf452008-05-31 00:58:22 +00003616 case bitc::FUNC_CODE_INST_INSERTVAL: {
3617 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00003618 unsigned OpNum = 0;
3619 Value *Agg;
3620 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003621 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003622 Value *Val;
3623 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003624 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003625
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003626 unsigned RecSize = Record.size();
3627 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003628 return error("INSERTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003629
Dan Gohman1ecaf452008-05-31 00:58:22 +00003630 SmallVector<unsigned, 4> INSERTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003631 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003632 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003633 bool IsArray = CurTy->isArrayTy();
3634 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003635 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003636
3637 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003638 return error("INSERTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003639 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003640 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003641 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003642 return error("INSERTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003643 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003644 return error("INSERTVAL: Invalid array index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003645
Dan Gohman1ecaf452008-05-31 00:58:22 +00003646 INSERTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003647 if (IsStruct)
3648 CurTy = CurTy->subtypes()[Index];
3649 else
3650 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00003651 }
3652
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00003653 if (CurTy != Val->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003654 return error("Inserted value type doesn't match aggregate type");
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00003655
Jay Foad57aa6362011-07-13 10:26:04 +00003656 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003657 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00003658 break;
3659 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003660
Chris Lattnere9759c22007-05-06 00:21:25 +00003661 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00003662 // obsolete form of select
3663 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00003664 unsigned OpNum = 0;
3665 Value *TrueVal, *FalseVal, *Cond;
3666 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003667 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3668 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003669 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003670
Dan Gohmanc5d28922008-09-16 01:01:33 +00003671 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00003672 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00003673 break;
3674 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003675
Dan Gohmanc5d28922008-09-16 01:01:33 +00003676 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3677 // new form of select
3678 // handles select i1 or select [N x i1]
3679 unsigned OpNum = 0;
3680 Value *TrueVal, *FalseVal, *Cond;
3681 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003682 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00003683 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003684 return error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00003685
3686 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00003687 if (VectorType* vector_type =
3688 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00003689 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003690 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003691 return error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00003692 } else {
3693 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003694 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003695 return error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003696 }
3697
Gabor Greife9ecc682008-04-06 20:25:17 +00003698 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00003699 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003700 break;
3701 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003702
Chris Lattner1fc27f02007-05-02 05:16:49 +00003703 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00003704 unsigned OpNum = 0;
3705 Value *Vec, *Idx;
3706 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003707 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003708 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003709 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003710 return error("Invalid type for value");
Eric Christopherc9742252009-07-25 02:28:41 +00003711 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00003712 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003713 break;
3714 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003715
Chris Lattner1fc27f02007-05-02 05:16:49 +00003716 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00003717 unsigned OpNum = 0;
3718 Value *Vec, *Elt, *Idx;
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003719 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003720 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003721 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003722 return error("Invalid type for value");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003723 if (popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00003724 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003725 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003726 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00003727 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00003728 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003729 break;
3730 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003731
Chris Lattnere9759c22007-05-06 00:21:25 +00003732 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3733 unsigned OpNum = 0;
3734 Value *Vec1, *Vec2, *Mask;
3735 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003736 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003737 return error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00003738
Mon P Wang25f01062008-11-10 04:46:22 +00003739 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003740 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003741 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003742 return error("Invalid type for value");
Chris Lattner1fc27f02007-05-02 05:16:49 +00003743 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00003744 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003745 break;
3746 }
Mon P Wang25f01062008-11-10 04:46:22 +00003747
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003748 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3749 // Old form of ICmp/FCmp returning bool
3750 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3751 // both legal on vectors but had different behaviour.
3752 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3753 // FCmp/ICmp returning bool or vector of bool
3754
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003755 unsigned OpNum = 0;
3756 Value *LHS, *RHS;
3757 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
James Molloy88eb5352015-07-10 12:52:00 +00003758 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3759 return error("Invalid record");
3760
3761 unsigned PredVal = Record[OpNum];
3762 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3763 FastMathFlags FMF;
3764 if (IsFP && Record.size() > OpNum+1)
3765 FMF = getDecodedFastMathFlags(Record[++OpNum]);
3766
3767 if (OpNum+1 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003768 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003769
Duncan Sands9dff9be2010-02-15 16:12:20 +00003770 if (LHS->getType()->isFPOrFPVectorTy())
James Molloy88eb5352015-07-10 12:52:00 +00003771 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003772 else
James Molloy88eb5352015-07-10 12:52:00 +00003773 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3774
3775 if (FMF.any())
3776 I->setFastMathFlags(FMF);
Devang Patelaf206b82009-09-18 19:26:43 +00003777 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00003778 break;
3779 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003780
Chris Lattnere53603e2007-05-02 04:27:25 +00003781 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00003782 {
3783 unsigned Size = Record.size();
3784 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00003785 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003786 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00003787 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003788 }
Devang Patelbbfd8742008-02-26 01:29:32 +00003789
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003790 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00003791 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00003792 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003793 return error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00003794 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003795 return error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003796
Chris Lattnerf1c87102011-06-17 18:09:11 +00003797 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003798 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003799 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00003800 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003801 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00003802 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003803 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003804 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003805 if (!TrueDest)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003806 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003807
Devang Patelaf206b82009-09-18 19:26:43 +00003808 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00003809 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003810 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00003811 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003812 else {
3813 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003814 Value *Cond = getValue(Record, 2, NextValueNo,
3815 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00003816 if (!FalseDest || !Cond)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003817 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00003818 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003819 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003820 }
3821 break;
3822 }
David Majnemerb01aa9f2015-08-23 19:22:31 +00003823 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003824 if (Record.size() != 1 && Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00003825 return error("Invalid record");
3826 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003827 Value *CleanupPad =
3828 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003829 if (!CleanupPad)
David Majnemer654e1302015-07-31 17:58:14 +00003830 return error("Invalid record");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003831 BasicBlock *UnwindDest = nullptr;
3832 if (Record.size() == 2) {
David Majnemer654e1302015-07-31 17:58:14 +00003833 UnwindDest = getBasicBlock(Record[Idx++]);
3834 if (!UnwindDest)
3835 return error("Invalid record");
3836 }
3837
David Majnemer8a1c45d2015-12-12 05:38:55 +00003838 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
David Majnemer654e1302015-07-31 17:58:14 +00003839 InstructionList.push_back(I);
3840 break;
3841 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003842 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
3843 if (Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00003844 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00003845 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003846 Value *CatchPad =
3847 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003848 if (!CatchPad)
3849 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00003850 BasicBlock *BB = getBasicBlock(Record[Idx++]);
David Majnemer654e1302015-07-31 17:58:14 +00003851 if (!BB)
3852 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00003853
David Majnemer8a1c45d2015-12-12 05:38:55 +00003854 I = CatchReturnInst::Create(CatchPad, BB);
David Majnemer654e1302015-07-31 17:58:14 +00003855 InstructionList.push_back(I);
3856 break;
3857 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003858 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
3859 // We must have, at minimum, the outer scope and the number of arguments.
3860 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00003861 return error("Invalid record");
3862
David Majnemer654e1302015-07-31 17:58:14 +00003863 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003864
3865 Value *ParentPad =
3866 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3867
3868 unsigned NumHandlers = Record[Idx++];
3869
3870 SmallVector<BasicBlock *, 2> Handlers;
3871 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
3872 BasicBlock *BB = getBasicBlock(Record[Idx++]);
3873 if (!BB)
David Majnemer654e1302015-07-31 17:58:14 +00003874 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00003875 Handlers.push_back(BB);
3876 }
3877
3878 BasicBlock *UnwindDest = nullptr;
3879 if (Idx + 1 == Record.size()) {
David Majnemer654e1302015-07-31 17:58:14 +00003880 UnwindDest = getBasicBlock(Record[Idx++]);
3881 if (!UnwindDest)
3882 return error("Invalid record");
3883 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003884
3885 if (Record.size() != Idx)
3886 return error("Invalid record");
3887
3888 auto *CatchSwitch =
3889 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
3890 for (BasicBlock *Handler : Handlers)
3891 CatchSwitch->addHandler(Handler);
3892 I = CatchSwitch;
3893 InstructionList.push_back(I);
3894 break;
3895 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003896 case bitc::FUNC_CODE_INST_CATCHPAD:
3897 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
3898 // We must have, at minimum, the outer scope and the number of arguments.
3899 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00003900 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00003901
David Majnemer654e1302015-07-31 17:58:14 +00003902 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003903
3904 Value *ParentPad =
3905 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3906
David Majnemer654e1302015-07-31 17:58:14 +00003907 unsigned NumArgOperands = Record[Idx++];
David Majnemer8a1c45d2015-12-12 05:38:55 +00003908
David Majnemer654e1302015-07-31 17:58:14 +00003909 SmallVector<Value *, 2> Args;
3910 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3911 Value *Val;
3912 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3913 return error("Invalid record");
3914 Args.push_back(Val);
3915 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003916
David Majnemer654e1302015-07-31 17:58:14 +00003917 if (Record.size() != Idx)
3918 return error("Invalid record");
3919
David Majnemer8a1c45d2015-12-12 05:38:55 +00003920 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
3921 I = CleanupPadInst::Create(ParentPad, Args);
3922 else
3923 I = CatchPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00003924 InstructionList.push_back(I);
3925 break;
3926 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00003927 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003928 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003929 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00003930 // "New" SwitchInst format with case ranges. The changes to write this
3931 // format were reverted but we still recognize bitcode that uses it.
3932 // Hopefully someday we will have support for case ranges and can use
3933 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003934
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003935 Type *OpTy = getTypeByID(Record[1]);
3936 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3937
Jan Wen Voungafaced02012-10-11 20:20:40 +00003938 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003939 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003940 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003941 return error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003942
3943 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003944
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003945 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3946 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003947
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003948 unsigned CurIdx = 5;
3949 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00003950 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003951 unsigned NumItems = Record[CurIdx++];
3952 for (unsigned ci = 0; ci != NumItems; ++ci) {
3953 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003954
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003955 APInt Low;
3956 unsigned ActiveWords = 1;
3957 if (ValueBitWidth > 64)
3958 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003959 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
Benjamin Kramer9704ed02012-05-28 14:10:31 +00003960 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003961 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00003962
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003963 if (!isSingleNumber) {
3964 ActiveWords = 1;
3965 if (ValueBitWidth > 64)
3966 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003967 APInt High = readWideAPInt(
3968 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003969 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00003970
3971 // FIXME: It is not clear whether values in the range should be
3972 // compared as signed or unsigned values. The partially
3973 // implemented changes that used this format in the past used
3974 // unsigned comparisons.
3975 for ( ; Low.ule(High); ++Low)
3976 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003977 } else
Bob Wilsone4077362013-09-09 19:14:35 +00003978 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003979 }
3980 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00003981 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3982 cve = CaseVals.end(); cvi != cve; ++cvi)
3983 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003984 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003985 I = SI;
3986 break;
3987 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003988
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00003989 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003990
Chris Lattner5285b5e2007-05-02 05:46:45 +00003991 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003992 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003993 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003994 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003995 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003996 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003997 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003998 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00003999 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00004000 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004001 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004002 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00004003 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4004 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004005 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00004006 delete SI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004007 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004008 }
4009 SI->addCase(CaseVal, DestBB);
4010 }
4011 I = SI;
4012 break;
4013 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004014 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00004015 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004016 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004017 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004018 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00004019 if (!OpTy || !Address)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004020 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004021 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004022 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00004023 InstructionList.push_back(IBI);
4024 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4025 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4026 IBI->addDestination(DestBB);
4027 } else {
4028 delete IBI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004029 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004030 }
4031 }
4032 I = IBI;
4033 break;
4034 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004035
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004036 case bitc::FUNC_CODE_INST_INVOKE: {
4037 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00004038 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004039 return error("Invalid record");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004040 unsigned OpNum = 0;
Reid Klecknerb5180542017-03-21 16:57:19 +00004041 AttributeList PAL = getAttributes(Record[OpNum++]);
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004042 unsigned CCInfo = Record[OpNum++];
4043 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4044 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004045
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004046 FunctionType *FTy = nullptr;
4047 if (CCInfo >> 13 & 1 &&
4048 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004049 return error("Explicit invoke type is not a function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004050
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004051 Value *Callee;
4052 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004053 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004054
Chris Lattner229907c2011-07-18 04:54:35 +00004055 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004056 if (!CalleeTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004057 return error("Callee is not a pointer");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004058 if (!FTy) {
4059 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4060 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004061 return error("Callee is not of pointer to function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004062 } else if (CalleeTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004063 return error("Explicit invoke type does not match pointee type of "
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004064 "callee operand");
4065 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004066 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004067
Chris Lattner5285b5e2007-05-02 05:46:45 +00004068 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004069 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004070 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4071 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004072 if (!Ops.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004073 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004074 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004075
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004076 if (!FTy->isVarArg()) {
4077 if (Record.size() != OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004078 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004079 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004080 // Read type/value pairs for varargs params.
4081 while (OpNum != Record.size()) {
4082 Value *Op;
4083 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004084 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004085 Ops.push_back(Op);
4086 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004087 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004088
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004089 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4090 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00004091 InstructionList.push_back(I);
Vedant Kumarad6d6e72015-10-27 21:17:06 +00004092 cast<InvokeInst>(I)->setCallingConv(
4093 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00004094 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004095 break;
4096 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00004097 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4098 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004099 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004100 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004101 return error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00004102 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00004103 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004104 break;
4105 }
Chris Lattnere53603e2007-05-02 04:27:25 +00004106 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00004107 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00004108 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004109 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00004110 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00004111 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004112 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004113 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004114 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004115 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004116
Jay Foad52131342011-03-30 11:28:46 +00004117 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00004118 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004119
Chris Lattnere14cb882007-05-04 19:11:41 +00004120 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004121 Value *V;
4122 // With the new function encoding, it is possible that operands have
4123 // negative IDs (for forward references). Use a signed VBR
4124 // representation to keep the encoding small.
4125 if (UseRelativeIDs)
4126 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4127 else
4128 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00004129 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004130 if (!V || !BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004131 return error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00004132 PN->addIncoming(V, BB);
4133 }
4134 I = PN;
4135 break;
4136 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004137
David Majnemer7fddecc2015-06-17 20:52:32 +00004138 case bitc::FUNC_CODE_INST_LANDINGPAD:
4139 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
Bill Wendlingfae14752011-08-12 20:24:12 +00004140 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4141 unsigned Idx = 0;
David Majnemer7fddecc2015-06-17 20:52:32 +00004142 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4143 if (Record.size() < 3)
4144 return error("Invalid record");
4145 } else {
4146 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4147 if (Record.size() < 4)
4148 return error("Invalid record");
4149 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004150 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004151 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004152 return error("Invalid record");
David Majnemer7fddecc2015-06-17 20:52:32 +00004153 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4154 Value *PersFn = nullptr;
4155 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4156 return error("Invalid record");
4157
4158 if (!F->hasPersonalityFn())
4159 F->setPersonalityFn(cast<Constant>(PersFn));
4160 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4161 return error("Personality function mismatch");
4162 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004163
4164 bool IsCleanup = !!Record[Idx++];
4165 unsigned NumClauses = Record[Idx++];
David Majnemer7fddecc2015-06-17 20:52:32 +00004166 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
Bill Wendlingfae14752011-08-12 20:24:12 +00004167 LP->setCleanup(IsCleanup);
4168 for (unsigned J = 0; J != NumClauses; ++J) {
4169 LandingPadInst::ClauseType CT =
4170 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4171 Value *Val;
4172
4173 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4174 delete LP;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004175 return error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00004176 }
4177
4178 assert((CT != LandingPadInst::Catch ||
4179 !isa<ArrayType>(Val->getType())) &&
4180 "Catch clause has a invalid type!");
4181 assert((CT != LandingPadInst::Filter ||
4182 isa<ArrayType>(Val->getType())) &&
4183 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004184 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00004185 }
4186
4187 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00004188 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00004189 break;
4190 }
4191
Chris Lattnerf1c87102011-06-17 18:09:11 +00004192 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4193 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004194 return error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00004195 uint64_t AlignRecord = Record[3];
4196 const uint64_t InAllocaMask = uint64_t(1) << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00004197 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00004198 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4199 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
4200 SwiftErrorMask;
JF Bastien30bf96b2015-02-22 19:32:03 +00004201 bool InAlloca = AlignRecord & InAllocaMask;
Manman Ren9bfd0d02016-04-01 21:41:15 +00004202 bool SwiftError = AlignRecord & SwiftErrorMask;
David Blaikiebdb49102015-04-28 16:51:01 +00004203 Type *Ty = getTypeByID(Record[0]);
4204 if ((AlignRecord & ExplicitTypeMask) == 0) {
4205 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4206 if (!PTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004207 return error("Old-style alloca with a non-pointer type");
David Blaikiebdb49102015-04-28 16:51:01 +00004208 Ty = PTy->getElementType();
4209 }
4210 Type *OpTy = getTypeByID(Record[1]);
4211 Value *Size = getFnValueByID(Record[2], OpTy);
JF Bastien30bf96b2015-02-22 19:32:03 +00004212 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004213 if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4214 return Err;
JF Bastien30bf96b2015-02-22 19:32:03 +00004215 }
Rafael Espindola48da4f42013-11-04 16:16:24 +00004216 if (!Ty || !Size)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004217 return error("Invalid record");
Matt Arsenault3c1fc762017-04-10 22:27:50 +00004218
4219 // FIXME: Make this an optional field.
4220 const DataLayout &DL = TheModule->getDataLayout();
4221 unsigned AS = DL.getAllocaAddrSpace();
4222
4223 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Align);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00004224 AI->setUsedWithInAlloca(InAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00004225 AI->setSwiftError(SwiftError);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00004226 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00004227 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00004228 break;
4229 }
Chris Lattner9f600c52007-05-03 22:04:19 +00004230 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004231 unsigned OpNum = 0;
4232 Value *Op;
4233 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004234 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004235 return error("Invalid record");
David Blaikie85035652015-02-25 01:07:20 +00004236
4237 Type *Ty = nullptr;
4238 if (OpNum + 3 == Record.size())
4239 Ty = getTypeByID(Record[OpNum++]);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004240 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4241 return Err;
David Blaikieb7a029872015-04-17 19:56:21 +00004242 if (!Ty)
4243 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004244
JF Bastien30bf96b2015-02-22 19:32:03 +00004245 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004246 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4247 return Err;
David Blaikieb7a029872015-04-17 19:56:21 +00004248 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
David Blaikie85035652015-02-25 01:07:20 +00004249
Devang Patelaf206b82009-09-18 19:26:43 +00004250 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00004251 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00004252 }
Eli Friedman59b66882011-08-09 23:02:53 +00004253 case bitc::FUNC_CODE_INST_LOADATOMIC: {
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004254 // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
Eli Friedman59b66882011-08-09 23:02:53 +00004255 unsigned OpNum = 0;
4256 Value *Op;
4257 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004258 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004259 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004260
David Blaikie85035652015-02-25 01:07:20 +00004261 Type *Ty = nullptr;
4262 if (OpNum + 5 == Record.size())
4263 Ty = getTypeByID(Record[OpNum++]);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004264 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4265 return Err;
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004266 if (!Ty)
4267 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004268
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004269 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00004270 if (Ordering == AtomicOrdering::NotAtomic ||
4271 Ordering == AtomicOrdering::Release ||
4272 Ordering == AtomicOrdering::AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004273 return error("Invalid record");
JF Bastien800f87a2016-04-06 21:19:33 +00004274 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004275 return error("Invalid record");
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004276 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00004277
JF Bastien30bf96b2015-02-22 19:32:03 +00004278 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004279 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4280 return Err;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004281 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SSID);
David Blaikie85035652015-02-25 01:07:20 +00004282
Eli Friedman59b66882011-08-09 23:02:53 +00004283 InstructionList.push_back(I);
4284 break;
4285 }
David Blaikie612ddbf2015-04-22 04:14:42 +00004286 case bitc::FUNC_CODE_INST_STORE:
4287 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004288 unsigned OpNum = 0;
4289 Value *Val, *Ptr;
4290 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie612ddbf2015-04-22 04:14:42 +00004291 (BitCode == bitc::FUNC_CODE_INST_STORE
4292 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4293 : popValue(Record, OpNum, NextValueNo,
4294 cast<PointerType>(Ptr->getType())->getElementType(),
4295 Val)) ||
4296 OpNum + 2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004297 return error("Invalid record");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004298
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004299 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4300 return Err;
JF Bastien30bf96b2015-02-22 19:32:03 +00004301 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004302 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4303 return Err;
JF Bastien30bf96b2015-02-22 19:32:03 +00004304 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
Devang Patelaf206b82009-09-18 19:26:43 +00004305 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004306 break;
4307 }
David Blaikie50a06152015-04-22 04:14:46 +00004308 case bitc::FUNC_CODE_INST_STOREATOMIC:
4309 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004310 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
Eli Friedman59b66882011-08-09 23:02:53 +00004311 unsigned OpNum = 0;
4312 Value *Val, *Ptr;
4313 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Filipe Cabecinhas036e73c2016-06-05 18:43:33 +00004314 !isa<PointerType>(Ptr->getType()) ||
David Blaikie50a06152015-04-22 04:14:46 +00004315 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4316 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4317 : popValue(Record, OpNum, NextValueNo,
4318 cast<PointerType>(Ptr->getType())->getElementType(),
4319 Val)) ||
4320 OpNum + 4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004321 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004322
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004323 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4324 return Err;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004325 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00004326 if (Ordering == AtomicOrdering::NotAtomic ||
4327 Ordering == AtomicOrdering::Acquire ||
4328 Ordering == AtomicOrdering::AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004329 return error("Invalid record");
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004330 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
JF Bastien800f87a2016-04-06 21:19:33 +00004331 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004332 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004333
JF Bastien30bf96b2015-02-22 19:32:03 +00004334 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004335 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4336 return Err;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004337 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SSID);
Eli Friedman59b66882011-08-09 23:02:53 +00004338 InstructionList.push_back(I);
4339 break;
4340 }
David Blaikie2a661cd2015-04-28 04:30:29 +00004341 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004342 case bitc::FUNC_CODE_INST_CMPXCHG: {
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004343 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, ssid,
Tim Northover420a2162014-06-13 14:24:07 +00004344 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004345 unsigned OpNum = 0;
4346 Value *Ptr, *Cmp, *New;
4347 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie2a661cd2015-04-28 04:30:29 +00004348 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4349 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4350 : popValue(Record, OpNum, NextValueNo,
4351 cast<PointerType>(Ptr->getType())->getElementType(),
4352 Cmp)) ||
4353 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4354 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004355 return error("Invalid record");
4356 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
JF Bastien800f87a2016-04-06 21:19:33 +00004357 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
4358 SuccessOrdering == AtomicOrdering::Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004359 return error("Invalid record");
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004360 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
Tim Northovere94a5182014-03-11 10:48:52 +00004361
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004362 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
4363 return Err;
Tim Northovere94a5182014-03-11 10:48:52 +00004364 AtomicOrdering FailureOrdering;
4365 if (Record.size() < 7)
4366 FailureOrdering =
4367 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4368 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004369 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
Tim Northovere94a5182014-03-11 10:48:52 +00004370
4371 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004372 SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004373 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00004374
4375 if (Record.size() < 8) {
4376 // Before weak cmpxchgs existed, the instruction simply returned the
4377 // value loaded from memory, so bitcode files from that era will be
4378 // expecting the first component of a modern cmpxchg.
4379 CurBB->getInstList().push_back(I);
4380 I = ExtractValueInst::Create(I, 0);
4381 } else {
4382 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4383 }
4384
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004385 InstructionList.push_back(I);
4386 break;
4387 }
4388 case bitc::FUNC_CODE_INST_ATOMICRMW: {
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004389 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004390 unsigned OpNum = 0;
4391 Value *Ptr, *Val;
4392 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Filipe Cabecinhas6328f8e2016-06-05 18:43:40 +00004393 !isa<PointerType>(Ptr->getType()) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004394 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004395 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4396 OpNum+4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004397 return error("Invalid record");
4398 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004399 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4400 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004401 return error("Invalid record");
4402 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00004403 if (Ordering == AtomicOrdering::NotAtomic ||
4404 Ordering == AtomicOrdering::Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004405 return error("Invalid record");
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004406 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4407 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004408 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4409 InstructionList.push_back(I);
4410 break;
4411 }
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004412 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
Eli Friedmanfee02c62011-07-25 23:16:38 +00004413 if (2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004414 return error("Invalid record");
4415 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
JF Bastien800f87a2016-04-06 21:19:33 +00004416 if (Ordering == AtomicOrdering::NotAtomic ||
4417 Ordering == AtomicOrdering::Unordered ||
4418 Ordering == AtomicOrdering::Monotonic)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004419 return error("Invalid record");
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004420 SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
4421 I = new FenceInst(Context, Ordering, SSID);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004422 InstructionList.push_back(I);
4423 break;
4424 }
Chris Lattnerc44070802011-06-17 18:17:37 +00004425 case bitc::FUNC_CODE_INST_CALL: {
Sanjay Patelfa54ace2015-12-14 21:59:03 +00004426 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004427 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004428 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004429
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004430 unsigned OpNum = 0;
Reid Klecknerb5180542017-03-21 16:57:19 +00004431 AttributeList PAL = getAttributes(Record[OpNum++]);
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004432 unsigned CCInfo = Record[OpNum++];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004433
Sanjay Patelfa54ace2015-12-14 21:59:03 +00004434 FastMathFlags FMF;
4435 if ((CCInfo >> bitc::CALL_FMF) & 1) {
4436 FMF = getDecodedFastMathFlags(Record[OpNum++]);
4437 if (!FMF.any())
4438 return error("Fast math flags indicator set for call with no FMF");
4439 }
4440
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004441 FunctionType *FTy = nullptr;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004442 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004443 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004444 return error("Explicit call type is not a function type");
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004445
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004446 Value *Callee;
4447 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004448 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004449
Chris Lattner229907c2011-07-18 04:54:35 +00004450 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004451 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004452 return error("Callee is not a pointer type");
David Blaikie348de692015-04-23 21:36:23 +00004453 if (!FTy) {
4454 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4455 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004456 return error("Callee is not of pointer to function type");
David Blaikie348de692015-04-23 21:36:23 +00004457 } else if (OpTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004458 return error("Explicit call type does not match pointee type of "
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004459 "callee operand");
4460 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004461 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004462
Chris Lattner9f600c52007-05-03 22:04:19 +00004463 SmallVector<Value*, 16> Args;
4464 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004465 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004466 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00004467 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00004468 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00004469 Args.push_back(getValue(Record, OpNum, NextValueNo,
4470 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004471 if (!Args.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004472 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004473 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004474
Chris Lattner9f600c52007-05-03 22:04:19 +00004475 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00004476 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004477 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004478 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004479 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004480 while (OpNum != Record.size()) {
4481 Value *Op;
4482 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004483 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004484 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00004485 }
4486 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004487
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004488 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4489 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00004490 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00004491 cast<CallInst>(I)->setCallingConv(
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004492 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
Reid Kleckner5772b772014-04-24 20:14:34 +00004493 CallInst::TailCallKind TCK = CallInst::TCK_None;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004494 if (CCInfo & 1 << bitc::CALL_TAIL)
Reid Kleckner5772b772014-04-24 20:14:34 +00004495 TCK = CallInst::TCK_Tail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004496 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
Reid Kleckner5772b772014-04-24 20:14:34 +00004497 TCK = CallInst::TCK_MustTail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004498 if (CCInfo & (1 << bitc::CALL_NOTAIL))
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00004499 TCK = CallInst::TCK_NoTail;
Reid Kleckner5772b772014-04-24 20:14:34 +00004500 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00004501 cast<CallInst>(I)->setAttributes(PAL);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00004502 if (FMF.any()) {
4503 if (!isa<FPMathOperator>(I))
4504 return error("Fast-math-flags specified for call without "
4505 "floating-point scalar or vector return type");
4506 I->setFastMathFlags(FMF);
4507 }
Chris Lattner9f600c52007-05-03 22:04:19 +00004508 break;
4509 }
4510 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4511 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004512 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004513 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004514 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00004515 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00004516 if (!OpTy || !Op || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004517 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004518 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00004519 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00004520 break;
4521 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004522
4523 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
4524 // A call or an invoke can be optionally prefixed with some variable
4525 // number of operand bundle blocks. These blocks are read into
4526 // OperandBundles and consumed at the next call or invoke instruction.
4527
4528 if (Record.size() < 1 || Record[0] >= BundleTags.size())
4529 return error("Invalid record");
4530
Sanjoy Dasf79d3442015-11-18 08:30:07 +00004531 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004532
4533 unsigned OpNum = 1;
4534 while (OpNum != Record.size()) {
4535 Value *Op;
4536 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4537 return error("Invalid record");
4538 Inputs.push_back(Op);
4539 }
4540
Sanjoy Dasf79d3442015-11-18 08:30:07 +00004541 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004542 continue;
4543 }
Chris Lattner83930552007-05-01 07:01:57 +00004544 }
4545
4546 // Add instruction to end of current BB. If there is no current BB, reject
4547 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00004548 if (!CurBB) {
Reid Kleckner96ab8722017-05-18 17:24:10 +00004549 I->deleteValue();
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004550 return error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00004551 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004552 if (!OperandBundles.empty()) {
Reid Kleckner96ab8722017-05-18 17:24:10 +00004553 I->deleteValue();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004554 return error("Operand bundles found with no consumer");
4555 }
Chris Lattner83930552007-05-01 07:01:57 +00004556 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004557
Chris Lattner83930552007-05-01 07:01:57 +00004558 // If this was a terminator instruction, move to the next block.
4559 if (isa<TerminatorInst>(I)) {
4560 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00004561 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00004562 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004563
Chris Lattner83930552007-05-01 07:01:57 +00004564 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00004565 if (I && !I->getType()->isVoidTy())
David Majnemer8a1c45d2015-12-12 05:38:55 +00004566 ValueList.assignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00004567 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004568
Chris Lattner27d38752013-01-20 02:13:19 +00004569OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00004570
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004571 if (!OperandBundles.empty())
4572 return error("Operand bundles found with no consumer");
4573
Chris Lattner83930552007-05-01 07:01:57 +00004574 // Check the function list for unresolved values.
4575 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004576 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00004577 // We found at least one unresolved value. Nuke them all to avoid leaks.
4578 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00004579 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00004580 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00004581 delete A;
4582 }
4583 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004584 return error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00004585 }
Chris Lattner83930552007-05-01 07:01:57 +00004586 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004587
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00004588 // Unexpected unresolved metadata about to be dropped.
Mehdi Aminief27db82016-12-12 19:34:26 +00004589 if (MDLoader->hasFwdRefs())
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00004590 return error("Invalid function metadata: outgoing forward refs");
Dan Gohman9b9ff462010-08-25 20:23:38 +00004591
Chris Lattner85b7b402007-05-01 05:52:21 +00004592 // Trim the value list down to the size it was before we parsed this function.
4593 ValueList.shrinkTo(ModuleValueListSize);
Mehdi Aminief27db82016-12-12 19:34:26 +00004594 MDLoader->shrinkTo(ModuleMDLoaderSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00004595 std::vector<BasicBlock*>().swap(FunctionBBs);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004596 return Error::success();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004597}
4598
Rafael Espindola7d712032013-11-05 17:16:08 +00004599/// Find the function body in the bitcode stream
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004600Error BitcodeReader::findFunctionInStream(
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004601 Function *F,
4602 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004603 while (DeferredFunctionInfoIterator->second == 0) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00004604 // This is the fallback handling for the old format bitcode that
Teresa Johnson1493ad92015-10-10 14:18:36 +00004605 // didn't contain the function index in the VST, or when we have
4606 // an anonymous function which would not have a VST entry.
4607 // Assert that we have one of those two cases.
4608 assert(VSTOffset == 0 || !F->hasName());
4609 // Parse the next body in the stream and set its position in the
4610 // DeferredFunctionInfo map.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004611 if (Error Err = rememberAndSkipFunctionBodies())
4612 return Err;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004613 }
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004614 return Error::success();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004615}
4616
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004617SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
4618 if (Val == SyncScope::SingleThread || Val == SyncScope::System)
4619 return SyncScope::ID(Val);
4620 if (Val >= SSIDs.size())
4621 return SyncScope::System; // Map unknown synchronization scopes to system.
4622 return SSIDs[Val];
4623}
4624
Chris Lattner9eeada92007-05-18 04:02:46 +00004625//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004626// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00004627//===----------------------------------------------------------------------===//
4628
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00004629Error BitcodeReader::materialize(GlobalValue *GV) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004630 Function *F = dyn_cast<Function>(GV);
4631 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004632 if (!F || !F->isMaterializable())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004633 return Error::success();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004634
4635 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00004636 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004637 // If its position is recorded as 0, its body is somewhere in the stream
4638 // but we haven't seen it yet.
Rafael Espindola1c863ca2015-06-22 18:06:15 +00004639 if (DFII->second == 0)
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004640 if (Error Err = findFunctionInStream(F, DFII))
4641 return Err;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004642
Duncan P. N. Exon Smith03a04a52016-04-24 15:04:28 +00004643 // Materialize metadata before parsing any function bodies.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00004644 if (Error Err = materializeMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004645 return Err;
Duncan P. N. Exon Smith03a04a52016-04-24 15:04:28 +00004646
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004647 // Move the bit stream to the saved position of the deferred function body.
4648 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004649
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004650 if (Error Err = parseFunctionBody(F))
4651 return Err;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00004652 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00004653
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00004654 if (StripDebugInfo)
4655 stripDebugInfo(*F);
4656
Chandler Carruth7132e002007-08-04 01:51:18 +00004657 // Upgrade any old intrinsic calls in the function.
Rafael Espindola86e33402015-07-02 15:55:09 +00004658 for (auto &I : UpgradedIntrinsics) {
Rafael Espindola257a3532016-01-15 19:00:20 +00004659 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4660 UI != UE;) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004661 User *U = *UI;
4662 ++UI;
4663 if (CallInst *CI = dyn_cast<CallInst>(U))
4664 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00004665 }
4666 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004667
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00004668 // Update calls to the remangled intrinsics
4669 for (auto &I : RemangledIntrinsics)
4670 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4671 UI != UE;)
4672 // Don't expect any other users than call sites
4673 CallSite(*UI++).setCalledFunction(I.second);
4674
Peter Collingbourned4bff302015-11-05 22:03:56 +00004675 // Finish fn->subprogram upgrade for materialized functions.
Mehdi Aminief27db82016-12-12 19:34:26 +00004676 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
Peter Collingbourned4bff302015-11-05 22:03:56 +00004677 F->setSubprogram(SP);
4678
Mehdi Amini86623052016-12-16 19:16:29 +00004679 // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
4680 if (!MDLoader->isStrippingTBAA()) {
4681 for (auto &I : instructions(F)) {
4682 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
4683 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
4684 continue;
4685 MDLoader->setStripTBAA(true);
4686 stripTBAA(F->getParent());
4687 }
4688 }
4689
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004690 // Bring in any functions that this function forward-referenced via
4691 // blockaddresses.
4692 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00004693}
4694
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00004695Error BitcodeReader::materializeModule() {
4696 if (Error Err = materializeMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004697 return Err;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004698
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004699 // Promise to materialize all forward references.
4700 WillMaterializeAllForwardRefs = true;
4701
Chris Lattner06310bf2009-06-16 05:15:21 +00004702 // Iterate over the module, deserializing any functions that are still on
4703 // disk.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00004704 for (Function &F : *TheModule) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00004705 if (Error Err = materialize(&F))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004706 return Err;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004707 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00004708 // At this point, if there are any function bodies, parse the rest of
4709 // the bits in the module past the last function block we have recorded
4710 // through either lazy scanning or the VST.
4711 if (LastFunctionBlockBit || NextUnreadBit)
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004712 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
4713 ? LastFunctionBlockBit
4714 : NextUnreadBit))
4715 return Err;
Derek Schuff92ef9752012-02-29 00:07:09 +00004716
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004717 // Check that all block address forward references got resolved (as we
4718 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004719 if (!BasicBlockFwdRefs.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004720 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004721
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004722 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4723 // delete the old functions to clean up. We can't do this unless the entire
4724 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00004725 // with calls to the old function.
Rafael Espindola86e33402015-07-02 15:55:09 +00004726 for (auto &I : UpgradedIntrinsics) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004727 for (auto *U : I.first->users()) {
4728 if (CallInst *CI = dyn_cast<CallInst>(U))
4729 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00004730 }
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004731 if (!I.first->use_empty())
4732 I.first->replaceAllUsesWith(I.second);
4733 I.first->eraseFromParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00004734 }
Rafael Espindola4e721212015-07-02 16:22:40 +00004735 UpgradedIntrinsics.clear();
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00004736 // Do the same for remangled intrinsics
4737 for (auto &I : RemangledIntrinsics) {
4738 I.first->replaceAllUsesWith(I.second);
4739 I.first->eraseFromParent();
4740 }
4741 RemangledIntrinsics.clear();
Devang Patel80ae3492009-08-28 23:24:31 +00004742
Rafael Espindola79753a02015-12-18 21:18:57 +00004743 UpgradeDebugInfo(*TheModule);
Manman Renb5d7ff42016-05-25 23:14:48 +00004744
4745 UpgradeModuleFlags(*TheModule);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004746 return Error::success();
Chris Lattner9eeada92007-05-18 04:02:46 +00004747}
4748
Rafael Espindola2fa1e432014-12-03 07:18:23 +00004749std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4750 return IdentifiedStructTypes;
4751}
4752
Teresa Johnson26ab5772016-03-15 00:04:37 +00004753ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00004754 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
4755 StringRef ModulePath, unsigned ModuleId)
4756 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
4757 ModulePath(ModulePath), ModuleId(ModuleId) {}
4758
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00004759ModuleSummaryIndex::ModuleInfo *
4760ModuleSummaryIndexBitcodeReader::addThisModule() {
4761 return TheIndex.addModule(ModulePath, ModuleId);
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00004762}
Teresa Johnson403a7872015-10-04 14:33:43 +00004763
Peter Collingbourne9667b912017-05-04 18:03:25 +00004764std::pair<ValueInfo, GlobalValue::GUID>
4765ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
4766 auto VGI = ValueIdToValueInfoMap[ValueId];
4767 assert(VGI.first);
4768 return VGI;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004769}
4770
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004771void ModuleSummaryIndexBitcodeReader::setValueGUID(
4772 uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
4773 StringRef SourceFileName) {
4774 std::string GlobalId =
4775 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
4776 auto ValueGUID = GlobalValue::getGUID(GlobalId);
4777 auto OriginalNameID = ValueGUID;
4778 if (GlobalValue::isLocalLinkage(Linkage))
4779 OriginalNameID = GlobalValue::getGUID(ValueName);
4780 if (PrintSummaryGUIDs)
4781 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
4782 << ValueName << "\n";
Peter Collingbourne9667b912017-05-04 18:03:25 +00004783 ValueIdToValueInfoMap[ValueID] =
4784 std::make_pair(TheIndex.getOrInsertValueInfo(ValueGUID), OriginalNameID);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004785}
4786
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004787// Specialized value symbol table parser used when reading module index
Teresa Johnson28e457b2016-04-24 14:57:11 +00004788// blocks where we don't actually create global values. The parsed information
4789// is saved in the bitcode reader for use when later parsing summaries.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004790Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004791 uint64_t Offset,
4792 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004793 // With a strtab the VST is not required to parse the summary.
4794 if (UseStrtab)
4795 return Error::success();
4796
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004797 assert(Offset > 0 && "Expected non-zero VST offset");
4798 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
4799
Teresa Johnson403a7872015-10-04 14:33:43 +00004800 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
4801 return error("Invalid record");
4802
4803 SmallVector<uint64_t, 64> Record;
4804
4805 // Read all the records for this value table.
4806 SmallString<128> ValueName;
Eugene Zelenko1804a772016-08-25 00:45:04 +00004807
4808 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00004809 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4810
4811 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004812 case BitstreamEntry::SubBlock: // Handled for us already.
4813 case BitstreamEntry::Error:
4814 return error("Malformed block");
4815 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004816 // Done parsing VST, jump back to wherever we came from.
4817 Stream.JumpToBit(CurrentBit);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004818 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004819 case BitstreamEntry::Record:
4820 // The interesting case.
4821 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00004822 }
4823
4824 // Read a record.
4825 Record.clear();
4826 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004827 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
4828 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004829 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
4830 if (convertToString(Record, 1, ValueName))
4831 return error("Invalid record");
4832 unsigned ValueID = Record[0];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004833 assert(!SourceFileName.empty());
4834 auto VLI = ValueIdToLinkageMap.find(ValueID);
4835 assert(VLI != ValueIdToLinkageMap.end() &&
4836 "No linkage found for VST entry?");
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00004837 auto Linkage = VLI->second;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004838 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004839 ValueName.clear();
4840 break;
4841 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004842 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00004843 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004844 if (convertToString(Record, 2, ValueName))
4845 return error("Invalid record");
4846 unsigned ValueID = Record[0];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004847 assert(!SourceFileName.empty());
4848 auto VLI = ValueIdToLinkageMap.find(ValueID);
4849 assert(VLI != ValueIdToLinkageMap.end() &&
4850 "No linkage found for VST entry?");
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00004851 auto Linkage = VLI->second;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004852 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004853 ValueName.clear();
4854 break;
4855 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004856 case bitc::VST_CODE_COMBINED_ENTRY: {
4857 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
4858 unsigned ValueID = Record[0];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00004859 GlobalValue::GUID RefGUID = Record[1];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00004860 // The "original name", which is the second value of the pair will be
4861 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
Peter Collingbourne9667b912017-05-04 18:03:25 +00004862 ValueIdToValueInfoMap[ValueID] =
4863 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004864 break;
4865 }
Teresa Johnson403a7872015-10-04 14:33:43 +00004866 }
4867 }
4868}
4869
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004870// Parse just the blocks needed for building the index out of the module.
4871// At the end of this routine the module Index is populated with a map
Teresa Johnson28e457b2016-04-24 14:57:11 +00004872// from global value id to GlobalValueSummary objects.
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00004873Error ModuleSummaryIndexBitcodeReader::parseModule() {
Teresa Johnson403a7872015-10-04 14:33:43 +00004874 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4875 return error("Invalid record");
4876
Teresa Johnsone1164de2016-02-10 21:55:02 +00004877 SmallVector<uint64_t, 64> Record;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004878 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
4879 unsigned ValueId = 0;
Teresa Johnsone1164de2016-02-10 21:55:02 +00004880
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004881 // Read the index for this module.
Eugene Zelenko1804a772016-08-25 00:45:04 +00004882 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00004883 BitstreamEntry Entry = Stream.advance();
4884
4885 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004886 case BitstreamEntry::Error:
4887 return error("Malformed block");
4888 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004889 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004890
4891 case BitstreamEntry::SubBlock:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004892 switch (Entry.ID) {
4893 default: // Skip unknown content.
4894 if (Stream.SkipBlock())
4895 return error("Invalid record");
4896 break;
4897 case bitc::BLOCKINFO_BLOCK_ID:
4898 // Need to parse these to get abbrev ids (e.g. for VST)
Peter Collingbourne939c7d92016-11-08 04:16:57 +00004899 if (readBlockInfo())
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004900 return error("Malformed block");
4901 break;
4902 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004903 // Should have been parsed earlier via VSTOffset, unless there
4904 // is no summary section.
4905 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
4906 !SeenGlobalValSummary) &&
4907 "Expected early VST parse via VSTOffset record");
4908 if (Stream.SkipBlock())
4909 return error("Invalid record");
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004910 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004911 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00004912 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004913 assert(!SeenValueSymbolTable &&
4914 "Already read VST when parsing summary block?");
Teresa Johnson620c1402016-09-20 23:07:17 +00004915 // We might not have a VST if there were no values in the
4916 // summary. An empty summary block generated when we are
4917 // performing ThinLTO compiles so we don't later invoke
4918 // the regular LTO process on them.
4919 if (VSTOffset > 0) {
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004920 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
4921 return Err;
Teresa Johnson620c1402016-09-20 23:07:17 +00004922 SeenValueSymbolTable = true;
4923 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004924 SeenGlobalValSummary = true;
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00004925 if (Error Err = parseEntireSummary(Entry.ID))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004926 return Err;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004927 break;
4928 case bitc::MODULE_STRTAB_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004929 if (Error Err = parseModuleStringTable())
4930 return Err;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004931 break;
4932 }
4933 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00004934
Mehdi Aminid7ad2212016-04-01 05:33:11 +00004935 case BitstreamEntry::Record: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00004936 Record.clear();
4937 auto BitCode = Stream.readRecord(Entry.ID, Record);
4938 switch (BitCode) {
4939 default:
4940 break; // Default behavior, ignore unknown content.
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004941 case bitc::MODULE_CODE_VERSION: {
4942 if (Error Err = parseVersionRecord(Record).takeError())
4943 return Err;
4944 break;
4945 }
Teresa Johnsone1164de2016-02-10 21:55:02 +00004946 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004947 case bitc::MODULE_CODE_SOURCE_FILENAME: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00004948 SmallString<128> ValueName;
4949 if (convertToString(Record, 0, ValueName))
4950 return error("Invalid record");
4951 SourceFileName = ValueName.c_str();
4952 break;
4953 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00004954 /// MODULE_CODE_HASH: [5*i32]
4955 case bitc::MODULE_CODE_HASH: {
4956 if (Record.size() != 5)
4957 return error("Invalid hash length " + Twine(Record.size()).str());
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00004958 auto &Hash = addThisModule()->second.second;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00004959 int Pos = 0;
4960 for (auto &Val : Record) {
4961 assert(!(Val >> 32) && "Unexpected high bits set");
4962 Hash[Pos++] = Val;
4963 }
4964 break;
4965 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004966 /// MODULE_CODE_VSTOFFSET: [offset]
4967 case bitc::MODULE_CODE_VSTOFFSET:
4968 if (Record.size() < 1)
4969 return error("Invalid record");
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00004970 // Note that we subtract 1 here because the offset is relative to one
4971 // word before the start of the identification or module block, which
4972 // was historically always the start of the regular bitcode header.
4973 VSTOffset = Record[0] - 1;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004974 break;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004975 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
4976 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
4977 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
4978 // v2: [strtab offset, strtab size, v1]
Peter Collingbournef43e0ae2017-04-10 21:17:54 +00004979 case bitc::MODULE_CODE_GLOBALVAR:
4980 case bitc::MODULE_CODE_FUNCTION:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004981 case bitc::MODULE_CODE_ALIAS: {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004982 StringRef Name;
4983 ArrayRef<uint64_t> GVRecord;
4984 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
4985 if (GVRecord.size() <= 3)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004986 return error("Invalid record");
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004987 uint64_t RawLinkage = GVRecord[3];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004988 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004989 if (!UseStrtab) {
4990 ValueIdToLinkageMap[ValueId++] = Linkage;
4991 break;
4992 }
4993
4994 setValueGUID(ValueId++, Name, Linkage, SourceFileName);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004995 break;
4996 }
4997 }
Teresa Johnsone1164de2016-02-10 21:55:02 +00004998 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004999 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00005000 }
5001 }
5002}
5003
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005004std::vector<ValueInfo>
5005ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
5006 std::vector<ValueInfo> Ret;
5007 Ret.reserve(Record.size());
5008 for (uint64_t RefValueId : Record)
Peter Collingbourne9667b912017-05-04 18:03:25 +00005009 Ret.push_back(getValueInfoFromValueId(RefValueId).first);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005010 return Ret;
5011}
5012
5013std::vector<FunctionSummary::EdgeTy> ModuleSummaryIndexBitcodeReader::makeCallList(
5014 ArrayRef<uint64_t> Record, bool IsOldProfileFormat, bool HasProfile) {
5015 std::vector<FunctionSummary::EdgeTy> Ret;
5016 Ret.reserve(Record.size());
5017 for (unsigned I = 0, E = Record.size(); I != E; ++I) {
5018 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
Peter Collingbourne9667b912017-05-04 18:03:25 +00005019 ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005020 if (IsOldProfileFormat) {
5021 I += 1; // Skip old callsitecount field
5022 if (HasProfile)
5023 I += 1; // Skip old profilecount field
5024 } else if (HasProfile)
5025 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
Peter Collingbourne9667b912017-05-04 18:03:25 +00005026 Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo{Hotness}});
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005027 }
5028 return Ret;
5029}
5030
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005031// Eagerly parse the entire summary block. This populates the GlobalValueSummary
5032// objects in the index.
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005033Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
5034 if (Stream.EnterSubBlock(ID))
Teresa Johnson403a7872015-10-04 14:33:43 +00005035 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00005036 SmallVector<uint64_t, 64> Record;
Mehdi Amini8fe69362016-04-24 03:18:11 +00005037
5038 // Parse version
5039 {
5040 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5041 if (Entry.Kind != BitstreamEntry::Record)
5042 return error("Invalid Summary Block: record for version expected");
5043 if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
5044 return error("Invalid Summary Block: version expected");
5045 }
5046 const uint64_t Version = Record[0];
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005047 const bool IsOldProfileFormat = Version == 1;
Charles Saternos75da10d2017-08-04 16:00:58 +00005048 if (Version < 1 || Version > 4)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005049 return error("Invalid summary version " + Twine(Version) +
Charles Saternos75da10d2017-08-04 16:00:58 +00005050 ", 1, 2, 3 or 4 expected");
Mehdi Amini8fe69362016-04-24 03:18:11 +00005051 Record.clear();
5052
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005053 // Keep around the last seen summary to be used when we see an optional
5054 // "OriginalName" attachement.
5055 GlobalValueSummary *LastSeenSummary = nullptr;
Dehao Chen4a435e02017-03-14 17:33:01 +00005056 GlobalValue::GUID LastSeenGUID = 0;
Peter Collingbournefa3175f2017-02-11 03:19:22 +00005057
5058 // We can expect to see any number of type ID information records before
5059 // each function summary records; these variables store the information
5060 // collected so far so that it can be used to create the summary object.
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00005061 std::vector<GlobalValue::GUID> PendingTypeTests;
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005062 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
5063 PendingTypeCheckedLoadVCalls;
5064 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
5065 PendingTypeCheckedLoadConstVCalls;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005066
5067 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005068 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5069
5070 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005071 case BitstreamEntry::SubBlock: // Handled for us already.
5072 case BitstreamEntry::Error:
5073 return error("Malformed block");
5074 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005075 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005076 case BitstreamEntry::Record:
5077 // The interesting case.
5078 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005079 }
5080
5081 // Read a record. The record format depends on whether this
5082 // is a per-module index or a combined index file. In the per-module
5083 // case the records contain the associated value's ID for correlation
5084 // with VST entries. In the combined index the correlation is done
5085 // via the bitcode offset of the summary records (which were saved
5086 // in the combined index VST entries). The records also contain
5087 // information used for ThinLTO renaming and importing.
5088 Record.clear();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005089 auto BitCode = Stream.readRecord(Entry.ID, Record);
5090 switch (BitCode) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005091 default: // Default behavior: ignore.
5092 break;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005093 case bitc::FS_VALUE_GUID: { // [valueid, refguid]
5094 uint64_t ValueID = Record[0];
5095 GlobalValue::GUID RefGUID = Record[1];
Peter Collingbourne9667b912017-05-04 18:03:25 +00005096 ValueIdToValueInfoMap[ValueID] =
5097 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005098 break;
5099 }
Charles Saternos75da10d2017-08-04 16:00:58 +00005100 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
5101 // numrefs x valueid, n x (valueid)]
5102 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005103 // numrefs x valueid,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005104 // n x (valueid, hotness)]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005105 case bitc::FS_PERMODULE:
5106 case bitc::FS_PERMODULE_PROFILE: {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005107 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005108 uint64_t RawFlags = Record[1];
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005109 unsigned InstCount = Record[2];
Charles Saternos75da10d2017-08-04 16:00:58 +00005110 uint64_t RawFunFlags = 0;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005111 unsigned NumRefs = Record[3];
Charles Saternos75da10d2017-08-04 16:00:58 +00005112 int RefListStartIndex = 4;
5113 if (Version >= 4) {
5114 RawFunFlags = Record[3];
5115 NumRefs = Record[4];
5116 RefListStartIndex = 5;
5117 }
5118
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005119 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005120 // The module path string ref set in the summary must be owned by the
5121 // index's module string table. Since we don't have a module path
5122 // string table section in the per-module index, we create a single
5123 // module path string table entry with an empty (0) ID to take
5124 // ownership.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005125 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5126 assert(Record.size() >= RefListStartIndex + NumRefs &&
5127 "Record size inconsistent with number of references");
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005128 std::vector<ValueInfo> Refs = makeRefList(
5129 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005130 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005131 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
5132 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5133 IsOldProfileFormat, HasProfile);
5134 auto FS = llvm::make_unique<FunctionSummary>(
Charles Saternos75da10d2017-08-04 16:00:58 +00005135 Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs),
5136 std::move(Calls), std::move(PendingTypeTests),
5137 std::move(PendingTypeTestAssumeVCalls),
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005138 std::move(PendingTypeCheckedLoadVCalls),
5139 std::move(PendingTypeTestAssumeConstVCalls),
5140 std::move(PendingTypeCheckedLoadConstVCalls));
Peter Collingbourne704f8142016-12-22 02:52:23 +00005141 PendingTypeTests.clear();
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005142 PendingTypeTestAssumeVCalls.clear();
5143 PendingTypeCheckedLoadVCalls.clear();
5144 PendingTypeTestAssumeConstVCalls.clear();
5145 PendingTypeCheckedLoadConstVCalls.clear();
Peter Collingbourne9667b912017-05-04 18:03:25 +00005146 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005147 FS->setModulePath(addThisModule()->first());
Peter Collingbourne9667b912017-05-04 18:03:25 +00005148 FS->setOriginalName(VIAndOriginalGUID.second);
5149 TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
Teresa Johnsonbbe05452016-02-24 17:57:28 +00005150 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005151 }
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005152 // FS_ALIAS: [valueid, flags, valueid]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005153 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
5154 // they expect all aliasee summaries to be available.
5155 case bitc::FS_ALIAS: {
5156 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005157 uint64_t RawFlags = Record[1];
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005158 unsigned AliaseeID = Record[2];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005159 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005160 auto AS =
5161 llvm::make_unique<AliasSummary>(Flags, std::vector<ValueInfo>{});
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005162 // The module path string ref set in the summary must be owned by the
5163 // index's module string table. Since we don't have a module path
5164 // string table section in the per-module index, we create a single
5165 // module path string table entry with an empty (0) ID to take
5166 // ownership.
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005167 AS->setModulePath(addThisModule()->first());
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005168
Peter Collingbourne9667b912017-05-04 18:03:25 +00005169 GlobalValue::GUID AliaseeGUID =
5170 getValueInfoFromValueId(AliaseeID).first.getGUID();
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005171 auto AliaseeInModule =
5172 TheIndex.findSummaryInModule(AliaseeGUID, ModulePath);
5173 if (!AliaseeInModule)
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005174 return error("Alias expects aliasee summary to be parsed");
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005175 AS->setAliasee(AliaseeInModule);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005176
Peter Collingbourne9667b912017-05-04 18:03:25 +00005177 auto GUID = getValueInfoFromValueId(ValueID);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005178 AS->setOriginalName(GUID.second);
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005179 TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005180 break;
5181 }
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005182 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005183 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
5184 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005185 uint64_t RawFlags = Record[1];
5186 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005187 std::vector<ValueInfo> Refs =
5188 makeRefList(ArrayRef<uint64_t>(Record).slice(2));
5189 auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005190 FS->setModulePath(addThisModule()->first());
Peter Collingbourne9667b912017-05-04 18:03:25 +00005191 auto GUID = getValueInfoFromValueId(ValueID);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005192 FS->setOriginalName(GUID.second);
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005193 TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005194 break;
5195 }
Charles Saternos75da10d2017-08-04 16:00:58 +00005196 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005197 // numrefs x valueid, n x (valueid)]
Charles Saternos75da10d2017-08-04 16:00:58 +00005198 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005199 // numrefs x valueid, n x (valueid, hotness)]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005200 case bitc::FS_COMBINED:
5201 case bitc::FS_COMBINED_PROFILE: {
Teresa Johnson02e98332016-04-27 13:28:35 +00005202 unsigned ValueID = Record[0];
5203 uint64_t ModuleId = Record[1];
5204 uint64_t RawFlags = Record[2];
5205 unsigned InstCount = Record[3];
Charles Saternos75da10d2017-08-04 16:00:58 +00005206 uint64_t RawFunFlags = 0;
Teresa Johnson02e98332016-04-27 13:28:35 +00005207 unsigned NumRefs = Record[4];
Charles Saternos75da10d2017-08-04 16:00:58 +00005208 int RefListStartIndex = 5;
5209
5210 if (Version >= 4) {
5211 RawFunFlags = Record[4];
5212 NumRefs = Record[5];
5213 RefListStartIndex = 6;
5214 }
5215
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005216 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005217 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5218 assert(Record.size() >= RefListStartIndex + NumRefs &&
5219 "Record size inconsistent with number of references");
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005220 std::vector<ValueInfo> Refs = makeRefList(
5221 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005222 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005223 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
5224 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5225 IsOldProfileFormat, HasProfile);
Peter Collingbourne9667b912017-05-04 18:03:25 +00005226 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005227 auto FS = llvm::make_unique<FunctionSummary>(
Charles Saternos75da10d2017-08-04 16:00:58 +00005228 Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs),
5229 std::move(Edges), std::move(PendingTypeTests),
5230 std::move(PendingTypeTestAssumeVCalls),
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005231 std::move(PendingTypeCheckedLoadVCalls),
5232 std::move(PendingTypeTestAssumeConstVCalls),
5233 std::move(PendingTypeCheckedLoadConstVCalls));
Peter Collingbourne704f8142016-12-22 02:52:23 +00005234 PendingTypeTests.clear();
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005235 PendingTypeTestAssumeVCalls.clear();
5236 PendingTypeCheckedLoadVCalls.clear();
5237 PendingTypeTestAssumeConstVCalls.clear();
5238 PendingTypeCheckedLoadConstVCalls.clear();
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005239 LastSeenSummary = FS.get();
Peter Collingbourne9667b912017-05-04 18:03:25 +00005240 LastSeenGUID = VI.getGUID();
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005241 FS->setModulePath(ModuleIdMap[ModuleId]);
Peter Collingbourne9667b912017-05-04 18:03:25 +00005242 TheIndex.addGlobalValueSummary(VI, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005243 break;
5244 }
Teresa Johnson02e98332016-04-27 13:28:35 +00005245 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005246 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
5247 // they expect all aliasee summaries to be available.
5248 case bitc::FS_COMBINED_ALIAS: {
Teresa Johnson02e98332016-04-27 13:28:35 +00005249 unsigned ValueID = Record[0];
5250 uint64_t ModuleId = Record[1];
5251 uint64_t RawFlags = Record[2];
5252 unsigned AliaseeValueId = Record[3];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005253 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005254 auto AS = llvm::make_unique<AliasSummary>(Flags, std::vector<ValueInfo>{});
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005255 LastSeenSummary = AS.get();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005256 AS->setModulePath(ModuleIdMap[ModuleId]);
5257
Peter Collingbourne9667b912017-05-04 18:03:25 +00005258 auto AliaseeGUID =
5259 getValueInfoFromValueId(AliaseeValueId).first.getGUID();
Teresa Johnson02e98332016-04-27 13:28:35 +00005260 auto AliaseeInModule =
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005261 TheIndex.findSummaryInModule(AliaseeGUID, AS->modulePath());
Teresa Johnson02e98332016-04-27 13:28:35 +00005262 if (!AliaseeInModule)
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005263 return error("Alias expects aliasee summary to be parsed");
Teresa Johnson02e98332016-04-27 13:28:35 +00005264 AS->setAliasee(AliaseeInModule);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005265
Peter Collingbourne9667b912017-05-04 18:03:25 +00005266 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5267 LastSeenGUID = VI.getGUID();
5268 TheIndex.addGlobalValueSummary(VI, std::move(AS));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005269 break;
5270 }
Teresa Johnson02e98332016-04-27 13:28:35 +00005271 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005272 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
Teresa Johnson02e98332016-04-27 13:28:35 +00005273 unsigned ValueID = Record[0];
5274 uint64_t ModuleId = Record[1];
5275 uint64_t RawFlags = Record[2];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005276 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005277 std::vector<ValueInfo> Refs =
5278 makeRefList(ArrayRef<uint64_t>(Record).slice(3));
5279 auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005280 LastSeenSummary = FS.get();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005281 FS->setModulePath(ModuleIdMap[ModuleId]);
Peter Collingbourne9667b912017-05-04 18:03:25 +00005282 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5283 LastSeenGUID = VI.getGUID();
5284 TheIndex.addGlobalValueSummary(VI, std::move(FS));
Teresa Johnsonbbe05452016-02-24 17:57:28 +00005285 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005286 }
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005287 // FS_COMBINED_ORIGINAL_NAME: [original_name]
5288 case bitc::FS_COMBINED_ORIGINAL_NAME: {
5289 uint64_t OriginalName = Record[0];
5290 if (!LastSeenSummary)
5291 return error("Name attachment that does not follow a combined record");
5292 LastSeenSummary->setOriginalName(OriginalName);
Dehao Chen4a435e02017-03-14 17:33:01 +00005293 TheIndex.addOriginalName(LastSeenGUID, OriginalName);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005294 // Reset the LastSeenSummary
5295 LastSeenSummary = nullptr;
Dehao Chen4a435e02017-03-14 17:33:01 +00005296 LastSeenGUID = 0;
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00005297 break;
5298 }
5299 case bitc::FS_TYPE_TESTS: {
5300 assert(PendingTypeTests.empty());
5301 PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(),
5302 Record.end());
5303 break;
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005304 }
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005305 case bitc::FS_TYPE_TEST_ASSUME_VCALLS: {
5306 assert(PendingTypeTestAssumeVCalls.empty());
5307 for (unsigned I = 0; I != Record.size(); I += 2)
5308 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
5309 break;
5310 }
5311 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: {
5312 assert(PendingTypeCheckedLoadVCalls.empty());
5313 for (unsigned I = 0; I != Record.size(); I += 2)
5314 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
5315 break;
5316 }
5317 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: {
5318 PendingTypeTestAssumeConstVCalls.push_back(
5319 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5320 break;
5321 }
5322 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL: {
5323 PendingTypeCheckedLoadConstVCalls.push_back(
5324 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5325 break;
5326 }
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00005327 case bitc::FS_CFI_FUNCTION_DEFS: {
5328 std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
5329 for (unsigned I = 0; I != Record.size(); I += 2)
Evgeniy Stepanovf63d4142017-06-16 00:32:11 +00005330 CfiFunctionDefs.insert(
5331 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00005332 break;
5333 }
5334 case bitc::FS_CFI_FUNCTION_DECLS: {
5335 std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
5336 for (unsigned I = 0; I != Record.size(); I += 2)
Evgeniy Stepanovf63d4142017-06-16 00:32:11 +00005337 CfiFunctionDecls.insert(
5338 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00005339 break;
5340 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005341 }
5342 }
5343 llvm_unreachable("Exit infinite loop");
5344}
5345
5346// Parse the module string table block into the Index.
5347// This populates the ModulePathStringTable map in the index.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005348Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
Teresa Johnson403a7872015-10-04 14:33:43 +00005349 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5350 return error("Invalid record");
5351
5352 SmallVector<uint64_t, 64> Record;
5353
5354 SmallString<128> ModulePath;
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005355 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005356
5357 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005358 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5359
5360 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005361 case BitstreamEntry::SubBlock: // Handled for us already.
5362 case BitstreamEntry::Error:
5363 return error("Malformed block");
5364 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005365 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005366 case BitstreamEntry::Record:
5367 // The interesting case.
5368 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005369 }
5370
5371 Record.clear();
5372 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005373 default: // Default behavior: ignore.
5374 break;
5375 case bitc::MST_CODE_ENTRY: {
5376 // MST_ENTRY: [modid, namechar x N]
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005377 uint64_t ModuleId = Record[0];
5378
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005379 if (convertToString(Record, 1, ModulePath))
5380 return error("Invalid record");
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005381
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005382 LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
5383 ModuleIdMap[ModuleId] = LastSeenModule->first();
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005384
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005385 ModulePath.clear();
5386 break;
5387 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005388 /// MST_CODE_HASH: [5*i32]
5389 case bitc::MST_CODE_HASH: {
5390 if (Record.size() != 5)
5391 return error("Invalid hash length " + Twine(Record.size()).str());
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005392 if (!LastSeenModule)
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005393 return error("Invalid hash that does not follow a module path");
5394 int Pos = 0;
5395 for (auto &Val : Record) {
5396 assert(!(Val >> 32) && "Unexpected high bits set");
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005397 LastSeenModule->second.second[Pos++] = Val;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005398 }
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005399 // Reset LastSeenModule to avoid overriding the hash unexpectedly.
5400 LastSeenModule = nullptr;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005401 break;
5402 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005403 }
5404 }
5405 llvm_unreachable("Exit infinite loop");
5406}
5407
Rafael Espindola48da4f42013-11-04 16:16:24 +00005408namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +00005409
Peter Collingbourne4718f8b2016-05-24 20:13:46 +00005410// FIXME: This class is only here to support the transition to llvm::Error. It
5411// will be removed once this transition is complete. Clients should prefer to
5412// deal with the Error value directly, rather than converting to error_code.
Rafael Espindola25188c92014-06-12 01:45:43 +00005413class BitcodeErrorCategoryType : public std::error_category {
Reid Kleckner990504e2016-10-19 23:52:38 +00005414 const char *name() const noexcept override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00005415 return "llvm.bitcode";
5416 }
Craig Topper73156022014-03-02 09:09:27 +00005417 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00005418 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005419 switch (E) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00005420 case BitcodeError::CorruptedBitcode:
5421 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00005422 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00005423 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00005424 }
5425};
Eugene Zelenko1804a772016-08-25 00:45:04 +00005426
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00005427} // end anonymous namespace
Rafael Espindola48da4f42013-11-04 16:16:24 +00005428
Chris Bieneman770163e2014-09-19 20:29:02 +00005429static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5430
Rafael Espindolac3f2e732014-07-29 20:22:46 +00005431const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00005432 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005433}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00005434
Peter Collingbourne99b98c22017-06-27 23:50:24 +00005435static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
5436 unsigned Block, unsigned RecordID) {
5437 if (Stream.EnterSubBlock(Block))
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005438 return error("Invalid record");
5439
5440 StringRef Strtab;
5441 while (1) {
5442 BitstreamEntry Entry = Stream.advance();
5443 switch (Entry.Kind) {
5444 case BitstreamEntry::EndBlock:
5445 return Strtab;
5446
5447 case BitstreamEntry::Error:
5448 return error("Malformed block");
5449
5450 case BitstreamEntry::SubBlock:
5451 if (Stream.SkipBlock())
5452 return error("Malformed block");
5453 break;
5454
5455 case BitstreamEntry::Record:
5456 StringRef Blob;
5457 SmallVector<uint64_t, 1> Record;
Peter Collingbourne99b98c22017-06-27 23:50:24 +00005458 if (Stream.readRecord(Entry.ID, Record, &Blob) == RecordID)
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005459 Strtab = Blob;
5460 break;
5461 }
5462 }
5463}
5464
Chris Lattner6694f602007-04-29 07:54:31 +00005465//===----------------------------------------------------------------------===//
5466// External interface
5467//===----------------------------------------------------------------------===//
5468
Peter Collingbourne7a748032016-11-16 21:44:45 +00005469Expected<std::vector<BitcodeModule>>
5470llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
Peter Collingbourne8dde4cb2017-06-08 22:00:24 +00005471 auto FOrErr = getBitcodeFileContents(Buffer);
5472 if (!FOrErr)
5473 return FOrErr.takeError();
5474 return std::move(FOrErr->Mods);
5475}
5476
5477Expected<BitcodeFileContents>
5478llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
Peter Collingbourne7a748032016-11-16 21:44:45 +00005479 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5480 if (!StreamOrErr)
5481 return StreamOrErr.takeError();
5482 BitstreamCursor &Stream = *StreamOrErr;
5483
Peter Collingbourne8dde4cb2017-06-08 22:00:24 +00005484 BitcodeFileContents F;
Peter Collingbourne7a748032016-11-16 21:44:45 +00005485 while (true) {
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005486 uint64_t BCBegin = Stream.getCurrentByteNo();
5487
Peter Collingbourne7a748032016-11-16 21:44:45 +00005488 // We may be consuming bitcode from a client that leaves garbage at the end
5489 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
5490 // the end that there cannot possibly be another module, stop looking.
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005491 if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
Peter Collingbourne8dde4cb2017-06-08 22:00:24 +00005492 return F;
Peter Collingbourne7a748032016-11-16 21:44:45 +00005493
5494 BitstreamEntry Entry = Stream.advance();
5495 switch (Entry.Kind) {
5496 case BitstreamEntry::EndBlock:
5497 case BitstreamEntry::Error:
5498 return error("Malformed block");
5499
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005500 case BitstreamEntry::SubBlock: {
5501 uint64_t IdentificationBit = -1ull;
5502 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
5503 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5504 if (Stream.SkipBlock())
5505 return error("Malformed block");
5506
5507 Entry = Stream.advance();
5508 if (Entry.Kind != BitstreamEntry::SubBlock ||
5509 Entry.ID != bitc::MODULE_BLOCK_ID)
5510 return error("Malformed block");
5511 }
5512
5513 if (Entry.ID == bitc::MODULE_BLOCK_ID) {
5514 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5515 if (Stream.SkipBlock())
5516 return error("Malformed block");
5517
Peter Collingbourne8dde4cb2017-06-08 22:00:24 +00005518 F.Mods.push_back({Stream.getBitcodeBytes().slice(
5519 BCBegin, Stream.getCurrentByteNo() - BCBegin),
5520 Buffer.getBufferIdentifier(), IdentificationBit,
5521 ModuleBit});
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005522 continue;
5523 }
Peter Collingbourne7a748032016-11-16 21:44:45 +00005524
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005525 if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
Peter Collingbourne99b98c22017-06-27 23:50:24 +00005526 Expected<StringRef> Strtab =
5527 readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005528 if (!Strtab)
5529 return Strtab.takeError();
5530 // This string table is used by every preceding bitcode module that does
5531 // not have its own string table. A bitcode file may have multiple
5532 // string tables if it was created by binary concatenation, for example
5533 // with "llvm-cat -b".
Peter Collingbourne8dde4cb2017-06-08 22:00:24 +00005534 for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005535 if (!I->Strtab.empty())
5536 break;
5537 I->Strtab = *Strtab;
5538 }
Peter Collingbourne99b98c22017-06-27 23:50:24 +00005539 // Similarly, the string table is used by every preceding symbol table;
5540 // normally there will be just one unless the bitcode file was created
5541 // by binary concatenation.
5542 if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
5543 F.StrtabForSymtab = *Strtab;
5544 continue;
5545 }
5546
5547 if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
5548 Expected<StringRef> SymtabOrErr =
5549 readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
5550 if (!SymtabOrErr)
5551 return SymtabOrErr.takeError();
5552
5553 // We can expect the bitcode file to have multiple symbol tables if it
5554 // was created by binary concatenation. In that case we silently
5555 // ignore any subsequent symbol tables, which is fine because this is a
5556 // low level function. The client is expected to notice that the number
5557 // of modules in the symbol table does not match the number of modules
5558 // in the input file and regenerate the symbol table.
5559 if (F.Symtab.empty())
5560 F.Symtab = *SymtabOrErr;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005561 continue;
5562 }
5563
Peter Collingbourne7a748032016-11-16 21:44:45 +00005564 if (Stream.SkipBlock())
5565 return error("Malformed block");
5566 continue;
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005567 }
Peter Collingbourne7a748032016-11-16 21:44:45 +00005568 case BitstreamEntry::Record:
5569 Stream.skipRecord(Entry.ID);
5570 continue;
5571 }
5572 }
5573}
5574
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005575/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00005576///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005577/// This isn't always used in a lazy context. In particular, it's also used by
Peter Collingbourne7a748032016-11-16 21:44:45 +00005578/// \a parseModule(). If this is truly lazy, then we need to eagerly pull
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005579/// in forward-referenced functions from block address references.
5580///
Rafael Espindola728074b2015-06-17 00:40:56 +00005581/// \param[in] MaterializeAll Set to \c true if we should materialize
5582/// everything.
Peter Collingbourne7a748032016-11-16 21:44:45 +00005583Expected<std::unique_ptr<Module>>
5584BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005585 bool ShouldLazyLoadMetadata, bool IsImporting) {
Peter Collingbourne7a748032016-11-16 21:44:45 +00005586 BitstreamCursor Stream(Buffer);
Peter Collingbournec0032b72016-11-11 19:50:10 +00005587
Peter Collingbourne7a748032016-11-16 21:44:45 +00005588 std::string ProducerIdentification;
5589 if (IdentificationBit != -1ull) {
5590 Stream.JumpToBit(IdentificationBit);
5591 Expected<std::string> ProducerIdentificationOrErr =
5592 readIdentificationBlock(Stream);
5593 if (!ProducerIdentificationOrErr)
5594 return ProducerIdentificationOrErr.takeError();
5595
5596 ProducerIdentification = *ProducerIdentificationOrErr;
5597 }
5598
5599 Stream.JumpToBit(ModuleBit);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005600 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
5601 Context);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005602
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005603 std::unique_ptr<Module> M =
Peter Collingbourne7a748032016-11-16 21:44:45 +00005604 llvm::make_unique<Module>(ModuleIdentifier, Context);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005605 M->setMaterializer(R);
Rafael Espindolab7993462012-01-02 07:49:53 +00005606
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005607 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005608 if (Error Err =
5609 R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting))
Peter Collingbourned9445c42016-11-13 07:00:17 +00005610 return std::move(Err);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005611
5612 if (MaterializeAll) {
5613 // Read in the entire module, and destroy the BitcodeReader.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00005614 if (Error Err = M->materializeAll())
Peter Collingbourned9445c42016-11-13 07:00:17 +00005615 return std::move(Err);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005616 } else {
5617 // Resolve forward references from blockaddresses.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005618 if (Error Err = R->materializeForwardReferencedFunctions())
Peter Collingbourned9445c42016-11-13 07:00:17 +00005619 return std::move(Err);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005620 }
5621 return std::move(M);
Chris Lattner6694f602007-04-29 07:54:31 +00005622}
5623
Peter Collingbourned9445c42016-11-13 07:00:17 +00005624Expected<std::unique_ptr<Module>>
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005625BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
5626 bool IsImporting) {
5627 return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting);
Peter Collingbourne7a748032016-11-16 21:44:45 +00005628}
5629
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005630// Parse the specified bitcode buffer and merge the index into CombinedIndex.
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005631// We don't use ModuleIdentifier here because the client may need to control the
5632// module path used in the combined summary (e.g. when reading summaries for
5633// regular LTO modules).
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005634Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005635 StringRef ModulePath, uint64_t ModuleId) {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005636 BitstreamCursor Stream(Buffer);
5637 Stream.JumpToBit(ModuleBit);
5638
5639 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005640 ModulePath, ModuleId);
Peter Collingbourne440e2042017-05-01 22:48:10 +00005641 return R.parseModule();
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005642}
5643
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005644// Parse the specified bitcode buffer, returning the function info index.
5645Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
5646 BitstreamCursor Stream(Buffer);
5647 Stream.JumpToBit(ModuleBit);
5648
5649 auto Index = llvm::make_unique<ModuleSummaryIndex>();
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005650 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
5651 ModuleIdentifier, 0);
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005652
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005653 if (Error Err = R.parseModule())
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005654 return std::move(Err);
5655
5656 return std::move(Index);
5657}
5658
5659// Check if the given bitcode buffer contains a global value summary block.
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005660Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005661 BitstreamCursor Stream(Buffer);
5662 Stream.JumpToBit(ModuleBit);
5663
5664 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5665 return error("Invalid record");
5666
5667 while (true) {
5668 BitstreamEntry Entry = Stream.advance();
5669
5670 switch (Entry.Kind) {
5671 case BitstreamEntry::Error:
5672 return error("Malformed block");
5673 case BitstreamEntry::EndBlock:
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005674 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false};
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005675
5676 case BitstreamEntry::SubBlock:
5677 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID)
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005678 return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true};
5679
5680 if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID)
5681 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true};
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005682
5683 // Ignore other sub-blocks.
5684 if (Stream.SkipBlock())
5685 return error("Malformed block");
5686 continue;
5687
5688 case BitstreamEntry::Record:
5689 Stream.skipRecord(Entry.ID);
5690 continue;
5691 }
5692 }
5693}
5694
5695static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
Peter Collingbourne7a748032016-11-16 21:44:45 +00005696 Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
5697 if (!MsOrErr)
5698 return MsOrErr.takeError();
5699
5700 if (MsOrErr->size() != 1)
5701 return error("Expected a single module");
5702
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005703 return (*MsOrErr)[0];
5704}
5705
5706Expected<std::unique_ptr<Module>>
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005707llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
5708 bool ShouldLazyLoadMetadata, bool IsImporting) {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005709 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5710 if (!BM)
5711 return BM.takeError();
5712
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005713 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005714}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005715
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005716Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
5717 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5718 bool ShouldLazyLoadMetadata, bool IsImporting) {
5719 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
5720 IsImporting);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005721 if (MOrErr)
5722 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
5723 return MOrErr;
5724}
5725
Peter Collingbourne7a748032016-11-16 21:44:45 +00005726Expected<std::unique_ptr<Module>>
5727BitcodeModule::parseModule(LLVMContext &Context) {
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005728 return getModuleImpl(Context, true, false, false);
Chad Rosierca2567b2011-12-07 21:44:12 +00005729 // TODO: Restore the use-lists to the in-memory state when the bitcode was
5730 // written. We must defer until the Module has been fully materialized.
Chris Lattner6694f602007-04-29 07:54:31 +00005731}
Bill Wendling0198ce02010-10-06 01:22:42 +00005732
Peter Collingbourne7a748032016-11-16 21:44:45 +00005733Expected<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
5734 LLVMContext &Context) {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005735 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5736 if (!BM)
5737 return BM.takeError();
Peter Collingbourne7a748032016-11-16 21:44:45 +00005738
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005739 return BM->parseModule(Context);
Peter Collingbourne7a748032016-11-16 21:44:45 +00005740}
5741
Peter Collingbournecd513a42016-11-11 19:50:24 +00005742Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
5743 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
Peter Collingbournec0032b72016-11-11 19:50:10 +00005744 if (!StreamOrErr)
Peter Collingbournecd513a42016-11-11 19:50:24 +00005745 return StreamOrErr.takeError();
Peter Collingbournec0032b72016-11-11 19:50:10 +00005746
Peter Collingbournecd513a42016-11-11 19:50:24 +00005747 return readTriple(*StreamOrErr);
Bill Wendling0198ce02010-10-06 01:22:42 +00005748}
Teresa Johnson403a7872015-10-04 14:33:43 +00005749
Peter Collingbournecd513a42016-11-11 19:50:24 +00005750Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
5751 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
Peter Collingbournec0032b72016-11-11 19:50:10 +00005752 if (!StreamOrErr)
Peter Collingbournecd513a42016-11-11 19:50:24 +00005753 return StreamOrErr.takeError();
Peter Collingbournec0032b72016-11-11 19:50:10 +00005754
Peter Collingbournecd513a42016-11-11 19:50:24 +00005755 return hasObjCCategory(*StreamOrErr);
Mehdi Aminie75aa6f2016-07-11 23:10:18 +00005756}
5757
Peter Collingbournecd513a42016-11-11 19:50:24 +00005758Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
5759 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
Peter Collingbournec0032b72016-11-11 19:50:10 +00005760 if (!StreamOrErr)
Peter Collingbournecd513a42016-11-11 19:50:24 +00005761 return StreamOrErr.takeError();
5762
5763 return readIdentificationCode(*StreamOrErr);
Mehdi Amini3383ccc2015-11-09 02:46:41 +00005764}
5765
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005766Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
5767 ModuleSummaryIndex &CombinedIndex,
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005768 uint64_t ModuleId) {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005769 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5770 if (!BM)
5771 return BM.takeError();
5772
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005773 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005774}
5775
Peter Collingbourne6de481a2016-11-11 19:50:39 +00005776Expected<std::unique_ptr<ModuleSummaryIndex>>
5777llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005778 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5779 if (!BM)
5780 return BM.takeError();
Peter Collingbournec0032b72016-11-11 19:50:10 +00005781
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005782 return BM->getSummary();
Teresa Johnson403a7872015-10-04 14:33:43 +00005783}
5784
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005785Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005786 Expected<BitcodeModule> BM = getSingleModule(Buffer);
5787 if (!BM)
5788 return BM.takeError();
Teresa Johnson403a7872015-10-04 14:33:43 +00005789
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005790 return BM->getLTOInfo();
Teresa Johnson403a7872015-10-04 14:33:43 +00005791}
Peter Collingbournec15d60b2017-05-01 20:42:32 +00005792
5793Expected<std::unique_ptr<ModuleSummaryIndex>>
Teresa Johnson4cd12ce2017-05-12 19:32:11 +00005794llvm::getModuleSummaryIndexForFile(StringRef Path,
5795 bool IgnoreEmptyThinLTOIndexFile) {
Peter Collingbournec15d60b2017-05-01 20:42:32 +00005796 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
5797 MemoryBuffer::getFileOrSTDIN(Path);
5798 if (!FileOrErr)
5799 return errorCodeToError(FileOrErr.getError());
5800 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
5801 return nullptr;
5802 return getModuleSummaryIndex(**FileOrErr);
5803}