blob: 87bd8f625faf05441ff4317b3a90998fbd76c7f1 [file] [log] [blame]
Chris Lattner1314b992007-04-22 06:23:29 +00001//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner1314b992007-04-22 06:23:29 +00006//
7//===----------------------------------------------------------------------===//
Chris Lattner1314b992007-04-22 06:23:29 +00008
Teresa Johnsonad176792016-11-11 05:34:58 +00009#include "llvm/Bitcode/BitcodeReader.h"
Mehdi Aminief27db82016-12-12 19:34:26 +000010#include "MetadataLoader.h"
11#include "ValueList.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000012#include "llvm/ADT/APFloat.h"
13#include "llvm/ADT/APInt.h"
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/DenseMap.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000016#include "llvm/ADT/Optional.h"
Benjamin Kramer0a446fd2015-03-01 21:28:53 +000017#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SmallString.h"
19#include "llvm/ADT/SmallVector.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000020#include "llvm/ADT/StringRef.h"
David Majnemer3087b222015-01-20 05:58:07 +000021#include "llvm/ADT/Triple.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000022#include "llvm/ADT/Twine.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000023#include "llvm/Bitcode/BitstreamReader.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000024#include "llvm/Bitcode/LLVMBitCodes.h"
Nico Weber432a3882018-04-30 14:59:11 +000025#include "llvm/Config/llvm-config.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000026#include "llvm/IR/Argument.h"
27#include "llvm/IR/Attributes.h"
Chandler Carruth91065212014-03-05 10:34:14 +000028#include "llvm/IR/AutoUpgrade.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000029#include "llvm/IR/BasicBlock.h"
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +000030#include "llvm/IR/CallSite.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000031#include "llvm/IR/CallingConv.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000032#include "llvm/IR/Comdat.h"
33#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Constants.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000035#include "llvm/IR/DataLayout.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/Function.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000041#include "llvm/IR/GVMaterializer.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000042#include "llvm/IR/GlobalAlias.h"
43#include "llvm/IR/GlobalIFunc.h"
44#include "llvm/IR/GlobalIndirectSymbol.h"
45#include "llvm/IR/GlobalObject.h"
46#include "llvm/IR/GlobalValue.h"
47#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/InlineAsm.h"
Mehdi Amini86623052016-12-16 19:16:29 +000049#include "llvm/IR/InstIterator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000050#include "llvm/IR/InstrTypes.h"
51#include "llvm/IR/Instruction.h"
52#include "llvm/IR/Instructions.h"
53#include "llvm/IR/Intrinsics.h"
Manman Ren209b17c2013-09-28 00:22:27 +000054#include "llvm/IR/LLVMContext.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000055#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000056#include "llvm/IR/Module.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000057#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000059#include "llvm/IR/Type.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000060#include "llvm/IR/Value.h"
Mehdi Amini86623052016-12-16 19:16:29 +000061#include "llvm/IR/Verifier.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000062#include "llvm/Support/AtomicOrdering.h"
63#include "llvm/Support/Casting.h"
Teresa Johnson916495d2016-04-04 18:52:58 +000064#include "llvm/Support/CommandLine.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000065#include "llvm/Support/Compiler.h"
Teresa Johnson916495d2016-04-04 18:52:58 +000066#include "llvm/Support/Debug.h"
Peter Collingbourne58f7f072016-11-09 00:51:04 +000067#include "llvm/Support/Error.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000068#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000069#include "llvm/Support/ErrorOr.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000070#include "llvm/Support/ManagedStatic.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000071#include "llvm/Support/MathExtras.h"
Chris Lattner6694f602007-04-29 07:54:31 +000072#include "llvm/Support/MemoryBuffer.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000073#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000074#include <algorithm>
75#include <cassert>
76#include <cstddef>
77#include <cstdint>
Benjamin Kramercced8be2015-03-17 20:40:24 +000078#include <deque>
Eugene Zelenko1804a772016-08-25 00:45:04 +000079#include <map>
80#include <memory>
Eugene Zelenko975293f2017-09-07 23:28:24 +000081#include <set>
Eugene Zelenko1804a772016-08-25 00:45:04 +000082#include <string>
83#include <system_error>
84#include <tuple>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000085#include <utility>
Eugene Zelenko1804a772016-08-25 00:45:04 +000086#include <vector>
Eugene Zelenko6ac3f732016-01-26 18:48:36 +000087
Chris Lattner1314b992007-04-22 06:23:29 +000088using namespace llvm;
89
Teresa Johnson916495d2016-04-04 18:52:58 +000090static cl::opt<bool> PrintSummaryGUIDs(
91 "print-summary-global-ids", cl::init(false), cl::Hidden,
92 cl::desc(
93 "Print the global id for each value when reading the module summary"));
94
Benjamin Kramercced8be2015-03-17 20:40:24 +000095namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +000096
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +000097enum {
98 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
99};
100
Eugene Zelenko975293f2017-09-07 23:28:24 +0000101} // end anonymous namespace
102
103static Error error(const Twine &Message) {
Peter Collingbournec0032b72016-11-11 19:50:10 +0000104 return make_error<StringError>(
105 Message, make_error_code(BitcodeError::CorruptedBitcode));
106}
107
108/// Helper to read the header common to all bitcode files.
Eugene Zelenko975293f2017-09-07 23:28:24 +0000109static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
Peter Collingbournec0032b72016-11-11 19:50:10 +0000110 // Sniff for the signature.
111 if (!Stream.canSkipToPos(4) ||
112 Stream.Read(8) != 'B' ||
113 Stream.Read(8) != 'C' ||
114 Stream.Read(4) != 0x0 ||
115 Stream.Read(4) != 0xC ||
116 Stream.Read(4) != 0xE ||
117 Stream.Read(4) != 0xD)
118 return false;
119 return true;
120}
121
Eugene Zelenko975293f2017-09-07 23:28:24 +0000122static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
Peter Collingbournec0032b72016-11-11 19:50:10 +0000123 const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
124 const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
125
126 if (Buffer.getBufferSize() & 3)
127 return error("Invalid bitcode signature");
128
129 // If we have a wrapper header, parse it and ignore the non-bc file contents.
130 // The magic number is 0x0B17C0DE stored in little endian.
131 if (isBitcodeWrapper(BufPtr, BufEnd))
132 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
133 return error("Invalid bitcode wrapper header");
134
135 BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
136 if (!hasValidBitcodeHeader(Stream))
137 return error("Invalid bitcode signature");
138
139 return std::move(Stream);
140}
141
Peter Collingbournecd513a42016-11-11 19:50:24 +0000142/// Convert a string from a record into an std::string, return true on failure.
143template <typename StrTy>
144static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
145 StrTy &Result) {
146 if (Idx > Record.size())
147 return true;
148
149 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
150 Result += (char)Record[i];
151 return false;
152}
153
Mehdi Amini86623052016-12-16 19:16:29 +0000154// Strip all the TBAA attachment for the module.
Eugene Zelenko975293f2017-09-07 23:28:24 +0000155static void stripTBAA(Module *M) {
Mehdi Amini86623052016-12-16 19:16:29 +0000156 for (auto &F : *M) {
157 if (F.isMaterializable())
158 continue;
159 for (auto &I : instructions(F))
160 I.setMetadata(LLVMContext::MD_tbaa, nullptr);
161 }
162}
163
Peter Collingbournecd513a42016-11-11 19:50:24 +0000164/// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
165/// "epoch" encoded in the bitcode, and return the producer name if any.
Eugene Zelenko975293f2017-09-07 23:28:24 +0000166static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
Peter Collingbournecd513a42016-11-11 19:50:24 +0000167 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
168 return error("Invalid record");
169
170 // Read all the records.
171 SmallVector<uint64_t, 64> Record;
172
173 std::string ProducerIdentification;
174
175 while (true) {
176 BitstreamEntry Entry = Stream.advance();
177
178 switch (Entry.Kind) {
179 default:
180 case BitstreamEntry::Error:
181 return error("Malformed block");
182 case BitstreamEntry::EndBlock:
183 return ProducerIdentification;
184 case BitstreamEntry::Record:
185 // The interesting case.
186 break;
187 }
188
189 // Read a record.
190 Record.clear();
191 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
192 switch (BitCode) {
193 default: // Default behavior: reject
194 return error("Invalid value");
195 case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
196 convertToString(Record, 0, ProducerIdentification);
197 break;
198 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
199 unsigned epoch = (unsigned)Record[0];
200 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
201 return error(
202 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
203 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
204 }
205 }
206 }
207 }
208}
209
Eugene Zelenko975293f2017-09-07 23:28:24 +0000210static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
Peter Collingbournecd513a42016-11-11 19:50:24 +0000211 // We expect a number of well-defined blocks, though we don't necessarily
212 // need to understand them all.
213 while (true) {
214 if (Stream.AtEndOfStream())
215 return "";
216
217 BitstreamEntry Entry = Stream.advance();
218 switch (Entry.Kind) {
219 case BitstreamEntry::EndBlock:
220 case BitstreamEntry::Error:
221 return error("Malformed block");
222
223 case BitstreamEntry::SubBlock:
224 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
225 return readIdentificationBlock(Stream);
226
227 // Ignore other sub-blocks.
228 if (Stream.SkipBlock())
229 return error("Malformed block");
230 continue;
231 case BitstreamEntry::Record:
232 Stream.skipRecord(Entry.ID);
233 continue;
234 }
235 }
236}
237
Eugene Zelenko975293f2017-09-07 23:28:24 +0000238static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
Peter Collingbournecd513a42016-11-11 19:50:24 +0000239 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
240 return error("Invalid record");
241
242 SmallVector<uint64_t, 64> Record;
243 // Read all the records for this module.
244
245 while (true) {
246 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
247
248 switch (Entry.Kind) {
249 case BitstreamEntry::SubBlock: // Handled for us already.
250 case BitstreamEntry::Error:
251 return error("Malformed block");
252 case BitstreamEntry::EndBlock:
253 return false;
254 case BitstreamEntry::Record:
255 // The interesting case.
256 break;
257 }
258
259 // Read a record.
260 switch (Stream.readRecord(Entry.ID, Record)) {
261 default:
262 break; // Default behavior, ignore unknown content.
263 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
264 std::string S;
265 if (convertToString(Record, 0, S))
266 return error("Invalid record");
267 // Check for the i386 and other (x86_64, ARM) conventions
Saleem Abdulrasool46a59fd2017-10-06 18:06:59 +0000268 if (S.find("__DATA,__objc_catlist") != std::string::npos ||
Peter Collingbournecd513a42016-11-11 19:50:24 +0000269 S.find("__OBJC,__category") != std::string::npos)
270 return true;
271 break;
272 }
273 }
274 Record.clear();
275 }
276 llvm_unreachable("Exit infinite loop");
277}
278
Eugene Zelenko975293f2017-09-07 23:28:24 +0000279static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
Peter Collingbournecd513a42016-11-11 19:50:24 +0000280 // We expect a number of well-defined blocks, though we don't necessarily
281 // need to understand them all.
282 while (true) {
283 BitstreamEntry Entry = Stream.advance();
284
285 switch (Entry.Kind) {
286 case BitstreamEntry::Error:
287 return error("Malformed block");
288 case BitstreamEntry::EndBlock:
289 return false;
290
291 case BitstreamEntry::SubBlock:
292 if (Entry.ID == bitc::MODULE_BLOCK_ID)
293 return hasObjCCategoryInModule(Stream);
294
295 // Ignore other sub-blocks.
296 if (Stream.SkipBlock())
297 return error("Malformed block");
298 continue;
299
300 case BitstreamEntry::Record:
301 Stream.skipRecord(Entry.ID);
302 continue;
303 }
304 }
305}
306
Eugene Zelenko975293f2017-09-07 23:28:24 +0000307static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
Peter Collingbournecd513a42016-11-11 19:50:24 +0000308 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
309 return error("Invalid record");
310
311 SmallVector<uint64_t, 64> Record;
312
313 std::string Triple;
314
315 // Read all the records for this module.
316 while (true) {
317 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
318
319 switch (Entry.Kind) {
320 case BitstreamEntry::SubBlock: // Handled for us already.
321 case BitstreamEntry::Error:
322 return error("Malformed block");
323 case BitstreamEntry::EndBlock:
324 return Triple;
325 case BitstreamEntry::Record:
326 // The interesting case.
327 break;
328 }
329
330 // Read a record.
331 switch (Stream.readRecord(Entry.ID, Record)) {
332 default: break; // Default behavior, ignore unknown content.
333 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
334 std::string S;
335 if (convertToString(Record, 0, S))
336 return error("Invalid record");
337 Triple = S;
338 break;
339 }
340 }
341 Record.clear();
342 }
343 llvm_unreachable("Exit infinite loop");
344}
345
Eugene Zelenko975293f2017-09-07 23:28:24 +0000346static Expected<std::string> readTriple(BitstreamCursor &Stream) {
Peter Collingbournecd513a42016-11-11 19:50:24 +0000347 // We expect a number of well-defined blocks, though we don't necessarily
348 // need to understand them all.
349 while (true) {
350 BitstreamEntry Entry = Stream.advance();
351
352 switch (Entry.Kind) {
353 case BitstreamEntry::Error:
354 return error("Malformed block");
355 case BitstreamEntry::EndBlock:
356 return "";
357
358 case BitstreamEntry::SubBlock:
359 if (Entry.ID == bitc::MODULE_BLOCK_ID)
360 return readModuleTriple(Stream);
361
362 // Ignore other sub-blocks.
363 if (Stream.SkipBlock())
364 return error("Malformed block");
365 continue;
366
367 case BitstreamEntry::Record:
368 Stream.skipRecord(Entry.ID);
369 continue;
370 }
371 }
372}
373
Eugene Zelenko975293f2017-09-07 23:28:24 +0000374namespace {
375
Peter Collingbourne6e860752016-09-23 18:27:42 +0000376class BitcodeReaderBase {
377protected:
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000378 BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
379 : Stream(std::move(Stream)), Strtab(Strtab) {
Peter Collingbournec0032b72016-11-11 19:50:10 +0000380 this->Stream.setBlockInfo(&BlockInfo);
381 }
Peter Collingbourne6e860752016-09-23 18:27:42 +0000382
Peter Collingbourne77c89b62016-11-08 04:17:11 +0000383 BitstreamBlockInfo BlockInfo;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000384 BitstreamCursor Stream;
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000385 StringRef Strtab;
386
387 /// In version 2 of the bitcode we store names of global values and comdats in
388 /// a string table rather than in the VST.
389 bool UseStrtab = false;
Peter Collingbourne6e860752016-09-23 18:27:42 +0000390
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000391 Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
392
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000393 /// If this module uses a string table, pop the reference to the string table
394 /// and return the referenced string and the rest of the record. Otherwise
395 /// just return the record itself.
396 std::pair<StringRef, ArrayRef<uint64_t>>
397 readNameFromStrtab(ArrayRef<uint64_t> Record);
398
Peter Collingbourne939c7d92016-11-08 04:16:57 +0000399 bool readBlockInfo();
Peter Collingbourne6e860752016-09-23 18:27:42 +0000400
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000401 // Contains an arbitrary and optional string identifying the bitcode producer
402 std::string ProducerIdentification;
403
404 Error error(const Twine &Message);
Peter Collingbourne6e860752016-09-23 18:27:42 +0000405};
406
Eugene Zelenko975293f2017-09-07 23:28:24 +0000407} // end anonymous namespace
408
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000409Error BitcodeReaderBase::error(const Twine &Message) {
410 std::string FullMsg = Message.str();
411 if (!ProducerIdentification.empty())
412 FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
413 LLVM_VERSION_STRING "')";
Peter Collingbournec0032b72016-11-11 19:50:10 +0000414 return ::error(FullMsg);
Peter Collingbourne6e860752016-09-23 18:27:42 +0000415}
416
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000417Expected<unsigned>
418BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
Eugene Zelenko975293f2017-09-07 23:28:24 +0000419 if (Record.empty())
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000420 return error("Invalid record");
421 unsigned ModuleVersion = Record[0];
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000422 if (ModuleVersion > 2)
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000423 return error("Invalid value");
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000424 UseStrtab = ModuleVersion >= 2;
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000425 return ModuleVersion;
426}
427
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000428std::pair<StringRef, ArrayRef<uint64_t>>
429BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
430 if (!UseStrtab)
431 return {"", Record};
432 // Invalid reference. Let the caller complain about the record being empty.
433 if (Record[0] + Record[1] > Strtab.size())
434 return {"", {}};
435 return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
436}
437
Eugene Zelenko975293f2017-09-07 23:28:24 +0000438namespace {
439
Peter Collingbourne6e860752016-09-23 18:27:42 +0000440class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
441 LLVMContext &Context;
442 Module *TheModule = nullptr;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000443 // Next offset to start scanning for lazy parsing of function bodies.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000444 uint64_t NextUnreadBit = 0;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000445 // Last function offset found in the VST.
446 uint64_t LastFunctionBlockBit = 0;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000447 bool SeenValueSymbolTable = false;
Peter Collingbourne128a9762015-10-27 23:01:25 +0000448 uint64_t VSTOffset = 0;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000449
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000450 std::vector<std::string> SectionTable;
451 std::vector<std::string> GCTable;
452
Benjamin Kramercced8be2015-03-17 20:40:24 +0000453 std::vector<Type*> TypeList;
454 BitcodeReaderValueList ValueList;
Mehdi Aminief27db82016-12-12 19:34:26 +0000455 Optional<MetadataLoader> MDLoader;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000456 std::vector<Comdat *> ComdatList;
457 SmallVector<Instruction *, 64> InstructionList;
458
Eugene Zelenko975293f2017-09-07 23:28:24 +0000459 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
460 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>> IndirectSymbolInits;
461 std::vector<std::pair<Function *, unsigned>> FunctionPrefixes;
462 std::vector<std::pair<Function *, unsigned>> FunctionPrologues;
463 std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFns;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000464
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000465 /// The set of attributes by index. Index zero in the file is for null, and
466 /// is thus not represented here. As such all indices are off by one.
Reid Klecknerb5180542017-03-21 16:57:19 +0000467 std::vector<AttributeList> MAttributes;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000468
Karl Schimpf36440082015-08-31 16:43:55 +0000469 /// The set of attribute groups.
Reid Klecknerb5180542017-03-21 16:57:19 +0000470 std::map<unsigned, AttributeList> MAttributeGroups;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000471
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000472 /// While parsing a function body, this is a list of the basic blocks for the
473 /// function.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000474 std::vector<BasicBlock*> FunctionBBs;
475
476 // When reading the module header, this list is populated with functions that
477 // have bodies later in the file.
478 std::vector<Function*> FunctionsWithBodies;
479
480 // When intrinsic functions are encountered which require upgrading they are
481 // stored here with their replacement function.
Eugene Zelenko975293f2017-09-07 23:28:24 +0000482 using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +0000483 UpdatedIntrinsicMap UpgradedIntrinsics;
484 // Intrinsics which were remangled because of types rename
485 UpdatedIntrinsicMap RemangledIntrinsics;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000486
Benjamin Kramercced8be2015-03-17 20:40:24 +0000487 // Several operations happen after the module header has been read, but
488 // before function bodies are processed. This keeps track of whether
489 // we've done this yet.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000490 bool SeenFirstFunctionBody = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000491
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000492 /// When function bodies are initially scanned, this map contains info about
493 /// where to find deferred function body in the stream.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000494 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
495
496 /// When Metadata block is initially scanned when parsing the module, we may
497 /// choose to defer parsing of the metadata. This vector contains info about
498 /// which Metadata blocks are deferred.
499 std::vector<uint64_t> DeferredMetadataInfo;
500
501 /// These are basic blocks forward-referenced by block addresses. They are
502 /// inserted lazily into functions when they're loaded. The basic block ID is
503 /// its index into the vector.
504 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
505 std::deque<Function *> BasicBlockFwdRefQueue;
506
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000507 /// Indicates that we are using a new encoding for instruction operands where
508 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
509 /// instruction number, for a more compact encoding. Some instruction
510 /// operands are not relative to the instruction ID: basic block numbers, and
511 /// types. Once the old style function blocks have been phased out, we would
Benjamin Kramercced8be2015-03-17 20:40:24 +0000512 /// not need this flag.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000513 bool UseRelativeIDs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000514
515 /// True if all functions will be materialized, negating the need to process
516 /// (e.g.) blockaddress forward references.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000517 bool WillMaterializeAllForwardRefs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000518
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000519 bool StripDebugInfo = false;
Mehdi Amini86623052016-12-16 19:16:29 +0000520 TBAAVerifier TBAAVerifyHelper;
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000521
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000522 std::vector<std::string> BundleTags;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000523 SmallVector<SyncScope::ID, 8> SSIDs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000524
Benjamin Kramercced8be2015-03-17 20:40:24 +0000525public:
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000526 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
527 StringRef ProducerIdentification, LLVMContext &Context);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000528
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000529 Error materializeForwardReferencedFunctions();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000530
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000531 Error materialize(GlobalValue *GV) override;
532 Error materializeModule() override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000533 std::vector<StructType *> getIdentifiedStructTypes() const override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000534
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000535 /// Main interface to parsing a bitcode buffer.
Rafael Espindola6ace6852015-06-15 21:02:49 +0000536 /// \returns true if an error occurred.
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000537 Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false,
538 bool IsImporting = false);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000539
Benjamin Kramercced8be2015-03-17 20:40:24 +0000540 static uint64_t decodeSignRotatedValue(uint64_t V);
541
542 /// Materialize any deferred Metadata block.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000543 Error materializeMetadata() override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000544
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000545 void setStripDebugInfo() override;
546
Benjamin Kramercced8be2015-03-17 20:40:24 +0000547private:
548 std::vector<StructType *> IdentifiedStructTypes;
549 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
550 StructType *createIdentifiedStructType(LLVMContext &Context);
551
552 Type *getTypeByID(unsigned ID);
Eugene Zelenko1804a772016-08-25 00:45:04 +0000553
David Majnemer8a1c45d2015-12-12 05:38:55 +0000554 Value *getFnValueByID(unsigned ID, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000555 if (Ty && Ty->isMetadataTy())
556 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
David Majnemer8a1c45d2015-12-12 05:38:55 +0000557 return ValueList.getValueFwdRef(ID, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000558 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000559
Benjamin Kramercced8be2015-03-17 20:40:24 +0000560 Metadata *getFnMetadataByID(unsigned ID) {
Mehdi Amini3bb4d012017-01-20 20:29:16 +0000561 return MDLoader->getMetadataFwdRefOrLoad(ID);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000562 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000563
Benjamin Kramercced8be2015-03-17 20:40:24 +0000564 BasicBlock *getBasicBlock(unsigned ID) const {
565 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
566 return FunctionBBs[ID];
567 }
Eugene Zelenko1804a772016-08-25 00:45:04 +0000568
Reid Klecknerb5180542017-03-21 16:57:19 +0000569 AttributeList getAttributes(unsigned i) const {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000570 if (i-1 < MAttributes.size())
571 return MAttributes[i-1];
Reid Klecknerb5180542017-03-21 16:57:19 +0000572 return AttributeList();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000573 }
574
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000575 /// Read a value/type pair out of the specified record from slot 'Slot'.
576 /// Increment Slot past the number of slots used in the record. Return true on
577 /// failure.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000578 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
579 unsigned InstNum, Value *&ResVal) {
580 if (Slot == Record.size()) return true;
581 unsigned ValNo = (unsigned)Record[Slot++];
582 // Adjust the ValNo, if it was encoded relative to the InstNum.
583 if (UseRelativeIDs)
584 ValNo = InstNum - ValNo;
585 if (ValNo < InstNum) {
586 // If this is not a forward reference, just return the value we already
587 // have.
588 ResVal = getFnValueByID(ValNo, nullptr);
589 return ResVal == nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000590 }
David Blaikiedbe6e0f2015-04-17 06:40:14 +0000591 if (Slot == Record.size())
592 return true;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000593
594 unsigned TypeNo = (unsigned)Record[Slot++];
595 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
596 return ResVal == nullptr;
597 }
598
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000599 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
600 /// past the number of slots used by the value in the record. Return true if
601 /// there is an error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000602 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000603 unsigned InstNum, Type *Ty, Value *&ResVal) {
604 if (getValue(Record, Slot, InstNum, Ty, ResVal))
Benjamin Kramercced8be2015-03-17 20:40:24 +0000605 return true;
606 // All values currently take a single record slot.
607 ++Slot;
608 return false;
609 }
610
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000611 /// Like popValue, but does not increment the Slot number.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000612 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000613 unsigned InstNum, Type *Ty, Value *&ResVal) {
614 ResVal = getValue(Record, Slot, InstNum, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000615 return ResVal == nullptr;
616 }
617
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000618 /// Version of getValue that returns ResVal directly, or 0 if there is an
619 /// error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000620 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000621 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000622 if (Slot == Record.size()) return nullptr;
623 unsigned ValNo = (unsigned)Record[Slot];
624 // Adjust the ValNo, if it was encoded relative to the InstNum.
625 if (UseRelativeIDs)
626 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000627 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000628 }
629
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000630 /// Like getValue, but decodes signed VBRs.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000631 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000632 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000633 if (Slot == Record.size()) return nullptr;
634 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
635 // Adjust the ValNo, if it was encoded relative to the InstNum.
636 if (UseRelativeIDs)
637 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000638 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000639 }
640
641 /// Converts alignment exponent (i.e. power of two (or zero)) to the
642 /// corresponding alignment to use. If alignment is too large, returns
643 /// a corresponding error code.
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000644 Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
645 Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
646 Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false);
Peter Collingbournece24a2a2017-04-12 20:02:09 +0000647
648 Error parseComdatRecord(ArrayRef<uint64_t> Record);
649 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
650 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
651 Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
652 ArrayRef<uint64_t> Record);
653
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000654 Error parseAttributeBlock();
655 Error parseAttributeGroupBlock();
656 Error parseTypeTable();
657 Error parseTypeTableBody();
658 Error parseOperandBundleTags();
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000659 Error parseSyncScopeNames();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000660
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000661 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
662 unsigned NameIndex, Triple &TT);
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000663 void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
664 ArrayRef<uint64_t> Record);
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000665 Error parseValueSymbolTable(uint64_t Offset = 0);
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000666 Error parseGlobalValueSymbolTable();
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000667 Error parseConstants();
668 Error rememberAndSkipFunctionBodies();
669 Error rememberAndSkipFunctionBody();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000670 /// Save the positions of the Metadata blocks and skip parsing the blocks.
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000671 Error rememberAndSkipMetadata();
672 Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
673 Error parseFunctionBody(Function *F);
674 Error globalCleanup();
675 Error resolveGlobalAndIndirectSymbolInits();
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000676 Error parseUseLists();
677 Error findFunctionInStream(
Benjamin Kramercced8be2015-03-17 20:40:24 +0000678 Function *F,
679 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000680
681 SyncScope::ID getDecodedSyncScopeID(unsigned Val);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000682};
Teresa Johnson403a7872015-10-04 14:33:43 +0000683
684/// Class to manage reading and parsing function summary index bitcode
685/// files/sections.
Peter Collingbourne6e860752016-09-23 18:27:42 +0000686class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +0000687 /// The module index built during parsing.
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +0000688 ModuleSummaryIndex &TheIndex;
Teresa Johnson403a7872015-10-04 14:33:43 +0000689
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000690 /// Indicates whether we have encountered a global value summary section
Peter Collingbournea46ec9f2016-12-01 06:00:53 +0000691 /// yet during parsing.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000692 bool SeenGlobalValSummary = false;
Teresa Johnson403a7872015-10-04 14:33:43 +0000693
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000694 /// Indicates whether we have already parsed the VST, used for error checking.
695 bool SeenValueSymbolTable = false;
696
697 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
698 /// Used to enable on-demand parsing of the VST.
699 uint64_t VSTOffset = 0;
700
Peter Collingbourne9667b912017-05-04 18:03:25 +0000701 // Map to save ValueId to ValueInfo association that was recorded in the
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000702 // ValueSymbolTable. It is used after the VST is parsed to convert
703 // call graph edges read from the function summary from referencing
Peter Collingbourne9667b912017-05-04 18:03:25 +0000704 // callees by their ValueId to using the ValueInfo instead, which is how
Teresa Johnson26ab5772016-03-15 00:04:37 +0000705 // they are recorded in the summary index being built.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000706 // We save a GUID which refers to the same global as the ValueInfo, but
707 // ignoring the linkage, i.e. for values other than local linkage they are
708 // identical.
709 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
710 ValueIdToValueInfoMap;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000711
Teresa Johnson403a7872015-10-04 14:33:43 +0000712 /// Map populated during module path string table parsing, from the
713 /// module ID to a string reference owned by the index's module
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000714 /// path string table, used to correlate with combined index
Teresa Johnson403a7872015-10-04 14:33:43 +0000715 /// summary records.
716 DenseMap<uint64_t, StringRef> ModuleIdMap;
717
Teresa Johnsone1164de2016-02-10 21:55:02 +0000718 /// Original source file name recorded in a bitcode record.
719 std::string SourceFileName;
720
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000721 /// The string identifier given to this module by the client, normally the
722 /// path to the bitcode file.
723 StringRef ModulePath;
724
725 /// For per-module summary indexes, the unique numerical identifier given to
726 /// this module by the client.
727 unsigned ModuleId;
728
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000729public:
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000730 ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab,
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000731 ModuleSummaryIndex &TheIndex,
732 StringRef ModulePath, unsigned ModuleId);
Teresa Johnson403a7872015-10-04 14:33:43 +0000733
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000734 Error parseModule();
Teresa Johnson403a7872015-10-04 14:33:43 +0000735
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000736private:
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000737 void setValueGUID(uint64_t ValueID, StringRef ValueName,
738 GlobalValue::LinkageTypes Linkage,
739 StringRef SourceFileName);
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000740 Error parseValueSymbolTable(
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000741 uint64_t Offset,
742 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000743 std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
744 std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
745 bool IsOldProfileFormat,
Easwaran Ramanc73cec82018-01-25 19:27:17 +0000746 bool HasProfile,
747 bool HasRelBF);
Peter Collingbournedbd2fed2017-06-15 17:26:13 +0000748 Error parseEntireSummary(unsigned ID);
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000749 Error parseModuleStringTable();
Eugene Zelenko1804a772016-08-25 00:45:04 +0000750
Peter Collingbourne9667b912017-05-04 18:03:25 +0000751 std::pair<ValueInfo, GlobalValue::GUID>
752 getValueInfoFromValueId(unsigned ValueId);
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000753
Teresa Johnson9766fd62018-06-26 01:32:58 +0000754 void addThisModule();
755 ModuleSummaryIndex::ModuleInfo *getThisModule();
Teresa Johnson403a7872015-10-04 14:33:43 +0000756};
Eugene Zelenko1804a772016-08-25 00:45:04 +0000757
Peter Collingbournecd513a42016-11-11 19:50:24 +0000758} // end anonymous namespace
759
760std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
761 Error Err) {
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000762 if (Err) {
763 std::error_code EC;
764 handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
765 EC = EIB.convertToErrorCode();
766 Ctx.emitError(EIB.message());
767 });
768 return EC;
769 }
770 return std::error_code();
771}
772
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000773BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
Peter Collingbourne7a748032016-11-16 21:44:45 +0000774 StringRef ProducerIdentification,
775 LLVMContext &Context)
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000776 : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
Mehdi Aminief27db82016-12-12 19:34:26 +0000777 ValueList(Context) {
Peter Collingbourne7a748032016-11-16 21:44:45 +0000778 this->ProducerIdentification = ProducerIdentification;
779}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000780
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000781Error BitcodeReader::materializeForwardReferencedFunctions() {
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000782 if (WillMaterializeAllForwardRefs)
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000783 return Error::success();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000784
785 // Prevent recursion.
786 WillMaterializeAllForwardRefs = true;
787
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000788 while (!BasicBlockFwdRefQueue.empty()) {
789 Function *F = BasicBlockFwdRefQueue.front();
790 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000791 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000792 if (!BasicBlockFwdRefs.count(F))
793 // Already materialized.
794 continue;
795
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000796 // Check for a function that isn't materializable to prevent an infinite
797 // loop. When parsing a blockaddress stored in a global variable, there
798 // isn't a trivial way to check if a function will have a body without a
799 // linear search through FunctionsWithBodies, so just check it here.
800 if (!F->isMaterializable())
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000801 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000802
803 // Try to materialize F.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000804 if (Error Err = materialize(F))
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000805 return Err;
Rafael Espindolab7993462012-01-02 07:49:53 +0000806 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000807 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000808
809 // Reset state.
810 WillMaterializeAllForwardRefs = false;
Peter Collingbourne58f7f072016-11-09 00:51:04 +0000811 return Error::success();
Rafael Espindolab7993462012-01-02 07:49:53 +0000812}
813
Chris Lattnerfee5a372007-05-04 03:30:17 +0000814//===----------------------------------------------------------------------===//
815// Helper functions to implement forward reference resolution, etc.
816//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +0000817
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000818static bool hasImplicitComdat(size_t Val) {
819 switch (Val) {
820 default:
821 return false;
822 case 1: // Old WeakAnyLinkage
823 case 4: // Old LinkOnceAnyLinkage
824 case 10: // Old WeakODRLinkage
825 case 11: // Old LinkOnceODRLinkage
826 return true;
827 }
828}
829
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000830static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000831 switch (Val) {
832 default: // Map unknown/new linkages to external
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000833 case 0:
834 return GlobalValue::ExternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000835 case 2:
836 return GlobalValue::AppendingLinkage;
837 case 3:
838 return GlobalValue::InternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000839 case 5:
840 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
841 case 6:
842 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
843 case 7:
844 return GlobalValue::ExternalWeakLinkage;
845 case 8:
846 return GlobalValue::CommonLinkage;
847 case 9:
848 return GlobalValue::PrivateLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000849 case 12:
850 return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000851 case 13:
852 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
853 case 14:
854 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Rafael Espindolabec6af62015-01-08 15:39:50 +0000855 case 15:
856 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000857 case 1: // Old value with implicit comdat.
858 case 16:
859 return GlobalValue::WeakAnyLinkage;
860 case 10: // Old value with implicit comdat.
861 case 17:
862 return GlobalValue::WeakODRLinkage;
863 case 4: // Old value with implicit comdat.
864 case 18:
865 return GlobalValue::LinkOnceAnyLinkage;
866 case 11: // Old value with implicit comdat.
867 case 19:
868 return GlobalValue::LinkOnceODRLinkage;
Chris Lattner1314b992007-04-22 06:23:29 +0000869 }
870}
871
Charles Saternos75da10d2017-08-04 16:00:58 +0000872static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
873 FunctionSummary::FFlags Flags;
874 Flags.ReadNone = RawFlags & 0x1;
875 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
876 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
877 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
Teresa Johnsoncb397462018-11-06 19:41:35 +0000878 Flags.NoInline = (RawFlags >> 4) & 0x1;
Charles Saternos75da10d2017-08-04 16:00:58 +0000879 return Flags;
880}
881
Piotr Padlewski332b3b22016-08-11 22:13:57 +0000882/// Decode the flags for GlobalValue in the summary.
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000883static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
884 uint64_t Version) {
885 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
886 // like getDecodedLinkage() above. Any future change to the linkage enum and
887 // to getDecodedLinkage() will need to be taken into account here as above.
888 auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
Mehdi Amini1380edf2017-02-03 07:41:43 +0000889 RawFlags = RawFlags >> 4;
890 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000891 // The Live flag wasn't introduced until version 3. For dead stripping
Teresa Johnson6c475a72017-01-05 21:34:18 +0000892 // to work correctly on earlier versions, we must conservatively treat all
893 // values as live.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000894 bool Live = (RawFlags & 0x2) || Version < 3;
Sean Fertile4595a912017-11-04 17:04:39 +0000895 bool Local = (RawFlags & 0x4);
896
897 return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, Live, Local);
Mehdi Aminic3ed48c2016-04-24 03:18:18 +0000898}
899
Eugene Leviantbf46e742018-11-16 07:08:00 +0000900// Decode the flags for GlobalVariable in the summary
901static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) {
902 return GlobalVarSummary::GVarFlags((RawFlags & 0x1) ? true : false);
903}
904
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000905static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000906 switch (Val) {
907 default: // Map unknown visibilities to default.
908 case 0: return GlobalValue::DefaultVisibility;
909 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000910 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000911 }
912}
913
Nico Rieck7157bb72014-01-14 15:22:47 +0000914static GlobalValue::DLLStorageClassTypes
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000915getDecodedDLLStorageClass(unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000916 switch (Val) {
917 default: // Map unknown values to default.
918 case 0: return GlobalValue::DefaultStorageClass;
919 case 1: return GlobalValue::DLLImportStorageClass;
920 case 2: return GlobalValue::DLLExportStorageClass;
921 }
922}
923
Sean Fertilec70d28b2017-10-26 15:00:26 +0000924static bool getDecodedDSOLocal(unsigned Val) {
925 switch(Val) {
926 default: // Map unknown values to preemptable.
927 case 0: return false;
928 case 1: return true;
929 }
930}
931
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000932static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000933 switch (Val) {
934 case 0: return GlobalVariable::NotThreadLocal;
935 default: // Map unknown non-zero value to general dynamic.
936 case 1: return GlobalVariable::GeneralDynamicTLSModel;
937 case 2: return GlobalVariable::LocalDynamicTLSModel;
938 case 3: return GlobalVariable::InitialExecTLSModel;
939 case 4: return GlobalVariable::LocalExecTLSModel;
940 }
941}
942
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000943static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
944 switch (Val) {
945 default: // Map unknown to UnnamedAddr::None.
946 case 0: return GlobalVariable::UnnamedAddr::None;
947 case 1: return GlobalVariable::UnnamedAddr::Global;
948 case 2: return GlobalVariable::UnnamedAddr::Local;
949 }
950}
951
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000952static int getDecodedCastOpcode(unsigned Val) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000953 switch (Val) {
954 default: return -1;
955 case bitc::CAST_TRUNC : return Instruction::Trunc;
956 case bitc::CAST_ZEXT : return Instruction::ZExt;
957 case bitc::CAST_SEXT : return Instruction::SExt;
958 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
959 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
960 case bitc::CAST_UITOFP : return Instruction::UIToFP;
961 case bitc::CAST_SITOFP : return Instruction::SIToFP;
962 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
963 case bitc::CAST_FPEXT : return Instruction::FPExt;
964 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
965 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
966 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000967 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000968 }
969}
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000970
Cameron McInallycbde0d92018-11-13 18:15:47 +0000971static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) {
972 bool IsFP = Ty->isFPOrFPVectorTy();
973 // UnOps are only valid for int/fp or vector of int/fp types
974 if (!IsFP && !Ty->isIntOrIntVectorTy())
975 return -1;
976
977 switch (Val) {
978 default:
979 return -1;
980 case bitc::UNOP_NEG:
981 return IsFP ? Instruction::FNeg : -1;
982 }
983}
984
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000985static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000986 bool IsFP = Ty->isFPOrFPVectorTy();
987 // BinOps are only valid for int/fp or vector of int/fp types
988 if (!IsFP && !Ty->isIntOrIntVectorTy())
989 return -1;
990
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000991 switch (Val) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000992 default:
993 return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000994 case bitc::BINOP_ADD:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000995 return IsFP ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000996 case bitc::BINOP_SUB:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000997 return IsFP ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000998 case bitc::BINOP_MUL:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000999 return IsFP ? Instruction::FMul : Instruction::Mul;
1000 case bitc::BINOP_UDIV:
1001 return IsFP ? -1 : Instruction::UDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001002 case bitc::BINOP_SDIV:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +00001003 return IsFP ? Instruction::FDiv : Instruction::SDiv;
1004 case bitc::BINOP_UREM:
1005 return IsFP ? -1 : Instruction::URem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001006 case bitc::BINOP_SREM:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +00001007 return IsFP ? Instruction::FRem : Instruction::SRem;
1008 case bitc::BINOP_SHL:
1009 return IsFP ? -1 : Instruction::Shl;
1010 case bitc::BINOP_LSHR:
1011 return IsFP ? -1 : Instruction::LShr;
1012 case bitc::BINOP_ASHR:
1013 return IsFP ? -1 : Instruction::AShr;
1014 case bitc::BINOP_AND:
1015 return IsFP ? -1 : Instruction::And;
1016 case bitc::BINOP_OR:
1017 return IsFP ? -1 : Instruction::Or;
1018 case bitc::BINOP_XOR:
1019 return IsFP ? -1 : Instruction::Xor;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00001020 }
1021}
1022
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001023static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +00001024 switch (Val) {
1025 default: return AtomicRMWInst::BAD_BINOP;
1026 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
1027 case bitc::RMW_ADD: return AtomicRMWInst::Add;
1028 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
1029 case bitc::RMW_AND: return AtomicRMWInst::And;
1030 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
1031 case bitc::RMW_OR: return AtomicRMWInst::Or;
1032 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
1033 case bitc::RMW_MAX: return AtomicRMWInst::Max;
1034 case bitc::RMW_MIN: return AtomicRMWInst::Min;
1035 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
1036 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
1037 }
1038}
1039
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001040static AtomicOrdering getDecodedOrdering(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +00001041 switch (Val) {
JF Bastien800f87a2016-04-06 21:19:33 +00001042 case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
1043 case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
1044 case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
1045 case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
1046 case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
1047 case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001048 default: // Map unknown orderings to sequentially-consistent.
JF Bastien800f87a2016-04-06 21:19:33 +00001049 case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
Eli Friedmanfee02c62011-07-25 23:16:38 +00001050 }
1051}
1052
David Majnemerdad0a642014-06-27 18:19:56 +00001053static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
1054 switch (Val) {
1055 default: // Map unknown selection kinds to any.
1056 case bitc::COMDAT_SELECTION_KIND_ANY:
1057 return Comdat::Any;
1058 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
1059 return Comdat::ExactMatch;
1060 case bitc::COMDAT_SELECTION_KIND_LARGEST:
1061 return Comdat::Largest;
1062 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
1063 return Comdat::NoDuplicates;
1064 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
1065 return Comdat::SameSize;
1066 }
1067}
1068
James Molloy88eb5352015-07-10 12:52:00 +00001069static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
1070 FastMathFlags FMF;
Steven Wu545d34a2018-02-19 19:22:28 +00001071 if (0 != (Val & bitc::UnsafeAlgebra))
1072 FMF.setFast();
1073 if (0 != (Val & bitc::AllowReassoc))
Sanjay Patel629c4112017-11-06 16:27:15 +00001074 FMF.setAllowReassoc();
Steven Wu545d34a2018-02-19 19:22:28 +00001075 if (0 != (Val & bitc::NoNaNs))
James Molloy88eb5352015-07-10 12:52:00 +00001076 FMF.setNoNaNs();
Steven Wu545d34a2018-02-19 19:22:28 +00001077 if (0 != (Val & bitc::NoInfs))
James Molloy88eb5352015-07-10 12:52:00 +00001078 FMF.setNoInfs();
Steven Wu545d34a2018-02-19 19:22:28 +00001079 if (0 != (Val & bitc::NoSignedZeros))
James Molloy88eb5352015-07-10 12:52:00 +00001080 FMF.setNoSignedZeros();
Steven Wu545d34a2018-02-19 19:22:28 +00001081 if (0 != (Val & bitc::AllowReciprocal))
James Molloy88eb5352015-07-10 12:52:00 +00001082 FMF.setAllowReciprocal();
Steven Wu545d34a2018-02-19 19:22:28 +00001083 if (0 != (Val & bitc::AllowContract))
Adam Nemetcd847a82017-03-28 20:11:52 +00001084 FMF.setAllowContract(true);
Steven Wu545d34a2018-02-19 19:22:28 +00001085 if (0 != (Val & bitc::ApproxFunc))
Sanjay Patel629c4112017-11-06 16:27:15 +00001086 FMF.setApproxFunc();
James Molloy88eb5352015-07-10 12:52:00 +00001087 return FMF;
1088}
1089
Eugene Zelenko1804a772016-08-25 00:45:04 +00001090static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +00001091 switch (Val) {
1092 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
1093 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
1094 }
1095}
1096
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001097Type *BitcodeReader::getTypeByID(unsigned ID) {
1098 // The type table size is always specified correctly.
1099 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +00001100 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +00001101
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001102 if (Type *Ty = TypeList[ID])
1103 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001104
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001105 // If we have a forward reference, the only possible case is when it is to a
1106 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001107 return TypeList[ID] = createIdentifiedStructType(Context);
1108}
1109
1110StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1111 StringRef Name) {
1112 auto *Ret = StructType::create(Context, Name);
1113 IdentifiedStructTypes.push_back(Ret);
1114 return Ret;
1115}
1116
1117StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1118 auto *Ret = StructType::create(Context);
1119 IdentifiedStructTypes.push_back(Ret);
1120 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +00001121}
1122
Chris Lattnerfee5a372007-05-04 03:30:17 +00001123//===----------------------------------------------------------------------===//
1124// Functions for parsing blocks from the bitcode file
1125//===----------------------------------------------------------------------===//
1126
Amaury Sechet74084c42016-11-06 07:48:46 +00001127static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1128 switch (Val) {
1129 case Attribute::EndAttrKinds:
1130 llvm_unreachable("Synthetic enumerators which should never get here");
1131
1132 case Attribute::None: return 0;
1133 case Attribute::ZExt: return 1 << 0;
1134 case Attribute::SExt: return 1 << 1;
1135 case Attribute::NoReturn: return 1 << 2;
1136 case Attribute::InReg: return 1 << 3;
1137 case Attribute::StructRet: return 1 << 4;
1138 case Attribute::NoUnwind: return 1 << 5;
1139 case Attribute::NoAlias: return 1 << 6;
1140 case Attribute::ByVal: return 1 << 7;
1141 case Attribute::Nest: return 1 << 8;
1142 case Attribute::ReadNone: return 1 << 9;
1143 case Attribute::ReadOnly: return 1 << 10;
1144 case Attribute::NoInline: return 1 << 11;
1145 case Attribute::AlwaysInline: return 1 << 12;
1146 case Attribute::OptimizeForSize: return 1 << 13;
1147 case Attribute::StackProtect: return 1 << 14;
1148 case Attribute::StackProtectReq: return 1 << 15;
1149 case Attribute::Alignment: return 31 << 16;
1150 case Attribute::NoCapture: return 1 << 21;
1151 case Attribute::NoRedZone: return 1 << 22;
1152 case Attribute::NoImplicitFloat: return 1 << 23;
1153 case Attribute::Naked: return 1 << 24;
1154 case Attribute::InlineHint: return 1 << 25;
1155 case Attribute::StackAlignment: return 7 << 26;
1156 case Attribute::ReturnsTwice: return 1 << 29;
1157 case Attribute::UWTable: return 1 << 30;
1158 case Attribute::NonLazyBind: return 1U << 31;
1159 case Attribute::SanitizeAddress: return 1ULL << 32;
1160 case Attribute::MinSize: return 1ULL << 33;
1161 case Attribute::NoDuplicate: return 1ULL << 34;
1162 case Attribute::StackProtectStrong: return 1ULL << 35;
1163 case Attribute::SanitizeThread: return 1ULL << 36;
1164 case Attribute::SanitizeMemory: return 1ULL << 37;
1165 case Attribute::NoBuiltin: return 1ULL << 38;
1166 case Attribute::Returned: return 1ULL << 39;
1167 case Attribute::Cold: return 1ULL << 40;
1168 case Attribute::Builtin: return 1ULL << 41;
1169 case Attribute::OptimizeNone: return 1ULL << 42;
1170 case Attribute::InAlloca: return 1ULL << 43;
1171 case Attribute::NonNull: return 1ULL << 44;
1172 case Attribute::JumpTable: return 1ULL << 45;
1173 case Attribute::Convergent: return 1ULL << 46;
1174 case Attribute::SafeStack: return 1ULL << 47;
1175 case Attribute::NoRecurse: return 1ULL << 48;
1176 case Attribute::InaccessibleMemOnly: return 1ULL << 49;
1177 case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1178 case Attribute::SwiftSelf: return 1ULL << 51;
1179 case Attribute::SwiftError: return 1ULL << 52;
1180 case Attribute::WriteOnly: return 1ULL << 53;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001181 case Attribute::Speculatable: return 1ULL << 54;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001182 case Attribute::StrictFP: return 1ULL << 55;
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001183 case Attribute::SanitizeHWAddress: return 1ULL << 56;
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001184 case Attribute::NoCfCheck: return 1ULL << 57;
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001185 case Attribute::OptForFuzzing: return 1ULL << 58;
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001186 case Attribute::ShadowCallStack: return 1ULL << 59;
Chandler Carruth664aa862018-09-04 12:38:00 +00001187 case Attribute::SpeculativeLoadHardening:
1188 return 1ULL << 60;
Amaury Sechet74084c42016-11-06 07:48:46 +00001189 case Attribute::Dereferenceable:
1190 llvm_unreachable("dereferenceable attribute not supported in raw format");
1191 break;
1192 case Attribute::DereferenceableOrNull:
1193 llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
1194 "format");
1195 break;
1196 case Attribute::ArgMemOnly:
1197 llvm_unreachable("argmemonly attribute not supported in raw format");
1198 break;
1199 case Attribute::AllocSize:
1200 llvm_unreachable("allocsize not supported in raw format");
1201 break;
1202 }
1203 llvm_unreachable("Unsupported attribute type");
1204}
1205
1206static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1207 if (!Val) return;
1208
1209 for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1210 I = Attribute::AttrKind(I + 1)) {
1211 if (I == Attribute::Dereferenceable ||
1212 I == Attribute::DereferenceableOrNull ||
1213 I == Attribute::ArgMemOnly ||
1214 I == Attribute::AllocSize)
1215 continue;
1216 if (uint64_t A = (Val & getRawAttributeMask(I))) {
1217 if (I == Attribute::Alignment)
1218 B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1219 else if (I == Attribute::StackAlignment)
1220 B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1221 else
1222 B.addAttribute(I);
1223 }
1224 }
1225}
1226
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001227/// This fills an AttrBuilder object with the LLVM attributes that have
Bill Wendling56aeccc2013-02-04 23:32:23 +00001228/// been decoded from the given integer. This function must stay in sync with
1229/// 'encodeLLVMAttributesForBitcode'.
1230static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1231 uint64_t EncodedAttrs) {
1232 // FIXME: Remove in 4.0.
1233
1234 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1235 // the bits above 31 down by 11 bits.
1236 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1237 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1238 "Alignment must be a power of two.");
1239
1240 if (Alignment)
1241 B.addAlignmentAttr(Alignment);
Amaury Sechet74084c42016-11-06 07:48:46 +00001242 addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1243 (EncodedAttrs & 0xffff));
Bill Wendling56aeccc2013-02-04 23:32:23 +00001244}
1245
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001246Error BitcodeReader::parseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001247 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001248 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001249
Devang Patela05633e2008-09-26 22:53:05 +00001250 if (!MAttributes.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001251 return error("Invalid multiple blocks");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001252
Chris Lattnerfee5a372007-05-04 03:30:17 +00001253 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001254
Reid Klecknerb5180542017-03-21 16:57:19 +00001255 SmallVector<AttributeList, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001256
Chris Lattnerfee5a372007-05-04 03:30:17 +00001257 // Read all the records.
Eugene Zelenko1804a772016-08-25 00:45:04 +00001258 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00001259 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001260
Chris Lattner27d38752013-01-20 02:13:19 +00001261 switch (Entry.Kind) {
1262 case BitstreamEntry::SubBlock: // Handled for us already.
1263 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001264 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001265 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001266 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00001267 case BitstreamEntry::Record:
1268 // The interesting case.
1269 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001270 }
Joe Abbey97b7a172013-02-06 22:14:06 +00001271
Chris Lattnerfee5a372007-05-04 03:30:17 +00001272 // Read a record.
1273 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001274 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +00001275 default: // Default behavior: ignore.
1276 break;
Eugene Zelenko975293f2017-09-07 23:28:24 +00001277 case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
Bill Wendling56aeccc2013-02-04 23:32:23 +00001278 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +00001279 if (Record.size() & 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001280 return error("Invalid record");
Chris Lattnerfee5a372007-05-04 03:30:17 +00001281
Chris Lattnerfee5a372007-05-04 03:30:17 +00001282 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +00001283 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001284 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Reid Klecknerb5180542017-03-21 16:57:19 +00001285 Attrs.push_back(AttributeList::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +00001286 }
Devang Patela05633e2008-09-26 22:53:05 +00001287
Reid Klecknerb5180542017-03-21 16:57:19 +00001288 MAttributes.push_back(AttributeList::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +00001289 Attrs.clear();
1290 break;
Eugene Zelenko975293f2017-09-07 23:28:24 +00001291 case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
Bill Wendling0dc08912013-02-12 08:13:50 +00001292 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1293 Attrs.push_back(MAttributeGroups[Record[i]]);
1294
Reid Klecknerb5180542017-03-21 16:57:19 +00001295 MAttributes.push_back(AttributeList::get(Context, Attrs));
Bill Wendling0dc08912013-02-12 08:13:50 +00001296 Attrs.clear();
1297 break;
1298 }
Chris Lattnerfee5a372007-05-04 03:30:17 +00001299 }
1300}
1301
Reid Klecknere9f36af2013-11-12 01:31:00 +00001302// Returns Attribute::None on unrecognized codes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001303static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
Reid Klecknere9f36af2013-11-12 01:31:00 +00001304 switch (Code) {
1305 default:
1306 return Attribute::None;
1307 case bitc::ATTR_KIND_ALIGNMENT:
1308 return Attribute::Alignment;
1309 case bitc::ATTR_KIND_ALWAYS_INLINE:
1310 return Attribute::AlwaysInline;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001311 case bitc::ATTR_KIND_ARGMEMONLY:
1312 return Attribute::ArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001313 case bitc::ATTR_KIND_BUILTIN:
1314 return Attribute::Builtin;
1315 case bitc::ATTR_KIND_BY_VAL:
1316 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +00001317 case bitc::ATTR_KIND_IN_ALLOCA:
1318 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001319 case bitc::ATTR_KIND_COLD:
1320 return Attribute::Cold;
Owen Anderson85fa7d52015-05-26 23:48:40 +00001321 case bitc::ATTR_KIND_CONVERGENT:
1322 return Attribute::Convergent;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001323 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1324 return Attribute::InaccessibleMemOnly;
1325 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1326 return Attribute::InaccessibleMemOrArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001327 case bitc::ATTR_KIND_INLINE_HINT:
1328 return Attribute::InlineHint;
1329 case bitc::ATTR_KIND_IN_REG:
1330 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +00001331 case bitc::ATTR_KIND_JUMP_TABLE:
1332 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001333 case bitc::ATTR_KIND_MIN_SIZE:
1334 return Attribute::MinSize;
1335 case bitc::ATTR_KIND_NAKED:
1336 return Attribute::Naked;
1337 case bitc::ATTR_KIND_NEST:
1338 return Attribute::Nest;
1339 case bitc::ATTR_KIND_NO_ALIAS:
1340 return Attribute::NoAlias;
1341 case bitc::ATTR_KIND_NO_BUILTIN:
1342 return Attribute::NoBuiltin;
1343 case bitc::ATTR_KIND_NO_CAPTURE:
1344 return Attribute::NoCapture;
1345 case bitc::ATTR_KIND_NO_DUPLICATE:
1346 return Attribute::NoDuplicate;
1347 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1348 return Attribute::NoImplicitFloat;
1349 case bitc::ATTR_KIND_NO_INLINE:
1350 return Attribute::NoInline;
James Molloye6f87ca2015-11-06 10:32:53 +00001351 case bitc::ATTR_KIND_NO_RECURSE:
1352 return Attribute::NoRecurse;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001353 case bitc::ATTR_KIND_NON_LAZY_BIND:
1354 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001355 case bitc::ATTR_KIND_NON_NULL:
1356 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001357 case bitc::ATTR_KIND_DEREFERENCEABLE:
1358 return Attribute::Dereferenceable;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001359 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1360 return Attribute::DereferenceableOrNull;
George Burgess IV278199f2016-04-12 01:05:35 +00001361 case bitc::ATTR_KIND_ALLOC_SIZE:
1362 return Attribute::AllocSize;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001363 case bitc::ATTR_KIND_NO_RED_ZONE:
1364 return Attribute::NoRedZone;
1365 case bitc::ATTR_KIND_NO_RETURN:
1366 return Attribute::NoReturn;
Oren Ben Simhonfdd72fd2018-03-17 13:29:46 +00001367 case bitc::ATTR_KIND_NOCF_CHECK:
1368 return Attribute::NoCfCheck;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001369 case bitc::ATTR_KIND_NO_UNWIND:
1370 return Attribute::NoUnwind;
Matt Morehouse236cdaf2018-03-22 17:07:51 +00001371 case bitc::ATTR_KIND_OPT_FOR_FUZZING:
1372 return Attribute::OptForFuzzing;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001373 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1374 return Attribute::OptimizeForSize;
1375 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1376 return Attribute::OptimizeNone;
1377 case bitc::ATTR_KIND_READ_NONE:
1378 return Attribute::ReadNone;
1379 case bitc::ATTR_KIND_READ_ONLY:
1380 return Attribute::ReadOnly;
1381 case bitc::ATTR_KIND_RETURNED:
1382 return Attribute::Returned;
1383 case bitc::ATTR_KIND_RETURNS_TWICE:
1384 return Attribute::ReturnsTwice;
1385 case bitc::ATTR_KIND_S_EXT:
1386 return Attribute::SExt;
Matt Arsenaultb19b57e2017-04-28 20:25:27 +00001387 case bitc::ATTR_KIND_SPECULATABLE:
1388 return Attribute::Speculatable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001389 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1390 return Attribute::StackAlignment;
1391 case bitc::ATTR_KIND_STACK_PROTECT:
1392 return Attribute::StackProtect;
1393 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1394 return Attribute::StackProtectReq;
1395 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1396 return Attribute::StackProtectStrong;
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001397 case bitc::ATTR_KIND_SAFESTACK:
1398 return Attribute::SafeStack;
Vlad Tsyrklevichd17f61e2018-04-03 20:10:40 +00001399 case bitc::ATTR_KIND_SHADOWCALLSTACK:
1400 return Attribute::ShadowCallStack;
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001401 case bitc::ATTR_KIND_STRICT_FP:
1402 return Attribute::StrictFP;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001403 case bitc::ATTR_KIND_STRUCT_RET:
1404 return Attribute::StructRet;
1405 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1406 return Attribute::SanitizeAddress;
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00001407 case bitc::ATTR_KIND_SANITIZE_HWADDRESS:
1408 return Attribute::SanitizeHWAddress;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001409 case bitc::ATTR_KIND_SANITIZE_THREAD:
1410 return Attribute::SanitizeThread;
1411 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1412 return Attribute::SanitizeMemory;
Chandler Carruth664aa862018-09-04 12:38:00 +00001413 case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING:
1414 return Attribute::SpeculativeLoadHardening;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001415 case bitc::ATTR_KIND_SWIFT_ERROR:
1416 return Attribute::SwiftError;
Manman Renf46262e2016-03-29 17:37:21 +00001417 case bitc::ATTR_KIND_SWIFT_SELF:
1418 return Attribute::SwiftSelf;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001419 case bitc::ATTR_KIND_UW_TABLE:
1420 return Attribute::UWTable;
Nicolai Haehnle84c9f992016-07-04 08:01:29 +00001421 case bitc::ATTR_KIND_WRITEONLY:
1422 return Attribute::WriteOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001423 case bitc::ATTR_KIND_Z_EXT:
1424 return Attribute::ZExt;
1425 }
1426}
1427
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001428Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1429 unsigned &Alignment) {
JF Bastien30bf96b2015-02-22 19:32:03 +00001430 // Note: Alignment in bitcode files is incremented by 1, so that zero
1431 // can be used for default alignment.
1432 if (Exponent > Value::MaxAlignmentExponent + 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001433 return error("Invalid alignment value");
JF Bastien30bf96b2015-02-22 19:32:03 +00001434 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001435 return Error::success();
JF Bastien30bf96b2015-02-22 19:32:03 +00001436}
1437
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001438Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001439 *Kind = getAttrFromCode(Code);
Reid Klecknere9f36af2013-11-12 01:31:00 +00001440 if (*Kind == Attribute::None)
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001441 return error("Unknown attribute kind (" + Twine(Code) + ")");
1442 return Error::success();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001443}
1444
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001445Error BitcodeReader::parseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +00001446 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001447 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001448
1449 if (!MAttributeGroups.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001450 return error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +00001451
1452 SmallVector<uint64_t, 64> Record;
1453
1454 // Read all the records.
Eugene Zelenko1804a772016-08-25 00:45:04 +00001455 while (true) {
Bill Wendlingba629332013-02-10 23:24:25 +00001456 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1457
1458 switch (Entry.Kind) {
1459 case BitstreamEntry::SubBlock: // Handled for us already.
1460 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001461 return error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +00001462 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001463 return Error::success();
Bill Wendlingba629332013-02-10 23:24:25 +00001464 case BitstreamEntry::Record:
1465 // The interesting case.
1466 break;
1467 }
1468
1469 // Read a record.
1470 Record.clear();
1471 switch (Stream.readRecord(Entry.ID, Record)) {
1472 default: // Default behavior: ignore.
1473 break;
1474 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1475 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001476 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001477
Bill Wendlinge46707e2013-02-11 22:32:29 +00001478 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +00001479 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1480
1481 AttrBuilder B;
1482 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1483 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001484 Attribute::AttrKind Kind;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001485 if (Error Err = parseAttrKind(Record[++i], &Kind))
1486 return Err;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001487
1488 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +00001489 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001490 Attribute::AttrKind Kind;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001491 if (Error Err = parseAttrKind(Record[++i], &Kind))
1492 return Err;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001493 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001494 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001495 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001496 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001497 else if (Kind == Attribute::Dereferenceable)
1498 B.addDereferenceableAttr(Record[++i]);
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001499 else if (Kind == Attribute::DereferenceableOrNull)
1500 B.addDereferenceableOrNullAttr(Record[++i]);
George Burgess IV278199f2016-04-12 01:05:35 +00001501 else if (Kind == Attribute::AllocSize)
1502 B.addAllocSizeAttrFromRawRepr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +00001503 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +00001504 assert((Record[i] == 3 || Record[i] == 4) &&
1505 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +00001506 bool HasValue = (Record[i++] == 4);
1507 SmallString<64> KindStr;
1508 SmallString<64> ValStr;
1509
1510 while (Record[i] != 0 && i != e)
1511 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001512 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001513
1514 if (HasValue) {
1515 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +00001516 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +00001517 while (Record[i] != 0 && i != e)
1518 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001519 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001520 }
1521
1522 B.addAttribute(KindStr.str(), ValStr.str());
1523 }
1524 }
1525
Reid Klecknerb5180542017-03-21 16:57:19 +00001526 MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +00001527 break;
1528 }
1529 }
1530 }
1531}
1532
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001533Error BitcodeReader::parseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001534 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001535 return error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +00001536
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001537 return parseTypeTableBody();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001538}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001539
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001540Error BitcodeReader::parseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +00001541 if (!TypeList.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001542 return error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +00001543
1544 SmallVector<uint64_t, 64> Record;
1545 unsigned NumRecords = 0;
1546
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001547 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +00001548
Chris Lattner1314b992007-04-22 06:23:29 +00001549 // Read all the records for this type table.
Eugene Zelenko1804a772016-08-25 00:45:04 +00001550 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00001551 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001552
Chris Lattner27d38752013-01-20 02:13:19 +00001553 switch (Entry.Kind) {
1554 case BitstreamEntry::SubBlock: // Handled for us already.
1555 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001556 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001557 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +00001558 if (NumRecords != TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001559 return error("Malformed block");
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001560 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00001561 case BitstreamEntry::Record:
1562 // The interesting case.
1563 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001564 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001565
Chris Lattner1314b992007-04-22 06:23:29 +00001566 // Read a record.
1567 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001568 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001569 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001570 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001571 return error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +00001572 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1573 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1574 // type list. This allows us to reserve space.
1575 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001576 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001577 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001578 continue;
Chris Lattner1314b992007-04-22 06:23:29 +00001579 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +00001580 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001581 break;
Dan Gohman518cda42011-12-17 00:04:22 +00001582 case bitc::TYPE_CODE_HALF: // HALF
1583 ResultTy = Type::getHalfTy(Context);
1584 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001585 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +00001586 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001587 break;
1588 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +00001589 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001590 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001591 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +00001592 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001593 break;
1594 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001595 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001596 break;
1597 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001598 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001599 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001600 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +00001601 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001602 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001603 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +00001604 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001605 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +00001606 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1607 ResultTy = Type::getX86_MMXTy(Context);
1608 break;
David Majnemerb611e3f2015-08-14 05:09:07 +00001609 case bitc::TYPE_CODE_TOKEN: // TOKEN
1610 ResultTy = Type::getTokenTy(Context);
1611 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001612 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
Chris Lattner1314b992007-04-22 06:23:29 +00001613 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001614 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001615
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001616 uint64_t NumBits = Record[0];
1617 if (NumBits < IntegerType::MIN_INT_BITS ||
1618 NumBits > IntegerType::MAX_INT_BITS)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001619 return error("Bitwidth for integer type out of range");
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001620 ResultTy = IntegerType::get(Context, NumBits);
Chris Lattner1314b992007-04-22 06:23:29 +00001621 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001622 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001623 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001624 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +00001625 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001626 return error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001627 unsigned AddressSpace = 0;
1628 if (Record.size() == 2)
1629 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001630 ResultTy = getTypeByID(Record[0]);
Filipe Cabecinhasd8a1bcd2015-04-29 02:27:28 +00001631 if (!ResultTy ||
1632 !PointerType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001633 return error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001634 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +00001635 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001636 }
Nuno Lopes561dae02012-05-23 15:19:39 +00001637 case bitc::TYPE_CODE_FUNCTION_OLD: {
1638 // FIXME: attrid is dead, remove it in LLVM 4.0
1639 // FUNCTION: [vararg, attrid, retty, paramty x N]
1640 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001641 return error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +00001642 SmallVector<Type*, 8> ArgTys;
1643 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1644 if (Type *T = getTypeByID(Record[i]))
1645 ArgTys.push_back(T);
1646 else
1647 break;
1648 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001649
Nuno Lopes561dae02012-05-23 15:19:39 +00001650 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001651 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001652 return error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +00001653
1654 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1655 break;
1656 }
Chad Rosier95898722011-11-03 00:14:01 +00001657 case bitc::TYPE_CODE_FUNCTION: {
1658 // FUNCTION: [vararg, retty, paramty x N]
1659 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001660 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001661 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +00001662 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001663 if (Type *T = getTypeByID(Record[i])) {
1664 if (!FunctionType::isValidArgumentType(T))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001665 return error("Invalid function argument type");
Chad Rosier95898722011-11-03 00:14:01 +00001666 ArgTys.push_back(T);
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001667 }
Chad Rosier95898722011-11-03 00:14:01 +00001668 else
1669 break;
1670 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001671
Chad Rosier95898722011-11-03 00:14:01 +00001672 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001673 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001674 return error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +00001675
1676 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1677 break;
1678 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001679 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +00001680 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001681 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001682 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001683 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1684 if (Type *T = getTypeByID(Record[i]))
1685 EltTys.push_back(T);
1686 else
1687 break;
1688 }
1689 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001690 return error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001691 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001692 break;
1693 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001694 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001695 if (convertToString(Record, 0, TypeName))
1696 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001697 continue;
1698
1699 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1700 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001701 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001702
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001703 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001704 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001705
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001706 // Check to see if this was forward referenced, if so fill in the temp.
1707 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1708 if (Res) {
1709 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001710 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001711 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001712 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001713 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001714
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001715 SmallVector<Type*, 8> EltTys;
1716 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1717 if (Type *T = getTypeByID(Record[i]))
1718 EltTys.push_back(T);
1719 else
1720 break;
1721 }
1722 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001723 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001724 Res->setBody(EltTys, Record[0]);
1725 ResultTy = Res;
1726 break;
1727 }
1728 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1729 if (Record.size() != 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001730 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001731
1732 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001733 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001734
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001735 // Check to see if this was forward referenced, if so fill in the temp.
1736 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1737 if (Res) {
1738 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001739 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001740 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001741 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001742 TypeName.clear();
1743 ResultTy = Res;
1744 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001745 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001746 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1747 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001748 return error("Invalid record");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001749 ResultTy = getTypeByID(Record[1]);
1750 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001751 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001752 ResultTy = ArrayType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001753 break;
1754 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1755 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001756 return error("Invalid record");
Filipe Cabecinhas8e421902015-06-03 00:05:30 +00001757 if (Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001758 return error("Invalid vector length");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001759 ResultTy = getTypeByID(Record[1]);
1760 if (!ResultTy || !StructType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001761 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001762 ResultTy = VectorType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001763 break;
1764 }
1765
1766 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001767 return error("Invalid TYPE table");
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001768 if (TypeList[NumRecords])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001769 return error(
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001770 "Invalid TYPE table: Only named structs can be forward referenced");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001771 assert(ResultTy && "Didn't read a type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001772 TypeList[NumRecords++] = ResultTy;
1773 }
1774}
1775
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001776Error BitcodeReader::parseOperandBundleTags() {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001777 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1778 return error("Invalid record");
1779
1780 if (!BundleTags.empty())
1781 return error("Invalid multiple blocks");
1782
1783 SmallVector<uint64_t, 64> Record;
1784
Eugene Zelenko1804a772016-08-25 00:45:04 +00001785 while (true) {
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001786 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1787
1788 switch (Entry.Kind) {
1789 case BitstreamEntry::SubBlock: // Handled for us already.
1790 case BitstreamEntry::Error:
1791 return error("Malformed block");
1792 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001793 return Error::success();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001794 case BitstreamEntry::Record:
1795 // The interesting case.
1796 break;
1797 }
1798
1799 // Tags are implicitly mapped to integers by their order.
1800
1801 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1802 return error("Invalid record");
1803
1804 // OPERAND_BUNDLE_TAG: [strchr x N]
1805 BundleTags.emplace_back();
1806 if (convertToString(Record, 0, BundleTags.back()))
1807 return error("Invalid record");
1808 Record.clear();
1809 }
1810}
1811
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001812Error BitcodeReader::parseSyncScopeNames() {
1813 if (Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
1814 return error("Invalid record");
1815
1816 if (!SSIDs.empty())
1817 return error("Invalid multiple synchronization scope names blocks");
1818
1819 SmallVector<uint64_t, 64> Record;
1820 while (true) {
1821 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1822 switch (Entry.Kind) {
1823 case BitstreamEntry::SubBlock: // Handled for us already.
1824 case BitstreamEntry::Error:
1825 return error("Malformed block");
1826 case BitstreamEntry::EndBlock:
1827 if (SSIDs.empty())
1828 return error("Invalid empty synchronization scope names block");
1829 return Error::success();
1830 case BitstreamEntry::Record:
1831 // The interesting case.
1832 break;
1833 }
1834
1835 // Synchronization scope names are implicitly mapped to synchronization
1836 // scope IDs by their order.
1837
1838 if (Stream.readRecord(Entry.ID, Record) != bitc::SYNC_SCOPE_NAME)
1839 return error("Invalid record");
1840
1841 SmallString<16> SSN;
1842 if (convertToString(Record, 0, SSN))
1843 return error("Invalid record");
1844
1845 SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
1846 Record.clear();
1847 }
1848}
1849
Teresa Johnsonff642b92015-09-17 20:12:00 +00001850/// Associate a value with its name from the given index in the provided record.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001851Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1852 unsigned NameIndex, Triple &TT) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001853 SmallString<128> ValueName;
1854 if (convertToString(Record, NameIndex, ValueName))
1855 return error("Invalid record");
1856 unsigned ValueID = Record[0];
1857 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1858 return error("Invalid record");
1859 Value *V = ValueList[ValueID];
1860
Filipe Cabecinhasa2b0ac42015-11-04 14:53:36 +00001861 StringRef NameStr(ValueName.data(), ValueName.size());
1862 if (NameStr.find_first_of(0) != StringRef::npos)
1863 return error("Invalid value name");
1864 V->setName(NameStr);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001865 auto *GO = dyn_cast<GlobalObject>(V);
1866 if (GO) {
1867 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
Sam Clegg99966072017-11-14 00:49:16 +00001868 if (TT.supportsCOMDAT())
Teresa Johnsonff642b92015-09-17 20:12:00 +00001869 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
Sam Clegg99966072017-11-14 00:49:16 +00001870 else
1871 GO->setComdat(nullptr);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001872 }
1873 }
1874 return V;
1875}
1876
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001877/// Helper to note and return the current location, and jump to the given
1878/// offset.
1879static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1880 BitstreamCursor &Stream) {
1881 // Save the current parsing location so we can jump back at the end
1882 // of the VST read.
1883 uint64_t CurrentBit = Stream.GetCurrentBitNo();
1884 Stream.JumpToBit(Offset * 32);
1885#ifndef NDEBUG
1886 // Do some checking if we are in debug mode.
1887 BitstreamEntry Entry = Stream.advance();
1888 assert(Entry.Kind == BitstreamEntry::SubBlock);
1889 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1890#else
1891 // In NDEBUG mode ignore the output so we don't get an unused variable
1892 // warning.
1893 Stream.advance();
1894#endif
1895 return CurrentBit;
1896}
1897
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001898void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
1899 Function *F,
1900 ArrayRef<uint64_t> Record) {
1901 // Note that we subtract 1 here because the offset is relative to one word
1902 // before the start of the identification or module block, which was
1903 // historically always the start of the regular bitcode header.
1904 uint64_t FuncWordOffset = Record[1] - 1;
1905 uint64_t FuncBitOffset = FuncWordOffset * 32;
1906 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1907 // Set the LastFunctionBlockBit to point to the last function block.
1908 // Later when parsing is resumed after function materialization,
1909 // we can simply skip that last function block.
1910 if (FuncBitOffset > LastFunctionBlockBit)
1911 LastFunctionBlockBit = FuncBitOffset;
1912}
1913
1914/// Read a new-style GlobalValue symbol table.
1915Error BitcodeReader::parseGlobalValueSymbolTable() {
1916 unsigned FuncBitcodeOffsetDelta =
1917 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1918
1919 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1920 return error("Invalid record");
1921
1922 SmallVector<uint64_t, 64> Record;
1923 while (true) {
1924 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1925
1926 switch (Entry.Kind) {
1927 case BitstreamEntry::SubBlock:
1928 case BitstreamEntry::Error:
1929 return error("Malformed block");
1930 case BitstreamEntry::EndBlock:
1931 return Error::success();
1932 case BitstreamEntry::Record:
1933 break;
1934 }
1935
1936 Record.clear();
1937 switch (Stream.readRecord(Entry.ID, Record)) {
1938 case bitc::VST_CODE_FNENTRY: // [valueid, offset]
1939 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
1940 cast<Function>(ValueList[Record[0]]), Record);
1941 break;
1942 }
1943 }
1944}
1945
Teresa Johnsonff642b92015-09-17 20:12:00 +00001946/// Parse the value symbol table at either the current parsing location or
1947/// at the given bit offset if provided.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00001948Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001949 uint64_t CurrentBit;
1950 // Pass in the Offset to distinguish between calling for the module-level
1951 // VST (where we want to jump to the VST offset) and the function-level
1952 // VST (where we don't).
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001953 if (Offset > 0) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001954 CurrentBit = jumpToValueSymbolTable(Offset, Stream);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00001955 // If this module uses a string table, read this as a module-level VST.
1956 if (UseStrtab) {
1957 if (Error Err = parseGlobalValueSymbolTable())
1958 return Err;
1959 Stream.JumpToBit(CurrentBit);
1960 return Error::success();
1961 }
1962 // Otherwise, the VST will be in a similar format to a function-level VST,
1963 // and will contain symbol names.
1964 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001965
1966 // Compute the delta between the bitcode indices in the VST (the word offset
1967 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1968 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1969 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1970 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1971 // just before entering the VST subblock because: 1) the EnterSubBlock
1972 // changes the AbbrevID width; 2) the VST block is nested within the same
1973 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1974 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1975 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1976 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1977 unsigned FuncBitcodeOffsetDelta =
1978 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1979
Chris Lattner982ec1e2007-05-05 00:17:00 +00001980 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001981 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001982
1983 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001984
David Majnemer3087b222015-01-20 05:58:07 +00001985 Triple TT(TheModule->getTargetTriple());
1986
Chris Lattnerccaa4482007-04-23 21:26:05 +00001987 // Read all the records for this value table.
1988 SmallString<128> ValueName;
Eugene Zelenko1804a772016-08-25 00:45:04 +00001989
1990 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00001991 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001992
Chris Lattner27d38752013-01-20 02:13:19 +00001993 switch (Entry.Kind) {
1994 case BitstreamEntry::SubBlock: // Handled for us already.
1995 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001996 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001997 case BitstreamEntry::EndBlock:
Teresa Johnsonff642b92015-09-17 20:12:00 +00001998 if (Offset > 0)
1999 Stream.JumpToBit(CurrentBit);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002000 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00002001 case BitstreamEntry::Record:
2002 // The interesting case.
2003 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00002004 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002005
Chris Lattnerccaa4482007-04-23 21:26:05 +00002006 // Read a record.
2007 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00002008 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00002009 default: // Default behavior: unknown type.
2010 break;
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002011 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002012 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
2013 if (Error Err = ValOrErr.takeError())
2014 return Err;
Teresa Johnsonff642b92015-09-17 20:12:00 +00002015 ValOrErr.get();
2016 break;
2017 }
2018 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00002019 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002020 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
2021 if (Error Err = ValOrErr.takeError())
2022 return Err;
Teresa Johnsonff642b92015-09-17 20:12:00 +00002023 Value *V = ValOrErr.get();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002024
Peter Collingbournedb4cafa2017-04-06 19:39:24 +00002025 // Ignore function offsets emitted for aliases of functions in older
2026 // versions of LLVM.
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002027 if (auto *F = dyn_cast<Function>(V))
2028 setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
Chris Lattnerccaa4482007-04-23 21:26:05 +00002029 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00002030 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00002031 case bitc::VST_CODE_BBENTRY: {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002032 if (convertToString(Record, 1, ValueName))
2033 return error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00002034 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002035 if (!BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002036 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002037
Daniel Dunbard786b512009-07-26 00:34:27 +00002038 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00002039 ValueName.clear();
2040 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00002041 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00002042 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00002043 }
2044}
2045
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002046/// Decode a signed value stored with the sign bit in the LSB for dense VBR
2047/// encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002048uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00002049 if ((V & 1) == 0)
2050 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002051 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00002052 return -(V >> 1);
2053 // There is no such thing as -0 with integers. "-0" really means MININT.
2054 return 1ULL << 63;
2055}
2056
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002057/// Resolve all of the initializers for global values and aliases that we can.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002058Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
Eugene Zelenko975293f2017-09-07 23:28:24 +00002059 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
2060 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002061 IndirectSymbolInitWorklist;
Eugene Zelenko975293f2017-09-07 23:28:24 +00002062 std::vector<std::pair<Function *, unsigned>> FunctionPrefixWorklist;
2063 std::vector<std::pair<Function *, unsigned>> FunctionPrologueWorklist;
2064 std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFnWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002065
Chris Lattner44c17072007-04-26 02:46:40 +00002066 GlobalInitWorklist.swap(GlobalInits);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002067 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002068 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002069 FunctionPrologueWorklist.swap(FunctionPrologues);
David Majnemer7fddecc2015-06-17 20:52:32 +00002070 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
Chris Lattner44c17072007-04-26 02:46:40 +00002071
2072 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00002073 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002074 if (ValID >= ValueList.size()) {
2075 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00002076 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002077 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002078 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00002079 GlobalInitWorklist.back().first->setInitializer(C);
2080 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002081 return error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00002082 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002083 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002084 }
2085
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002086 while (!IndirectSymbolInitWorklist.empty()) {
2087 unsigned ValID = IndirectSymbolInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002088 if (ValID >= ValueList.size()) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002089 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002090 } else {
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002091 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2092 if (!C)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002093 return error("Expected a constant");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002094 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2095 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002096 return error("Alias and aliasee types don't match");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002097 GIS->setIndirectSymbol(C);
Chris Lattner44c17072007-04-26 02:46:40 +00002098 }
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002099 IndirectSymbolInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002100 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002101
2102 while (!FunctionPrefixWorklist.empty()) {
2103 unsigned ValID = FunctionPrefixWorklist.back().second;
2104 if (ValID >= ValueList.size()) {
2105 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2106 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002107 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002108 FunctionPrefixWorklist.back().first->setPrefixData(C);
2109 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002110 return error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002111 }
2112 FunctionPrefixWorklist.pop_back();
2113 }
2114
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002115 while (!FunctionPrologueWorklist.empty()) {
2116 unsigned ValID = FunctionPrologueWorklist.back().second;
2117 if (ValID >= ValueList.size()) {
2118 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2119 } else {
2120 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2121 FunctionPrologueWorklist.back().first->setPrologueData(C);
2122 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002123 return error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002124 }
2125 FunctionPrologueWorklist.pop_back();
2126 }
2127
David Majnemer7fddecc2015-06-17 20:52:32 +00002128 while (!FunctionPersonalityFnWorklist.empty()) {
2129 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2130 if (ValID >= ValueList.size()) {
2131 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2132 } else {
2133 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2134 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2135 else
2136 return error("Expected a constant");
2137 }
2138 FunctionPersonalityFnWorklist.pop_back();
2139 }
2140
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002141 return Error::success();
Chris Lattner44c17072007-04-26 02:46:40 +00002142}
2143
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002144static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002145 SmallVector<uint64_t, 8> Words(Vals.size());
David Majnemer2d006e72016-08-12 04:32:42 +00002146 transform(Vals, Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00002147 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002148
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002149 return APInt(TypeBits, Words);
2150}
2151
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002152Error BitcodeReader::parseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002153 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002154 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002155
2156 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002157
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002158 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00002159 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00002160 unsigned NextCstNo = ValueList.size();
Eugene Zelenko1804a772016-08-25 00:45:04 +00002161
2162 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00002163 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002164
Chris Lattner27d38752013-01-20 02:13:19 +00002165 switch (Entry.Kind) {
2166 case BitstreamEntry::SubBlock: // Handled for us already.
2167 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002168 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002169 case BitstreamEntry::EndBlock:
2170 if (NextCstNo != ValueList.size())
George Burgess IV1030d682016-01-20 22:15:23 +00002171 return error("Invalid constant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00002172
Chris Lattner27d38752013-01-20 02:13:19 +00002173 // Once all the constants have been read, go through and resolve forward
2174 // references.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002175 ValueList.resolveConstantForwardRefs();
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002176 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00002177 case BitstreamEntry::Record:
2178 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00002179 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002180 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002181
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002182 // Read a record.
2183 Record.clear();
Filipe Cabecinhas2849b482016-06-05 18:43:17 +00002184 Type *VoidType = Type::getVoidTy(Context);
Craig Topper2617dcc2014-04-15 06:32:26 +00002185 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002186 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002187 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002188 default: // Default behavior: unknown constant
2189 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00002190 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002191 break;
2192 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2193 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002194 return error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00002195 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002196 return error("Invalid record");
Filipe Cabecinhas2849b482016-06-05 18:43:17 +00002197 if (TypeList[Record[0]] == VoidType)
2198 return error("Invalid constant type");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002199 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00002200 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002201 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00002202 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002203 break;
2204 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002205 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002206 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002207 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00002208 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00002209 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002210 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002211 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002212
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002213 APInt VInt =
2214 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002215 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002216
Chris Lattner08feb1e2007-04-24 04:04:35 +00002217 break;
2218 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002219 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00002220 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002221 return error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00002222 if (CurTy->isHalfTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002223 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
Tim Northover29178a32013-01-22 09:46:31 +00002224 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00002225 else if (CurTy->isFloatTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002226 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
Tim Northover29178a32013-01-22 09:46:31 +00002227 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002228 else if (CurTy->isDoubleTy())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002229 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
Tim Northover29178a32013-01-22 09:46:31 +00002230 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002231 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00002232 // Bits are not stored the same way as a normal i80 APInt, compensate.
2233 uint64_t Rearrange[2];
2234 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2235 Rearrange[1] = Record[0] >> 48;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002236 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
Tim Northover29178a32013-01-22 09:46:31 +00002237 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002238 } else if (CurTy->isFP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002239 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
Tim Northover29178a32013-01-22 09:46:31 +00002240 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002241 else if (CurTy->isPPC_FP128Ty())
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002242 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
Tim Northover29178a32013-01-22 09:46:31 +00002243 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002244 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00002245 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002246 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00002247 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002248
Chris Lattnere14cb882007-05-04 19:11:41 +00002249 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2250 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002251 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002252
Chris Lattnere14cb882007-05-04 19:11:41 +00002253 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00002254 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002255
Chris Lattner229907c2011-07-18 04:54:35 +00002256 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00002257 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002258 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00002259 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00002260 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002261 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2262 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002263 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002264 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00002265 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002266 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2267 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002268 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002269 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00002270 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00002271 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002272 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00002273 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002274 break;
2275 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002276 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00002277 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2278 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002279 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002280
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002281 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002282 V = ConstantDataArray::getString(Context, Elts,
2283 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00002284 break;
2285 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002286 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2287 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002288 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002289
Chris Lattner372dd1e2012-01-30 00:51:16 +00002290 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
Chris Lattner372dd1e2012-01-30 00:51:16 +00002291 if (EltTy->isIntegerTy(8)) {
2292 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2293 if (isa<VectorType>(CurTy))
2294 V = ConstantDataVector::get(Context, Elts);
2295 else
2296 V = ConstantDataArray::get(Context, Elts);
2297 } else if (EltTy->isIntegerTy(16)) {
2298 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2299 if (isa<VectorType>(CurTy))
2300 V = ConstantDataVector::get(Context, Elts);
2301 else
2302 V = ConstantDataArray::get(Context, Elts);
2303 } else if (EltTy->isIntegerTy(32)) {
2304 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2305 if (isa<VectorType>(CurTy))
2306 V = ConstantDataVector::get(Context, Elts);
2307 else
2308 V = ConstantDataArray::get(Context, Elts);
2309 } else if (EltTy->isIntegerTy(64)) {
2310 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2311 if (isa<VectorType>(CurTy))
2312 V = ConstantDataVector::get(Context, Elts);
2313 else
2314 V = ConstantDataArray::get(Context, Elts);
Justin Bognera43eacb2016-01-06 22:31:32 +00002315 } else if (EltTy->isHalfTy()) {
2316 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2317 if (isa<VectorType>(CurTy))
2318 V = ConstantDataVector::getFP(Context, Elts);
2319 else
2320 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002321 } else if (EltTy->isFloatTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00002322 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002323 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00002324 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002325 else
Justin Bognera43eacb2016-01-06 22:31:32 +00002326 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002327 } else if (EltTy->isDoubleTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00002328 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002329 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00002330 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002331 else
Justin Bognera43eacb2016-01-06 22:31:32 +00002332 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002333 } else {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002334 return error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00002335 }
2336 break;
2337 }
Cameron McInallycbde0d92018-11-13 18:15:47 +00002338 case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval]
2339 if (Record.size() < 2)
2340 return error("Invalid record");
2341 int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
2342 if (Opc < 0) {
2343 V = UndefValue::get(CurTy); // Unknown unop.
2344 } else {
2345 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2346 unsigned Flags = 0;
2347 V = ConstantExpr::get(Opc, LHS, Flags);
2348 }
2349 break;
2350 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002351 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002352 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002353 return error("Invalid record");
2354 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002355 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002356 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00002357 } else {
2358 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2359 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00002360 unsigned Flags = 0;
2361 if (Record.size() >= 4) {
2362 if (Opc == Instruction::Add ||
2363 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002364 Opc == Instruction::Mul ||
2365 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00002366 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2367 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2368 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2369 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002370 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002371 Opc == Instruction::UDiv ||
2372 Opc == Instruction::LShr ||
2373 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00002374 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00002375 Flags |= SDivOperator::IsExact;
2376 }
2377 }
2378 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00002379 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002380 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002381 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002382 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002383 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002384 return error("Invalid record");
2385 int Opc = getDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00002386 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002387 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00002388 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002389 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002390 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002391 return error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00002392 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002393 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2394 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002395 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002396 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002397 }
Peter Collingbourned93620b2016-11-10 22:34:55 +00002398 case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2399 case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2400 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2401 // operands]
David Blaikieb9263572015-03-13 21:03:36 +00002402 unsigned OpNum = 0;
2403 Type *PointeeType = nullptr;
Peter Collingbourned93620b2016-11-10 22:34:55 +00002404 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
2405 Record.size() % 2)
David Blaikieb9263572015-03-13 21:03:36 +00002406 PointeeType = getTypeByID(Record[OpNum++]);
Peter Collingbourned93620b2016-11-10 22:34:55 +00002407
2408 bool InBounds = false;
2409 Optional<unsigned> InRangeIndex;
2410 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
2411 uint64_t Op = Record[OpNum++];
2412 InBounds = Op & 1;
2413 InRangeIndex = Op >> 1;
2414 } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2415 InBounds = true;
2416
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002417 SmallVector<Constant*, 16> Elts;
David Blaikieb9263572015-03-13 21:03:36 +00002418 while (OpNum != Record.size()) {
2419 Type *ElTy = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002420 if (!ElTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002421 return error("Invalid record");
David Blaikieb9263572015-03-13 21:03:36 +00002422 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002423 }
David Blaikieb9263572015-03-13 21:03:36 +00002424
David Blaikieb9263572015-03-13 21:03:36 +00002425 if (PointeeType &&
David Blaikie4a2e73b2015-04-02 18:55:32 +00002426 PointeeType !=
Peter Collingbourne9ef5a8c2016-11-13 06:59:28 +00002427 cast<PointerType>(Elts[0]->getType()->getScalarType())
David Blaikie4a2e73b2015-04-02 18:55:32 +00002428 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002429 return error("Explicit gep operator type does not match pointee type "
David Blaikie12cf5d702015-03-16 22:03:50 +00002430 "of pointer operand");
David Blaikie4a2e73b2015-04-02 18:55:32 +00002431
Filipe Cabecinhasfc2a3c92016-06-05 18:43:26 +00002432 if (Elts.size() < 1)
2433 return error("Invalid gep with no operands");
2434
David Blaikie4a2e73b2015-04-02 18:55:32 +00002435 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2436 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
Peter Collingbourned93620b2016-11-10 22:34:55 +00002437 InBounds, InRangeIndex);
Chris Lattner890683d2007-04-24 18:15:21 +00002438 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002439 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00002440 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002441 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002442 return error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00002443
2444 Type *SelectorTy = Type::getInt1Ty(Context);
2445
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00002446 // The selector might be an i1 or an <n x i1>
2447 // Get the type from the ValueList before getting a forward ref.
Joe Abbey1a6e7702013-09-12 22:02:31 +00002448 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00002449 if (Value *V = ValueList[Record[0]])
2450 if (SelectorTy != V->getType())
2451 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
Joe Abbey1a6e7702013-09-12 22:02:31 +00002452
2453 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2454 SelectorTy),
2455 ValueList.getConstantFwdRef(Record[1],CurTy),
2456 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002457 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00002458 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002459 case bitc::CST_CODE_CE_EXTRACTELT
2460 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002461 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002462 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002463 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002464 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002465 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002466 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002467 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002468 Constant *Op1 = nullptr;
2469 if (Record.size() == 4) {
2470 Type *IdxTy = getTypeByID(Record[2]);
2471 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002472 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002473 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2474 } else // TODO: Remove with llvm 4.0
2475 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2476 if (!Op1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002477 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002478 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002479 break;
2480 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002481 case bitc::CST_CODE_CE_INSERTELT
2482 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002483 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002484 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002485 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002486 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2487 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2488 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002489 Constant *Op2 = nullptr;
2490 if (Record.size() == 4) {
2491 Type *IdxTy = getTypeByID(Record[2]);
2492 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002493 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002494 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2495 } else // TODO: Remove with llvm 4.0
2496 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2497 if (!Op2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002498 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002499 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002500 break;
2501 }
2502 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002503 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002504 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002505 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002506 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2507 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002508 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002509 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002510 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002511 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002512 break;
2513 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00002514 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002515 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2516 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00002517 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002518 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002519 return error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002520 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2521 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002522 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002523 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00002524 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002525 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00002526 break;
2527 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002528 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002529 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002530 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002531 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002532 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002533 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002534 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2535 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2536
Duncan Sands9dff9be2010-02-15 16:12:20 +00002537 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002538 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00002539 else
Owen Anderson487375e2009-07-29 18:55:55 +00002540 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002541 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00002542 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002543 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00002544 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002545 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002546 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002547 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002548 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00002549 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002550 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002551 unsigned AsmStrSize = Record[1];
2552 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002553 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002554 unsigned ConstStrSize = Record[2+AsmStrSize];
2555 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002556 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002557
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002558 for (unsigned i = 0; i != AsmStrSize; ++i)
2559 AsmStr += (char)Record[2+i];
2560 for (unsigned i = 0; i != ConstStrSize; ++i)
2561 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00002562 PointerType *PTy = cast<PointerType>(CurTy);
Gerolf Hoflehner1c3a0782018-04-17 04:02:24 +00002563 UpgradeInlineAsmString(&AsmStr);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002564 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002565 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002566 break;
2567 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002568 // This version adds support for the asm dialect keywords (e.g.,
2569 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002570 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002571 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002572 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002573 std::string AsmStr, ConstrStr;
2574 bool HasSideEffects = Record[0] & 1;
2575 bool IsAlignStack = (Record[0] >> 1) & 1;
2576 unsigned AsmDialect = Record[0] >> 2;
2577 unsigned AsmStrSize = Record[1];
2578 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002579 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002580 unsigned ConstStrSize = Record[2+AsmStrSize];
2581 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002582 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002583
2584 for (unsigned i = 0; i != AsmStrSize; ++i)
2585 AsmStr += (char)Record[2+i];
2586 for (unsigned i = 0; i != ConstStrSize; ++i)
2587 ConstrStr += (char)Record[3+AsmStrSize+i];
2588 PointerType *PTy = cast<PointerType>(CurTy);
Gerolf Hoflehner1c3a0782018-04-17 04:02:24 +00002589 UpgradeInlineAsmString(&AsmStr);
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002590 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2591 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00002592 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002593 break;
2594 }
Chris Lattner5956dc82009-10-28 05:53:48 +00002595 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00002596 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002597 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002598 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002599 if (!FnTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002600 return error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00002601 Function *Fn =
2602 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00002603 if (!Fn)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002604 return error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002605
2606 // If the function is already parsed we can insert the block address right
2607 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002608 BasicBlock *BB;
2609 unsigned BBID = Record[2];
2610 if (!BBID)
2611 // Invalid reference to entry block.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002612 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002613 if (!Fn->empty()) {
2614 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002615 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002616 if (BBI == BBE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002617 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002618 ++BBI;
2619 }
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00002620 BB = &*BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002621 } else {
2622 // Otherwise insert a placeholder and remember it so it can be inserted
2623 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00002624 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2625 if (FwdBBs.empty())
2626 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00002627 if (FwdBBs.size() < BBID + 1)
2628 FwdBBs.resize(BBID + 1);
2629 if (!FwdBBs[BBID])
2630 FwdBBs[BBID] = BasicBlock::Create(Context);
2631 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002632 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002633 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00002634 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002635 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002636 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002637
David Majnemer8a1c45d2015-12-12 05:38:55 +00002638 ValueList.assignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00002639 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002640 }
2641}
Chris Lattner1314b992007-04-22 06:23:29 +00002642
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002643Error BitcodeReader::parseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00002644 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002645 return error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00002646
Chad Rosierca2567b2011-12-07 21:44:12 +00002647 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002648 SmallVector<uint64_t, 64> Record;
Eugene Zelenko1804a772016-08-25 00:45:04 +00002649
2650 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00002651 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002652
Chris Lattner27d38752013-01-20 02:13:19 +00002653 switch (Entry.Kind) {
2654 case BitstreamEntry::SubBlock: // Handled for us already.
2655 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002656 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002657 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002658 return Error::success();
Chris Lattner27d38752013-01-20 02:13:19 +00002659 case BitstreamEntry::Record:
2660 // The interesting case.
2661 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00002662 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002663
Chad Rosierca2567b2011-12-07 21:44:12 +00002664 // Read a use list record.
2665 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002666 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00002667 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00002668 default: // Default behavior: unknown type.
2669 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002670 case bitc::USELIST_CODE_BB:
2671 IsBB = true;
Justin Bognerb03fd122016-08-17 05:10:15 +00002672 LLVM_FALLTHROUGH;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002673 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00002674 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002675 if (RecordLength < 3)
2676 // Records should have at least an ID and two indexes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002677 return error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002678 unsigned ID = Record.back();
2679 Record.pop_back();
2680
2681 Value *V;
2682 if (IsBB) {
2683 assert(ID < FunctionBBs.size() && "Basic block not found");
2684 V = FunctionBBs[ID];
2685 } else
2686 V = ValueList[ID];
2687 unsigned NumUses = 0;
2688 SmallDenseMap<const Use *, unsigned, 16> Order;
Rafael Espindola257a3532016-01-15 19:00:20 +00002689 for (const Use &U : V->materialized_uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00002690 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002691 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00002692 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002693 }
2694 if (Order.size() != Record.size() || NumUses > Record.size())
2695 // Mismatches can happen if the functions are being materialized lazily
2696 // (out-of-order), or a value has been upgraded.
2697 break;
2698
2699 V->sortUseList([&](const Use &L, const Use &R) {
2700 return Order.lookup(&L) < Order.lookup(&R);
2701 });
Chad Rosierca2567b2011-12-07 21:44:12 +00002702 break;
2703 }
2704 }
2705 }
2706}
2707
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002708/// When we see the block for metadata, remember where it is and then skip it.
2709/// This lets us lazily deserialize the metadata.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002710Error BitcodeReader::rememberAndSkipMetadata() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002711 // Save the current stream state.
2712 uint64_t CurBit = Stream.GetCurrentBitNo();
2713 DeferredMetadataInfo.push_back(CurBit);
2714
2715 // Skip over the block for now.
2716 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002717 return error("Invalid record");
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002718 return Error::success();
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002719}
2720
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00002721Error BitcodeReader::materializeMetadata() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002722 for (uint64_t BitPos : DeferredMetadataInfo) {
2723 // Move the bit stream to the saved position.
2724 Stream.JumpToBit(BitPos);
Mehdi Aminief27db82016-12-12 19:34:26 +00002725 if (Error Err = MDLoader->parseModuleMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002726 return Err;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002727 }
Peter Collingbourne89061b22017-06-12 20:10:48 +00002728
2729 // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
2730 // metadata.
2731 if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
2732 NamedMDNode *LinkerOpts =
2733 TheModule->getOrInsertNamedMetadata("llvm.linker.options");
2734 for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
2735 LinkerOpts->addOperand(cast<MDNode>(MDOptions));
2736 }
2737
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002738 DeferredMetadataInfo.clear();
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002739 return Error::success();
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002740}
2741
Rafael Espindola468b8682015-04-01 14:44:59 +00002742void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00002743
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002744/// When we see the block for a function body, remember where it is and then
2745/// skip it. This lets us lazily deserialize the functions.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002746Error BitcodeReader::rememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002747 // Get the function we are talking about.
2748 if (FunctionsWithBodies.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002749 return error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002750
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002751 Function *Fn = FunctionsWithBodies.back();
2752 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002753
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002754 // Save the current stream state.
2755 uint64_t CurBit = Stream.GetCurrentBitNo();
Teresa Johnson1493ad92015-10-10 14:18:36 +00002756 assert(
2757 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
2758 "Mismatch between VST and scanned function offsets");
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00002759 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002760
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002761 // Skip over the function block for now.
2762 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002763 return error("Invalid record");
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002764 return Error::success();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002765}
2766
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002767Error BitcodeReader::globalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002768 // Patch the initializers for globals and aliases up.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002769 if (Error Err = resolveGlobalAndIndirectSymbolInits())
2770 return Err;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002771 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002772 return error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002773
2774 // Look for intrinsic functions which need to be upgraded at some point
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002775 for (Function &F : *TheModule) {
Adrian Prantl6825fb62017-04-18 01:21:53 +00002776 MDLoader->upgradeDebugIntrinsics(F);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002777 Function *NewFn;
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002778 if (UpgradeIntrinsicFunction(&F, NewFn))
Rafael Espindola4e721212015-07-02 16:22:40 +00002779 UpgradedIntrinsics[&F] = NewFn;
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00002780 else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
2781 // Some types could be renamed during loading if several modules are
2782 // loaded in the same LLVMContext (LTO scenario). In this case we should
2783 // remangle intrinsics names as well.
2784 RemangledIntrinsics[&F] = Remangled.getValue();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002785 }
2786
2787 // Look for global variables which need to be renamed.
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002788 for (GlobalVariable &GV : TheModule->globals())
2789 UpgradeGlobalVariable(&GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00002790
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002791 // Force deallocation of memory for these vectors to favor the client that
2792 // want lazy deserialization.
Eugene Zelenko975293f2017-09-07 23:28:24 +00002793 std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
2794 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>().swap(
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002795 IndirectSymbolInits);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002796 return Error::success();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002797}
2798
Teresa Johnson1493ad92015-10-10 14:18:36 +00002799/// Support for lazy parsing of function bodies. This is required if we
2800/// either have an old bitcode file without a VST forward declaration record,
2801/// or if we have an anonymous function being materialized, since anonymous
2802/// functions do not have a name and are therefore not in the VST.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002803Error BitcodeReader::rememberAndSkipFunctionBodies() {
Teresa Johnson1493ad92015-10-10 14:18:36 +00002804 Stream.JumpToBit(NextUnreadBit);
2805
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002806 if (Stream.AtEndOfStream())
2807 return error("Could not find function in stream");
Teresa Johnson1493ad92015-10-10 14:18:36 +00002808
Filipe Cabecinhas7aae2f22015-11-03 13:48:26 +00002809 if (!SeenFirstFunctionBody)
2810 return error("Trying to materialize functions before seeing function blocks");
2811
Teresa Johnson1493ad92015-10-10 14:18:36 +00002812 // An old bitcode file with the symbol table at the end would have
2813 // finished the parse greedily.
2814 assert(SeenValueSymbolTable);
2815
2816 SmallVector<uint64_t, 64> Record;
2817
Eugene Zelenko1804a772016-08-25 00:45:04 +00002818 while (true) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00002819 BitstreamEntry Entry = Stream.advance();
2820 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002821 default:
2822 return error("Expect SubBlock");
2823 case BitstreamEntry::SubBlock:
2824 switch (Entry.ID) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00002825 default:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002826 return error("Expect function block");
2827 case bitc::FUNCTION_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002828 if (Error Err = rememberAndSkipFunctionBody())
2829 return Err;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002830 NextUnreadBit = Stream.GetCurrentBitNo();
Peter Collingbourne58f7f072016-11-09 00:51:04 +00002831 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00002832 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00002833 }
2834 }
2835}
2836
Peter Collingbourne939c7d92016-11-08 04:16:57 +00002837bool BitcodeReaderBase::readBlockInfo() {
Peter Collingbourne77c89b62016-11-08 04:17:11 +00002838 Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock();
2839 if (!NewBlockInfo)
2840 return true;
2841 BlockInfo = std::move(*NewBlockInfo);
2842 return false;
Peter Collingbourne939c7d92016-11-08 04:16:57 +00002843}
2844
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002845Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002846 // v1: [selection_kind, name]
2847 // v2: [strtab_offset, strtab_size, selection_kind]
2848 StringRef Name;
2849 std::tie(Name, Record) = readNameFromStrtab(Record);
2850
Eugene Zelenko975293f2017-09-07 23:28:24 +00002851 if (Record.empty())
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002852 return error("Invalid record");
2853 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002854 std::string OldFormatName;
2855 if (!UseStrtab) {
2856 if (Record.size() < 2)
2857 return error("Invalid record");
2858 unsigned ComdatNameSize = Record[1];
2859 OldFormatName.reserve(ComdatNameSize);
2860 for (unsigned i = 0; i != ComdatNameSize; ++i)
2861 OldFormatName += (char)Record[2 + i];
2862 Name = OldFormatName;
2863 }
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002864 Comdat *C = TheModule->getOrInsertComdat(Name);
2865 C->setSelectionKind(SK);
2866 ComdatList.push_back(C);
2867 return Error::success();
2868}
2869
Steven Wue1f7c5f2018-07-09 16:52:05 +00002870static void inferDSOLocal(GlobalValue *GV) {
2871 // infer dso_local from linkage and visibility if it is not encoded.
2872 if (GV->hasLocalLinkage() ||
2873 (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
2874 GV->setDSOLocal(true);
2875}
2876
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002877Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002878 // v1: [pointer type, isconst, initid, linkage, alignment, section,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002879 // visibility, threadlocal, unnamed_addr, externally_initialized,
Sean Fertilec70d28b2017-10-26 15:00:26 +00002880 // dllstorageclass, comdat, attributes, preemption specifier] (name in VST)
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002881 // v2: [strtab_offset, strtab_size, v1]
2882 StringRef Name;
2883 std::tie(Name, Record) = readNameFromStrtab(Record);
2884
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002885 if (Record.size() < 6)
2886 return error("Invalid record");
2887 Type *Ty = getTypeByID(Record[0]);
2888 if (!Ty)
2889 return error("Invalid record");
2890 bool isConstant = Record[1] & 1;
2891 bool explicitType = Record[1] & 2;
2892 unsigned AddressSpace;
2893 if (explicitType) {
2894 AddressSpace = Record[1] >> 2;
2895 } else {
2896 if (!Ty->isPointerTy())
2897 return error("Invalid type for value");
2898 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2899 Ty = cast<PointerType>(Ty)->getElementType();
2900 }
2901
2902 uint64_t RawLinkage = Record[3];
2903 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2904 unsigned Alignment;
2905 if (Error Err = parseAlignmentValue(Record[4], Alignment))
2906 return Err;
2907 std::string Section;
2908 if (Record[5]) {
2909 if (Record[5] - 1 >= SectionTable.size())
2910 return error("Invalid ID");
2911 Section = SectionTable[Record[5] - 1];
2912 }
2913 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2914 // Local linkage must have default visibility.
2915 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2916 // FIXME: Change to an error if non-default in 4.0.
2917 Visibility = getDecodedVisibility(Record[6]);
2918
2919 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2920 if (Record.size() > 7)
2921 TLM = getDecodedThreadLocalMode(Record[7]);
2922
2923 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
2924 if (Record.size() > 8)
2925 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
2926
2927 bool ExternallyInitialized = false;
2928 if (Record.size() > 9)
2929 ExternallyInitialized = Record[9];
2930
2931 GlobalVariable *NewGV =
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002932 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002933 nullptr, TLM, AddressSpace, ExternallyInitialized);
2934 NewGV->setAlignment(Alignment);
2935 if (!Section.empty())
2936 NewGV->setSection(Section);
2937 NewGV->setVisibility(Visibility);
2938 NewGV->setUnnamedAddr(UnnamedAddr);
2939
2940 if (Record.size() > 10)
2941 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
2942 else
2943 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
2944
2945 ValueList.push_back(NewGV);
2946
2947 // Remember which value to use for the global initializer.
2948 if (unsigned InitID = Record[2])
2949 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
2950
2951 if (Record.size() > 11) {
2952 if (unsigned ComdatID = Record[11]) {
2953 if (ComdatID > ComdatList.size())
2954 return error("Invalid global variable comdat ID");
2955 NewGV->setComdat(ComdatList[ComdatID - 1]);
2956 }
2957 } else if (hasImplicitComdat(RawLinkage)) {
2958 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2959 }
Javed Absarf3d79042017-05-11 12:28:08 +00002960
2961 if (Record.size() > 12) {
2962 auto AS = getAttributes(Record[12]).getFnAttributes();
2963 NewGV->setAttributes(AS);
2964 }
Sean Fertilec70d28b2017-10-26 15:00:26 +00002965
2966 if (Record.size() > 13) {
2967 NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
2968 }
Steven Wue1f7c5f2018-07-09 16:52:05 +00002969 inferDSOLocal(NewGV);
Sean Fertilec70d28b2017-10-26 15:00:26 +00002970
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002971 return Error::success();
2972}
2973
2974Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002975 // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002976 // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00002977 // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST)
Peter Collingbournea0f371a2017-04-17 17:51:36 +00002978 // v2: [strtab_offset, strtab_size, v1]
2979 StringRef Name;
2980 std::tie(Name, Record) = readNameFromStrtab(Record);
2981
Peter Collingbournece24a2a2017-04-12 20:02:09 +00002982 if (Record.size() < 8)
2983 return error("Invalid record");
2984 Type *Ty = getTypeByID(Record[0]);
2985 if (!Ty)
2986 return error("Invalid record");
2987 if (auto *PTy = dyn_cast<PointerType>(Ty))
2988 Ty = PTy->getElementType();
2989 auto *FTy = dyn_cast<FunctionType>(Ty);
2990 if (!FTy)
2991 return error("Invalid type for value");
2992 auto CC = static_cast<CallingConv::ID>(Record[1]);
2993 if (CC & ~CallingConv::MaxID)
2994 return error("Invalid calling convention ID");
2995
Alexander Richardson6bcf2ba2018-08-23 09:25:17 +00002996 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
2997 if (Record.size() > 16)
2998 AddrSpace = Record[16];
2999
3000 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3001 AddrSpace, Name, TheModule);
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003002
3003 Func->setCallingConv(CC);
3004 bool isProto = Record[2];
3005 uint64_t RawLinkage = Record[3];
3006 Func->setLinkage(getDecodedLinkage(RawLinkage));
3007 Func->setAttributes(getAttributes(Record[4]));
3008
3009 unsigned Alignment;
3010 if (Error Err = parseAlignmentValue(Record[5], Alignment))
3011 return Err;
3012 Func->setAlignment(Alignment);
3013 if (Record[6]) {
3014 if (Record[6] - 1 >= SectionTable.size())
3015 return error("Invalid ID");
3016 Func->setSection(SectionTable[Record[6] - 1]);
3017 }
3018 // Local linkage must have default visibility.
3019 if (!Func->hasLocalLinkage())
3020 // FIXME: Change to an error if non-default in 4.0.
3021 Func->setVisibility(getDecodedVisibility(Record[7]));
3022 if (Record.size() > 8 && Record[8]) {
3023 if (Record[8] - 1 >= GCTable.size())
3024 return error("Invalid ID");
3025 Func->setGC(GCTable[Record[8] - 1]);
3026 }
3027 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3028 if (Record.size() > 9)
3029 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
3030 Func->setUnnamedAddr(UnnamedAddr);
3031 if (Record.size() > 10 && Record[10] != 0)
3032 FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
3033
3034 if (Record.size() > 11)
3035 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3036 else
3037 upgradeDLLImportExportLinkage(Func, RawLinkage);
3038
3039 if (Record.size() > 12) {
3040 if (unsigned ComdatID = Record[12]) {
3041 if (ComdatID > ComdatList.size())
3042 return error("Invalid function comdat ID");
3043 Func->setComdat(ComdatList[ComdatID - 1]);
3044 }
3045 } else if (hasImplicitComdat(RawLinkage)) {
3046 Func->setComdat(reinterpret_cast<Comdat *>(1));
3047 }
3048
3049 if (Record.size() > 13 && Record[13] != 0)
3050 FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
3051
3052 if (Record.size() > 14 && Record[14] != 0)
3053 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3054
Sean Fertilec70d28b2017-10-26 15:00:26 +00003055 if (Record.size() > 15) {
3056 Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
3057 }
Steven Wue1f7c5f2018-07-09 16:52:05 +00003058 inferDSOLocal(Func);
Sean Fertilec70d28b2017-10-26 15:00:26 +00003059
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003060 ValueList.push_back(Func);
3061
3062 // If this is a function with a body, remember the prototype we are
3063 // creating now, so that we can match up the body with them later.
3064 if (!isProto) {
3065 Func->setIsMaterializable(true);
3066 FunctionsWithBodies.push_back(Func);
3067 DeferredFunctionInfo[Func] = 0;
3068 }
3069 return Error::success();
3070}
3071
3072Error BitcodeReader::parseGlobalIndirectSymbolRecord(
3073 unsigned BitCode, ArrayRef<uint64_t> Record) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003074 // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
3075 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
Sean Fertilec70d28b2017-10-26 15:00:26 +00003076 // dllstorageclass, threadlocal, unnamed_addr,
3077 // preemption specifier] (name in VST)
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003078 // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
Sean Fertilec70d28b2017-10-26 15:00:26 +00003079 // visibility, dllstorageclass, threadlocal, unnamed_addr,
3080 // preemption specifier] (name in VST)
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003081 // v2: [strtab_offset, strtab_size, v1]
3082 StringRef Name;
3083 std::tie(Name, Record) = readNameFromStrtab(Record);
3084
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003085 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
3086 if (Record.size() < (3 + (unsigned)NewRecord))
3087 return error("Invalid record");
3088 unsigned OpNum = 0;
3089 Type *Ty = getTypeByID(Record[OpNum++]);
3090 if (!Ty)
3091 return error("Invalid record");
3092
3093 unsigned AddrSpace;
3094 if (!NewRecord) {
3095 auto *PTy = dyn_cast<PointerType>(Ty);
3096 if (!PTy)
3097 return error("Invalid type for value");
3098 Ty = PTy->getElementType();
3099 AddrSpace = PTy->getAddressSpace();
3100 } else {
3101 AddrSpace = Record[OpNum++];
3102 }
3103
3104 auto Val = Record[OpNum++];
3105 auto Linkage = Record[OpNum++];
3106 GlobalIndirectSymbol *NewGA;
3107 if (BitCode == bitc::MODULE_CODE_ALIAS ||
3108 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003109 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003110 TheModule);
3111 else
Peter Collingbournea0f371a2017-04-17 17:51:36 +00003112 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003113 nullptr, TheModule);
3114 // Old bitcode files didn't have visibility field.
3115 // Local linkage must have default visibility.
3116 if (OpNum != Record.size()) {
3117 auto VisInd = OpNum++;
3118 if (!NewGA->hasLocalLinkage())
3119 // FIXME: Change to an error if non-default in 4.0.
3120 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3121 }
Rafael Espindola3b9843f2018-01-12 17:03:43 +00003122 if (BitCode == bitc::MODULE_CODE_ALIAS ||
3123 BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
3124 if (OpNum != Record.size())
3125 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3126 else
3127 upgradeDLLImportExportLinkage(NewGA, Linkage);
3128 if (OpNum != Record.size())
3129 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3130 if (OpNum != Record.size())
3131 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
3132 }
Sean Fertilec70d28b2017-10-26 15:00:26 +00003133 if (OpNum != Record.size())
3134 NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
Steven Wue1f7c5f2018-07-09 16:52:05 +00003135 inferDSOLocal(NewGA);
3136
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003137 ValueList.push_back(NewGA);
3138 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3139 return Error::success();
3140}
3141
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003142Error BitcodeReader::parseModule(uint64_t ResumeBit,
3143 bool ShouldLazyLoadMetadata) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003144 if (ResumeBit)
3145 Stream.JumpToBit(ResumeBit);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003146 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003147 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003148
Chris Lattner1314b992007-04-22 06:23:29 +00003149 SmallVector<uint64_t, 64> Record;
Chris Lattner1314b992007-04-22 06:23:29 +00003150
3151 // Read all the records for this module.
Eugene Zelenko1804a772016-08-25 00:45:04 +00003152 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00003153 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003154
Chris Lattner27d38752013-01-20 02:13:19 +00003155 switch (Entry.Kind) {
3156 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003157 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003158 case BitstreamEntry::EndBlock:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003159 return globalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00003160
Chris Lattner27d38752013-01-20 02:13:19 +00003161 case BitstreamEntry::SubBlock:
3162 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00003163 default: // Skip unknown content.
3164 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003165 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003166 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003167 case bitc::BLOCKINFO_BLOCK_ID:
Peter Collingbourne939c7d92016-11-08 04:16:57 +00003168 if (readBlockInfo())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003169 return error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003170 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003171 case bitc::PARAMATTR_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003172 if (Error Err = parseAttributeBlock())
3173 return Err;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003174 break;
Bill Wendlingba629332013-02-10 23:24:25 +00003175 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003176 if (Error Err = parseAttributeGroupBlock())
3177 return Err;
Bill Wendlingba629332013-02-10 23:24:25 +00003178 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003179 case bitc::TYPE_BLOCK_ID_NEW:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003180 if (Error Err = parseTypeTable())
3181 return Err;
Chris Lattner1314b992007-04-22 06:23:29 +00003182 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00003183 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnsonff642b92015-09-17 20:12:00 +00003184 if (!SeenValueSymbolTable) {
3185 // Either this is an old form VST without function index and an
3186 // associated VST forward declaration record (which would have caused
3187 // the VST to be jumped to and parsed before it was encountered
3188 // normally in the stream), or there were no function blocks to
3189 // trigger an earlier parsing of the VST.
3190 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003191 if (Error Err = parseValueSymbolTable())
3192 return Err;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003193 SeenValueSymbolTable = true;
3194 } else {
3195 // We must have had a VST forward declaration record, which caused
3196 // the parser to jump to and parse the VST earlier.
3197 assert(VSTOffset > 0);
3198 if (Stream.SkipBlock())
3199 return error("Invalid record");
3200 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00003201 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003202 case bitc::CONSTANTS_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003203 if (Error Err = parseConstants())
3204 return Err;
3205 if (Error Err = resolveGlobalAndIndirectSymbolInits())
3206 return Err;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003207 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00003208 case bitc::METADATA_BLOCK_ID:
Mehdi Aminibf2090e2016-12-12 19:23:39 +00003209 if (ShouldLazyLoadMetadata) {
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003210 if (Error Err = rememberAndSkipMetadata())
3211 return Err;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003212 break;
3213 }
3214 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
Mehdi Aminief27db82016-12-12 19:34:26 +00003215 if (Error Err = MDLoader->parseModuleMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003216 return Err;
Devang Patel7428d8a2009-07-22 17:43:22 +00003217 break;
Teresa Johnson12545072015-11-15 02:00:09 +00003218 case bitc::METADATA_KIND_BLOCK_ID:
Mehdi Aminief27db82016-12-12 19:34:26 +00003219 if (Error Err = MDLoader->parseMetadataKinds())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003220 return Err;
Teresa Johnson12545072015-11-15 02:00:09 +00003221 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003222 case bitc::FUNCTION_BLOCK_ID:
Mehdi Amini466a64e2016-08-13 23:39:14 +00003223 // If this is the first function body we've seen, reverse the
3224 // FunctionsWithBodies list.
3225 if (!SeenFirstFunctionBody) {
3226 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003227 if (Error Err = globalCleanup())
3228 return Err;
Mehdi Amini466a64e2016-08-13 23:39:14 +00003229 SeenFirstFunctionBody = true;
3230 }
3231
Teresa Johnsonff642b92015-09-17 20:12:00 +00003232 if (VSTOffset > 0) {
3233 // If we have a VST forward declaration record, make sure we
3234 // parse the VST now if we haven't already. It is needed to
3235 // set up the DeferredFunctionInfo vector for lazy reading.
3236 if (!SeenValueSymbolTable) {
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003237 if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3238 return Err;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003239 SeenValueSymbolTable = true;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003240 // Fall through so that we record the NextUnreadBit below.
3241 // This is necessary in case we have an anonymous function that
3242 // is later materialized. Since it will not have a VST entry we
3243 // need to fall back to the lazy parse to find its offset.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003244 } else {
3245 // If we have a VST forward declaration record, but have already
3246 // parsed the VST (just above, when the first function body was
3247 // encountered here), then we are resuming the parse after
Teresa Johnson1493ad92015-10-10 14:18:36 +00003248 // materializing functions. The ResumeBit points to the
3249 // start of the last function block recorded in the
3250 // DeferredFunctionInfo map. Skip it.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003251 if (Stream.SkipBlock())
3252 return error("Invalid record");
3253 continue;
3254 }
3255 }
3256
3257 // Support older bitcode files that did not have the function
Teresa Johnson1493ad92015-10-10 14:18:36 +00003258 // index in the VST, nor a VST forward declaration record, as
3259 // well as anonymous functions that do not have VST entries.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003260 // Build the DeferredFunctionInfo vector on the fly.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003261 if (Error Err = rememberAndSkipFunctionBody())
3262 return Err;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003263
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003264 // Suspend parsing when we reach the function bodies. Subsequent
3265 // materialization calls will resume it when necessary. If the bitcode
3266 // file is old, the symbol table will be at the end instead and will not
3267 // have been seen yet. In this case, just finish the parse now.
3268 if (SeenValueSymbolTable) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003269 NextUnreadBit = Stream.GetCurrentBitNo();
Mehdi Aminia71002e2016-08-14 00:01:27 +00003270 // After the VST has been parsed, we need to make sure intrinsic name
3271 // are auto-upgraded.
3272 return globalCleanup();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003273 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003274 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003275 case bitc::USELIST_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003276 if (Error Err = parseUseLists())
3277 return Err;
Chad Rosierca2567b2011-12-07 21:44:12 +00003278 break;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003279 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003280 if (Error Err = parseOperandBundleTags())
3281 return Err;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003282 break;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00003283 case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
3284 if (Error Err = parseSyncScopeNames())
3285 return Err;
3286 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003287 }
3288 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003289
Chris Lattner27d38752013-01-20 02:13:19 +00003290 case BitstreamEntry::Record:
3291 // The interesting case.
3292 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003293 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003294
Chris Lattner1314b992007-04-22 06:23:29 +00003295 // Read a record.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003296 auto BitCode = Stream.readRecord(Entry.ID, Record);
3297 switch (BitCode) {
Chris Lattner1314b992007-04-22 06:23:29 +00003298 default: break; // Default behavior, ignore unknown content.
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003299 case bitc::MODULE_CODE_VERSION: {
3300 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
3301 if (!VersionOrErr)
3302 return VersionOrErr.takeError();
3303 UseRelativeIDs = *VersionOrErr >= 1;
Chris Lattner1314b992007-04-22 06:23:29 +00003304 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00003305 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003306 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003307 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003308 if (convertToString(Record, 0, S))
3309 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003310 TheModule->setTargetTriple(S);
3311 break;
3312 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003313 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003314 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003315 if (convertToString(Record, 0, S))
3316 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003317 TheModule->setDataLayout(S);
3318 break;
3319 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003320 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003321 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003322 if (convertToString(Record, 0, S))
3323 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003324 TheModule->setModuleInlineAsm(S);
3325 break;
3326 }
Bill Wendling706d3d62012-11-28 08:41:48 +00003327 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3328 // FIXME: Remove in 4.0.
3329 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003330 if (convertToString(Record, 0, S))
3331 return error("Invalid record");
Bill Wendling706d3d62012-11-28 08:41:48 +00003332 // Ignore value.
3333 break;
3334 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003335 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003336 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003337 if (convertToString(Record, 0, S))
3338 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003339 SectionTable.push_back(S);
3340 break;
3341 }
Gordon Henriksend930f912008-08-17 18:44:35 +00003342 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00003343 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003344 if (convertToString(Record, 0, S))
3345 return error("Invalid record");
Gordon Henriksend930f912008-08-17 18:44:35 +00003346 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00003347 break;
3348 }
Eugene Zelenko975293f2017-09-07 23:28:24 +00003349 case bitc::MODULE_CODE_COMDAT:
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003350 if (Error Err = parseComdatRecord(Record))
3351 return Err;
David Majnemerdad0a642014-06-27 18:19:56 +00003352 break;
Eugene Zelenko975293f2017-09-07 23:28:24 +00003353 case bitc::MODULE_CODE_GLOBALVAR:
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003354 if (Error Err = parseGlobalVarRecord(Record))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003355 return Err;
Chris Lattner1314b992007-04-22 06:23:29 +00003356 break;
Eugene Zelenko975293f2017-09-07 23:28:24 +00003357 case bitc::MODULE_CODE_FUNCTION:
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003358 if (Error Err = parseFunctionRecord(Record))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003359 return Err;
Chris Lattner1314b992007-04-22 06:23:29 +00003360 break;
Dmitry Polukhina1feff72016-04-07 12:32:19 +00003361 case bitc::MODULE_CODE_IFUNC:
David Blaikie6a51dbd2015-09-17 22:18:59 +00003362 case bitc::MODULE_CODE_ALIAS:
Eugene Zelenko975293f2017-09-07 23:28:24 +00003363 case bitc::MODULE_CODE_ALIAS_OLD:
Peter Collingbournece24a2a2017-04-12 20:02:09 +00003364 if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
3365 return Err;
Chris Lattner44c17072007-04-26 02:46:40 +00003366 break;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003367 /// MODULE_CODE_VSTOFFSET: [offset]
3368 case bitc::MODULE_CODE_VSTOFFSET:
3369 if (Record.size() < 1)
3370 return error("Invalid record");
Peter Collingbournebfcf9802016-11-29 02:27:04 +00003371 // Note that we subtract 1 here because the offset is relative to one word
3372 // before the start of the identification or module block, which was
3373 // historically always the start of the regular bitcode header.
3374 VSTOffset = Record[0] - 1;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003375 break;
Teresa Johnsone1164de2016-02-10 21:55:02 +00003376 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3377 case bitc::MODULE_CODE_SOURCE_FILENAME:
3378 SmallString<128> ValueName;
3379 if (convertToString(Record, 0, ValueName))
3380 return error("Invalid record");
3381 TheModule->setSourceFileName(ValueName);
3382 break;
Chris Lattner831d4202007-04-26 03:27:58 +00003383 }
Chris Lattner1314b992007-04-22 06:23:29 +00003384 Record.clear();
3385 }
Chris Lattner1314b992007-04-22 06:23:29 +00003386}
3387
Teresa Johnsona61f5e32016-12-16 21:25:01 +00003388Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
3389 bool IsImporting) {
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003390 TheModule = M;
Teresa Johnsona61f5e32016-12-16 21:25:01 +00003391 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
Mehdi Aminief27db82016-12-12 19:34:26 +00003392 [&](unsigned ID) { return getTypeByID(ID); });
Peter Collingbourne7a748032016-11-16 21:44:45 +00003393 return parseModule(0, ShouldLazyLoadMetadata);
Chris Lattner1314b992007-04-22 06:23:29 +00003394}
Chris Lattner6694f602007-04-29 07:54:31 +00003395
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003396Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003397 if (!isa<PointerType>(PtrType))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003398 return error("Load/Store operand is not a pointer type");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003399 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3400
3401 if (ValType && ValType != ElemType)
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003402 return error("Explicit load/store type does not match pointee "
3403 "type of pointer operand");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003404 if (!PointerType::isLoadableOrStorableType(ElemType))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003405 return error("Cannot load/store from pointer");
3406 return Error::success();
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003407}
3408
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003409/// Lazily parse the specified function body block.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003410Error BitcodeReader::parseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00003411 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003412 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003413
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00003414 // Unexpected unresolved metadata when parsing function.
Mehdi Aminief27db82016-12-12 19:34:26 +00003415 if (MDLoader->hasFwdRefs())
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00003416 return error("Invalid function metadata: incoming forward references");
3417
Nick Lewyckya72e1af2010-02-25 08:30:17 +00003418 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00003419 unsigned ModuleValueListSize = ValueList.size();
Mehdi Aminief27db82016-12-12 19:34:26 +00003420 unsigned ModuleMDLoaderSize = MDLoader->size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003421
Chris Lattner85b7b402007-05-01 05:52:21 +00003422 // Add all the function arguments to the value table.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00003423 for (Argument &I : F->args())
3424 ValueList.push_back(&I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003425
Chris Lattner83930552007-05-01 07:01:57 +00003426 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00003427 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00003428 unsigned CurBBNo = 0;
3429
Chris Lattner07d09ed2010-04-03 02:17:50 +00003430 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003431 auto getLastInstruction = [&]() -> Instruction * {
3432 if (CurBB && !CurBB->empty())
3433 return &CurBB->back();
3434 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3435 !FunctionBBs[CurBBNo - 1]->empty())
3436 return &FunctionBBs[CurBBNo - 1]->back();
3437 return nullptr;
3438 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003439
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003440 std::vector<OperandBundleDef> OperandBundles;
3441
Chris Lattner85b7b402007-05-01 05:52:21 +00003442 // Read all the records.
3443 SmallVector<uint64_t, 64> Record;
Eugene Zelenko1804a772016-08-25 00:45:04 +00003444
3445 while (true) {
Chris Lattner27d38752013-01-20 02:13:19 +00003446 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003447
Chris Lattner27d38752013-01-20 02:13:19 +00003448 switch (Entry.Kind) {
3449 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003450 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003451 case BitstreamEntry::EndBlock:
3452 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00003453
Chris Lattner27d38752013-01-20 02:13:19 +00003454 case BitstreamEntry::SubBlock:
3455 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00003456 default: // Skip unknown content.
3457 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003458 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00003459 break;
3460 case bitc::CONSTANTS_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003461 if (Error Err = parseConstants())
3462 return Err;
Chris Lattner83930552007-05-01 07:01:57 +00003463 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00003464 break;
3465 case bitc::VALUE_SYMTAB_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003466 if (Error Err = parseValueSymbolTable())
3467 return Err;
Chris Lattner85b7b402007-05-01 05:52:21 +00003468 break;
Devang Patelaf206b82009-09-18 19:26:43 +00003469 case bitc::METADATA_ATTACHMENT_ID:
Mehdi Aminief27db82016-12-12 19:34:26 +00003470 if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003471 return Err;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003472 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00003473 case bitc::METADATA_BLOCK_ID:
Mehdi Aminief27db82016-12-12 19:34:26 +00003474 assert(DeferredMetadataInfo.empty() &&
3475 "Must read all module-level metadata before function-level");
3476 if (Error Err = MDLoader->parseFunctionMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003477 return Err;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00003478 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003479 case bitc::USELIST_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00003480 if (Error Err = parseUseLists())
3481 return Err;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003482 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00003483 }
3484 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003485
Chris Lattner27d38752013-01-20 02:13:19 +00003486 case BitstreamEntry::Record:
3487 // The interesting case.
3488 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00003489 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003490
Chris Lattner85b7b402007-05-01 05:52:21 +00003491 // Read a record.
3492 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00003493 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00003494 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00003495 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00003496 default: // Default behavior: reject
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003497 return error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003498 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00003499 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003500 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00003501 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00003502 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003503
3504 // See if anything took the address of blocks in this function.
3505 auto BBFRI = BasicBlockFwdRefs.find(F);
3506 if (BBFRI == BasicBlockFwdRefs.end()) {
3507 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3508 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3509 } else {
3510 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003511 // Check for invalid basic block references.
3512 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003513 return error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003514 assert(!BBRefs.empty() && "Unexpected empty array");
3515 assert(!BBRefs.front() && "Invalid reference to entry block");
3516 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3517 ++I)
3518 if (I < RE && BBRefs[I]) {
3519 BBRefs[I]->insertInto(F);
3520 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003521 } else {
3522 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3523 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003524
3525 // Erase from the table.
3526 BasicBlockFwdRefs.erase(BBFRI);
3527 }
3528
Chris Lattner83930552007-05-01 07:01:57 +00003529 CurBB = FunctionBBs[0];
3530 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003531 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003532
Chris Lattner07d09ed2010-04-03 02:17:50 +00003533 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3534 // This record indicates that the last instruction is at the same
3535 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003536 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003537
Craig Topper2617dcc2014-04-15 06:32:26 +00003538 if (!I)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003539 return error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00003540 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003541 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003542 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003543
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00003544 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003545 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00003546 if (!I || Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003547 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003548
Chris Lattner07d09ed2010-04-03 02:17:50 +00003549 unsigned Line = Record[0], Col = Record[1];
3550 unsigned ScopeID = Record[2], IAID = Record[3];
Calixte Denizeteb7f6022018-09-20 08:53:06 +00003551 bool isImplicitCode = Record.size() == 5 && Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003552
Craig Topper2617dcc2014-04-15 06:32:26 +00003553 MDNode *Scope = nullptr, *IA = nullptr;
Justin Bognerae341c62016-03-17 20:12:06 +00003554 if (ScopeID) {
Teresa Johnsonf61a5632018-11-14 20:58:04 +00003555 Scope = dyn_cast_or_null<MDNode>(
3556 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
Justin Bognerae341c62016-03-17 20:12:06 +00003557 if (!Scope)
3558 return error("Invalid record");
3559 }
3560 if (IAID) {
Teresa Johnsonf61a5632018-11-14 20:58:04 +00003561 IA = dyn_cast_or_null<MDNode>(
3562 MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
Justin Bognerae341c62016-03-17 20:12:06 +00003563 if (!IA)
3564 return error("Invalid record");
3565 }
Calixte Denizeteb7f6022018-09-20 08:53:06 +00003566 LastLoc = DebugLoc::get(Line, Col, Scope, IA, isImplicitCode);
Chris Lattner07d09ed2010-04-03 02:17:50 +00003567 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003568 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003569 continue;
3570 }
Cameron McInallycbde0d92018-11-13 18:15:47 +00003571 case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode]
3572 unsigned OpNum = 0;
3573 Value *LHS;
3574 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3575 OpNum+1 > Record.size())
3576 return error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00003577
Cameron McInallycbde0d92018-11-13 18:15:47 +00003578 int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
3579 if (Opc == -1)
3580 return error("Invalid record");
3581 I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
3582 InstructionList.push_back(I);
3583 if (OpNum < Record.size()) {
3584 if (isa<FPMathOperator>(I)) {
3585 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3586 if (FMF.any())
3587 I->setFastMathFlags(FMF);
3588 }
3589 }
3590 break;
3591 }
Chris Lattnere9759c22007-05-06 00:21:25 +00003592 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3593 unsigned OpNum = 0;
3594 Value *LHS, *RHS;
3595 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003596 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00003597 OpNum+1 > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003598 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003599
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003600 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00003601 if (Opc == -1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003602 return error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003603 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00003604 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00003605 if (OpNum < Record.size()) {
3606 if (Opc == Instruction::Add ||
3607 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003608 Opc == Instruction::Mul ||
3609 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00003610 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00003611 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00003612 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00003613 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00003614 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003615 Opc == Instruction::UDiv ||
3616 Opc == Instruction::LShr ||
3617 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00003618 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00003619 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003620 } else if (isa<FPMathOperator>(I)) {
James Molloy88eb5352015-07-10 12:52:00 +00003621 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003622 if (FMF.any())
3623 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00003624 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003625
Dan Gohman1b849082009-09-07 23:54:19 +00003626 }
Chris Lattner85b7b402007-05-01 05:52:21 +00003627 break;
3628 }
Chris Lattnere9759c22007-05-06 00:21:25 +00003629 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3630 unsigned OpNum = 0;
3631 Value *Op;
3632 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3633 OpNum+2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003634 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003635
Chris Lattner229907c2011-07-18 04:54:35 +00003636 Type *ResTy = getTypeByID(Record[OpNum]);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003637 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003638 if (Opc == -1 || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003639 return error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00003640 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003641 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3642 if (Temp) {
3643 InstructionList.push_back(Temp);
3644 CurBB->getInstList().push_back(Temp);
3645 }
3646 } else {
Filipe Cabecinhasb70fd872015-10-06 12:37:54 +00003647 auto CastOp = (Instruction::CastOps)Opc;
3648 if (!CastInst::castIsValid(CastOp, Op, ResTy))
3649 return error("Invalid cast");
3650 I = CastInst::Create(CastOp, Op, ResTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003651 }
Devang Patelaf206b82009-09-18 19:26:43 +00003652 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00003653 break;
3654 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00003655 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3656 case bitc::FUNC_CODE_INST_GEP_OLD:
3657 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003658 unsigned OpNum = 0;
David Blaikieb5b5efd2015-02-25 01:08:52 +00003659
3660 Type *Ty;
3661 bool InBounds;
3662
3663 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3664 InBounds = Record[OpNum++];
3665 Ty = getTypeByID(Record[OpNum++]);
3666 } else {
3667 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3668 Ty = nullptr;
3669 }
3670
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003671 Value *BasePtr;
3672 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003673 return error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00003674
David Blaikie60310f22015-05-08 00:42:26 +00003675 if (!Ty)
Peter Collingbourne9ef5a8c2016-11-13 06:59:28 +00003676 Ty = cast<PointerType>(BasePtr->getType()->getScalarType())
David Blaikie60310f22015-05-08 00:42:26 +00003677 ->getElementType();
3678 else if (Ty !=
Peter Collingbourne9ef5a8c2016-11-13 06:59:28 +00003679 cast<PointerType>(BasePtr->getType()->getScalarType())
David Blaikie60310f22015-05-08 00:42:26 +00003680 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003681 return error(
David Blaikie675e8cb2015-03-16 21:35:48 +00003682 "Explicit gep type does not match pointee type of pointer operand");
3683
Chris Lattner5285b5e2007-05-02 05:46:45 +00003684 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003685 while (OpNum != Record.size()) {
3686 Value *Op;
3687 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003688 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003689 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003690 }
3691
David Blaikie096b1da2015-03-14 19:53:33 +00003692 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
David Blaikie675e8cb2015-03-16 21:35:48 +00003693
Devang Patelaf206b82009-09-18 19:26:43 +00003694 InstructionList.push_back(I);
David Blaikieb5b5efd2015-02-25 01:08:52 +00003695 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00003696 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003697 break;
3698 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003699
Dan Gohman1ecaf452008-05-31 00:58:22 +00003700 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3701 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00003702 unsigned OpNum = 0;
3703 Value *Agg;
3704 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003705 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003706
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003707 unsigned RecSize = Record.size();
3708 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003709 return error("EXTRACTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003710
Dan Gohman1ecaf452008-05-31 00:58:22 +00003711 SmallVector<unsigned, 4> EXTRACTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003712 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003713 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003714 bool IsArray = CurTy->isArrayTy();
3715 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003716 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003717
3718 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003719 return error("EXTRACTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003720 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003721 return error("Invalid value");
James Y Knight62df5ee2019-01-10 16:07:20 +00003722 if (IsStruct && Index >= CurTy->getStructNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003723 return error("EXTRACTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003724 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003725 return error("EXTRACTVAL: Invalid array index");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003726 EXTRACTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003727
3728 if (IsStruct)
James Y Knight62df5ee2019-01-10 16:07:20 +00003729 CurTy = CurTy->getStructElementType(Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003730 else
James Y Knight62df5ee2019-01-10 16:07:20 +00003731 CurTy = CurTy->getArrayElementType();
Dan Gohman30499842008-05-23 01:55:30 +00003732 }
3733
Jay Foad57aa6362011-07-13 10:26:04 +00003734 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003735 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00003736 break;
3737 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003738
Dan Gohman1ecaf452008-05-31 00:58:22 +00003739 case bitc::FUNC_CODE_INST_INSERTVAL: {
3740 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00003741 unsigned OpNum = 0;
3742 Value *Agg;
3743 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003744 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003745 Value *Val;
3746 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003747 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003748
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003749 unsigned RecSize = Record.size();
3750 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003751 return error("INSERTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003752
Dan Gohman1ecaf452008-05-31 00:58:22 +00003753 SmallVector<unsigned, 4> INSERTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003754 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003755 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003756 bool IsArray = CurTy->isArrayTy();
3757 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003758 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003759
3760 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003761 return error("INSERTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003762 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003763 return error("Invalid value");
James Y Knight62df5ee2019-01-10 16:07:20 +00003764 if (IsStruct && Index >= CurTy->getStructNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003765 return error("INSERTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003766 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003767 return error("INSERTVAL: Invalid array index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003768
Dan Gohman1ecaf452008-05-31 00:58:22 +00003769 INSERTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003770 if (IsStruct)
James Y Knight62df5ee2019-01-10 16:07:20 +00003771 CurTy = CurTy->getStructElementType(Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003772 else
James Y Knight62df5ee2019-01-10 16:07:20 +00003773 CurTy = CurTy->getArrayElementType();
Dan Gohman30499842008-05-23 01:55:30 +00003774 }
3775
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00003776 if (CurTy != Val->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003777 return error("Inserted value type doesn't match aggregate type");
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00003778
Jay Foad57aa6362011-07-13 10:26:04 +00003779 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003780 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00003781 break;
3782 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003783
Chris Lattnere9759c22007-05-06 00:21:25 +00003784 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00003785 // obsolete form of select
3786 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00003787 unsigned OpNum = 0;
3788 Value *TrueVal, *FalseVal, *Cond;
3789 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003790 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3791 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003792 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003793
Dan Gohmanc5d28922008-09-16 01:01:33 +00003794 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00003795 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00003796 break;
3797 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003798
Dan Gohmanc5d28922008-09-16 01:01:33 +00003799 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3800 // new form of select
3801 // handles select i1 or select [N x i1]
3802 unsigned OpNum = 0;
3803 Value *TrueVal, *FalseVal, *Cond;
3804 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003805 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00003806 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003807 return error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00003808
3809 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00003810 if (VectorType* vector_type =
3811 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00003812 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003813 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003814 return error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00003815 } else {
3816 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003817 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003818 return error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003819 }
3820
Gabor Greife9ecc682008-04-06 20:25:17 +00003821 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00003822 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003823 break;
3824 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003825
Chris Lattner1fc27f02007-05-02 05:16:49 +00003826 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00003827 unsigned OpNum = 0;
3828 Value *Vec, *Idx;
3829 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003830 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003831 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003832 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003833 return error("Invalid type for value");
Eric Christopherc9742252009-07-25 02:28:41 +00003834 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00003835 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003836 break;
3837 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003838
Chris Lattner1fc27f02007-05-02 05:16:49 +00003839 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00003840 unsigned OpNum = 0;
3841 Value *Vec, *Elt, *Idx;
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003842 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003843 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003844 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003845 return error("Invalid type for value");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003846 if (popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00003847 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003848 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003849 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00003850 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00003851 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003852 break;
3853 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003854
Chris Lattnere9759c22007-05-06 00:21:25 +00003855 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3856 unsigned OpNum = 0;
3857 Value *Vec1, *Vec2, *Mask;
3858 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003859 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003860 return error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00003861
Mon P Wang25f01062008-11-10 04:46:22 +00003862 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003863 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003864 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003865 return error("Invalid type for value");
Chris Lattner1fc27f02007-05-02 05:16:49 +00003866 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00003867 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003868 break;
3869 }
Mon P Wang25f01062008-11-10 04:46:22 +00003870
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003871 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3872 // Old form of ICmp/FCmp returning bool
3873 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3874 // both legal on vectors but had different behaviour.
3875 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3876 // FCmp/ICmp returning bool or vector of bool
3877
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003878 unsigned OpNum = 0;
3879 Value *LHS, *RHS;
3880 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
James Molloy88eb5352015-07-10 12:52:00 +00003881 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3882 return error("Invalid record");
3883
3884 unsigned PredVal = Record[OpNum];
3885 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3886 FastMathFlags FMF;
3887 if (IsFP && Record.size() > OpNum+1)
3888 FMF = getDecodedFastMathFlags(Record[++OpNum]);
3889
3890 if (OpNum+1 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003891 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003892
Duncan Sands9dff9be2010-02-15 16:12:20 +00003893 if (LHS->getType()->isFPOrFPVectorTy())
James Molloy88eb5352015-07-10 12:52:00 +00003894 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003895 else
James Molloy88eb5352015-07-10 12:52:00 +00003896 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3897
3898 if (FMF.any())
3899 I->setFastMathFlags(FMF);
Devang Patelaf206b82009-09-18 19:26:43 +00003900 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00003901 break;
3902 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003903
Chris Lattnere53603e2007-05-02 04:27:25 +00003904 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00003905 {
3906 unsigned Size = Record.size();
3907 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00003908 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003909 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00003910 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003911 }
Devang Patelbbfd8742008-02-26 01:29:32 +00003912
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003913 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00003914 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00003915 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003916 return error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00003917 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003918 return error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003919
Chris Lattnerf1c87102011-06-17 18:09:11 +00003920 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003921 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003922 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00003923 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003924 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00003925 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003926 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003927 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003928 if (!TrueDest)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003929 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003930
Devang Patelaf206b82009-09-18 19:26:43 +00003931 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00003932 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003933 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00003934 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003935 else {
3936 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003937 Value *Cond = getValue(Record, 2, NextValueNo,
3938 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00003939 if (!FalseDest || !Cond)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003940 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00003941 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003942 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003943 }
3944 break;
3945 }
David Majnemerb01aa9f2015-08-23 19:22:31 +00003946 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003947 if (Record.size() != 1 && Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00003948 return error("Invalid record");
3949 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003950 Value *CleanupPad =
3951 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003952 if (!CleanupPad)
David Majnemer654e1302015-07-31 17:58:14 +00003953 return error("Invalid record");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003954 BasicBlock *UnwindDest = nullptr;
3955 if (Record.size() == 2) {
David Majnemer654e1302015-07-31 17:58:14 +00003956 UnwindDest = getBasicBlock(Record[Idx++]);
3957 if (!UnwindDest)
3958 return error("Invalid record");
3959 }
3960
David Majnemer8a1c45d2015-12-12 05:38:55 +00003961 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
David Majnemer654e1302015-07-31 17:58:14 +00003962 InstructionList.push_back(I);
3963 break;
3964 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003965 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
3966 if (Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00003967 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00003968 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003969 Value *CatchPad =
3970 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003971 if (!CatchPad)
3972 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00003973 BasicBlock *BB = getBasicBlock(Record[Idx++]);
David Majnemer654e1302015-07-31 17:58:14 +00003974 if (!BB)
3975 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00003976
David Majnemer8a1c45d2015-12-12 05:38:55 +00003977 I = CatchReturnInst::Create(CatchPad, BB);
David Majnemer654e1302015-07-31 17:58:14 +00003978 InstructionList.push_back(I);
3979 break;
3980 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003981 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
3982 // We must have, at minimum, the outer scope and the number of arguments.
3983 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00003984 return error("Invalid record");
3985
David Majnemer654e1302015-07-31 17:58:14 +00003986 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00003987
3988 Value *ParentPad =
3989 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3990
3991 unsigned NumHandlers = Record[Idx++];
3992
3993 SmallVector<BasicBlock *, 2> Handlers;
3994 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
3995 BasicBlock *BB = getBasicBlock(Record[Idx++]);
3996 if (!BB)
David Majnemer654e1302015-07-31 17:58:14 +00003997 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00003998 Handlers.push_back(BB);
3999 }
4000
4001 BasicBlock *UnwindDest = nullptr;
4002 if (Idx + 1 == Record.size()) {
David Majnemer654e1302015-07-31 17:58:14 +00004003 UnwindDest = getBasicBlock(Record[Idx++]);
4004 if (!UnwindDest)
4005 return error("Invalid record");
4006 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004007
4008 if (Record.size() != Idx)
4009 return error("Invalid record");
4010
4011 auto *CatchSwitch =
4012 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4013 for (BasicBlock *Handler : Handlers)
4014 CatchSwitch->addHandler(Handler);
4015 I = CatchSwitch;
4016 InstructionList.push_back(I);
4017 break;
4018 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004019 case bitc::FUNC_CODE_INST_CATCHPAD:
4020 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4021 // We must have, at minimum, the outer scope and the number of arguments.
4022 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00004023 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004024
David Majnemer654e1302015-07-31 17:58:14 +00004025 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004026
4027 Value *ParentPad =
4028 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4029
David Majnemer654e1302015-07-31 17:58:14 +00004030 unsigned NumArgOperands = Record[Idx++];
David Majnemer8a1c45d2015-12-12 05:38:55 +00004031
David Majnemer654e1302015-07-31 17:58:14 +00004032 SmallVector<Value *, 2> Args;
4033 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4034 Value *Val;
4035 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4036 return error("Invalid record");
4037 Args.push_back(Val);
4038 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004039
David Majnemer654e1302015-07-31 17:58:14 +00004040 if (Record.size() != Idx)
4041 return error("Invalid record");
4042
David Majnemer8a1c45d2015-12-12 05:38:55 +00004043 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4044 I = CleanupPadInst::Create(ParentPad, Args);
4045 else
4046 I = CatchPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00004047 InstructionList.push_back(I);
4048 break;
4049 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00004050 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004051 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004052 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00004053 // "New" SwitchInst format with case ranges. The changes to write this
4054 // format were reverted but we still recognize bitcode that uses it.
4055 // Hopefully someday we will have support for case ranges and can use
4056 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004057
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004058 Type *OpTy = getTypeByID(Record[1]);
4059 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4060
Jan Wen Voungafaced02012-10-11 20:20:40 +00004061 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004062 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004063 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004064 return error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004065
4066 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004067
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004068 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4069 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004070
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004071 unsigned CurIdx = 5;
4072 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00004073 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004074 unsigned NumItems = Record[CurIdx++];
4075 for (unsigned ci = 0; ci != NumItems; ++ci) {
4076 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004077
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004078 APInt Low;
4079 unsigned ActiveWords = 1;
4080 if (ValueBitWidth > 64)
4081 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004082 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
Benjamin Kramer9704ed02012-05-28 14:10:31 +00004083 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004084 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00004085
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004086 if (!isSingleNumber) {
4087 ActiveWords = 1;
4088 if (ValueBitWidth > 64)
4089 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004090 APInt High = readWideAPInt(
4091 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004092 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00004093
4094 // FIXME: It is not clear whether values in the range should be
4095 // compared as signed or unsigned values. The partially
4096 // implemented changes that used this format in the past used
4097 // unsigned comparisons.
4098 for ( ; Low.ule(High); ++Low)
4099 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004100 } else
Bob Wilsone4077362013-09-09 19:14:35 +00004101 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004102 }
4103 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00004104 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4105 cve = CaseVals.end(); cvi != cve; ++cvi)
4106 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004107 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004108 I = SI;
4109 break;
4110 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004111
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004112 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004113
Chris Lattner5285b5e2007-05-02 05:46:45 +00004114 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004115 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004116 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004117 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004118 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004119 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004120 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004121 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00004122 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00004123 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004124 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004125 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00004126 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4127 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004128 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00004129 delete SI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004130 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004131 }
4132 SI->addCase(CaseVal, DestBB);
4133 }
4134 I = SI;
4135 break;
4136 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004137 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00004138 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004139 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004140 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004141 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00004142 if (!OpTy || !Address)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004143 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004144 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004145 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00004146 InstructionList.push_back(IBI);
4147 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4148 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4149 IBI->addDestination(DestBB);
4150 } else {
4151 delete IBI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004152 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004153 }
4154 }
4155 I = IBI;
4156 break;
4157 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004158
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004159 case bitc::FUNC_CODE_INST_INVOKE: {
4160 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00004161 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004162 return error("Invalid record");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004163 unsigned OpNum = 0;
Reid Klecknerb5180542017-03-21 16:57:19 +00004164 AttributeList PAL = getAttributes(Record[OpNum++]);
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004165 unsigned CCInfo = Record[OpNum++];
4166 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4167 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004168
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004169 FunctionType *FTy = nullptr;
4170 if (CCInfo >> 13 & 1 &&
4171 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004172 return error("Explicit invoke type is not a function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004173
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004174 Value *Callee;
4175 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004176 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004177
Chris Lattner229907c2011-07-18 04:54:35 +00004178 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004179 if (!CalleeTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004180 return error("Callee is not a pointer");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004181 if (!FTy) {
4182 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4183 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004184 return error("Callee is not of pointer to function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004185 } else if (CalleeTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004186 return error("Explicit invoke type does not match pointee type of "
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004187 "callee operand");
4188 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004189 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004190
Chris Lattner5285b5e2007-05-02 05:46:45 +00004191 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004192 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004193 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4194 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004195 if (!Ops.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004196 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004197 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004198
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004199 if (!FTy->isVarArg()) {
4200 if (Record.size() != OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004201 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004202 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004203 // Read type/value pairs for varargs params.
4204 while (OpNum != Record.size()) {
4205 Value *Op;
4206 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004207 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004208 Ops.push_back(Op);
4209 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004210 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004211
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004212 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4213 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00004214 InstructionList.push_back(I);
Vedant Kumarad6d6e72015-10-27 21:17:06 +00004215 cast<InvokeInst>(I)->setCallingConv(
4216 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00004217 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004218 break;
4219 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00004220 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4221 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004222 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004223 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004224 return error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00004225 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00004226 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004227 break;
4228 }
Chris Lattnere53603e2007-05-02 04:27:25 +00004229 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00004230 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00004231 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004232 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00004233 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00004234 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004235 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004236 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004237 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004238 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004239
Jay Foad52131342011-03-30 11:28:46 +00004240 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00004241 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004242
Chris Lattnere14cb882007-05-04 19:11:41 +00004243 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004244 Value *V;
4245 // With the new function encoding, it is possible that operands have
4246 // negative IDs (for forward references). Use a signed VBR
4247 // representation to keep the encoding small.
4248 if (UseRelativeIDs)
4249 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4250 else
4251 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00004252 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004253 if (!V || !BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004254 return error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00004255 PN->addIncoming(V, BB);
4256 }
4257 I = PN;
4258 break;
4259 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004260
David Majnemer7fddecc2015-06-17 20:52:32 +00004261 case bitc::FUNC_CODE_INST_LANDINGPAD:
4262 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
Bill Wendlingfae14752011-08-12 20:24:12 +00004263 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4264 unsigned Idx = 0;
David Majnemer7fddecc2015-06-17 20:52:32 +00004265 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4266 if (Record.size() < 3)
4267 return error("Invalid record");
4268 } else {
4269 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4270 if (Record.size() < 4)
4271 return error("Invalid record");
4272 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004273 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004274 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004275 return error("Invalid record");
David Majnemer7fddecc2015-06-17 20:52:32 +00004276 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4277 Value *PersFn = nullptr;
4278 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4279 return error("Invalid record");
4280
4281 if (!F->hasPersonalityFn())
4282 F->setPersonalityFn(cast<Constant>(PersFn));
4283 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4284 return error("Personality function mismatch");
4285 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004286
4287 bool IsCleanup = !!Record[Idx++];
4288 unsigned NumClauses = Record[Idx++];
David Majnemer7fddecc2015-06-17 20:52:32 +00004289 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
Bill Wendlingfae14752011-08-12 20:24:12 +00004290 LP->setCleanup(IsCleanup);
4291 for (unsigned J = 0; J != NumClauses; ++J) {
4292 LandingPadInst::ClauseType CT =
4293 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4294 Value *Val;
4295
4296 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4297 delete LP;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004298 return error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00004299 }
4300
4301 assert((CT != LandingPadInst::Catch ||
4302 !isa<ArrayType>(Val->getType())) &&
4303 "Catch clause has a invalid type!");
4304 assert((CT != LandingPadInst::Filter ||
4305 isa<ArrayType>(Val->getType())) &&
4306 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004307 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00004308 }
4309
4310 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00004311 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00004312 break;
4313 }
4314
Chris Lattnerf1c87102011-06-17 18:09:11 +00004315 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4316 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004317 return error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00004318 uint64_t AlignRecord = Record[3];
4319 const uint64_t InAllocaMask = uint64_t(1) << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00004320 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00004321 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4322 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
4323 SwiftErrorMask;
JF Bastien30bf96b2015-02-22 19:32:03 +00004324 bool InAlloca = AlignRecord & InAllocaMask;
Manman Ren9bfd0d02016-04-01 21:41:15 +00004325 bool SwiftError = AlignRecord & SwiftErrorMask;
David Blaikiebdb49102015-04-28 16:51:01 +00004326 Type *Ty = getTypeByID(Record[0]);
4327 if ((AlignRecord & ExplicitTypeMask) == 0) {
4328 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4329 if (!PTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004330 return error("Old-style alloca with a non-pointer type");
David Blaikiebdb49102015-04-28 16:51:01 +00004331 Ty = PTy->getElementType();
4332 }
4333 Type *OpTy = getTypeByID(Record[1]);
4334 Value *Size = getFnValueByID(Record[2], OpTy);
JF Bastien30bf96b2015-02-22 19:32:03 +00004335 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004336 if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4337 return Err;
JF Bastien30bf96b2015-02-22 19:32:03 +00004338 }
Rafael Espindola48da4f42013-11-04 16:16:24 +00004339 if (!Ty || !Size)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004340 return error("Invalid record");
Matt Arsenault3c1fc762017-04-10 22:27:50 +00004341
4342 // FIXME: Make this an optional field.
4343 const DataLayout &DL = TheModule->getDataLayout();
4344 unsigned AS = DL.getAllocaAddrSpace();
4345
4346 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Align);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00004347 AI->setUsedWithInAlloca(InAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00004348 AI->setSwiftError(SwiftError);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00004349 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00004350 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00004351 break;
4352 }
Chris Lattner9f600c52007-05-03 22:04:19 +00004353 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004354 unsigned OpNum = 0;
4355 Value *Op;
4356 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004357 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004358 return error("Invalid record");
David Blaikie85035652015-02-25 01:07:20 +00004359
4360 Type *Ty = nullptr;
4361 if (OpNum + 3 == Record.size())
4362 Ty = getTypeByID(Record[OpNum++]);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004363 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4364 return Err;
David Blaikieb7a029872015-04-17 19:56:21 +00004365 if (!Ty)
4366 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004367
JF Bastien30bf96b2015-02-22 19:32:03 +00004368 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004369 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4370 return Err;
David Blaikieb7a029872015-04-17 19:56:21 +00004371 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
David Blaikie85035652015-02-25 01:07:20 +00004372
Devang Patelaf206b82009-09-18 19:26:43 +00004373 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00004374 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00004375 }
Eli Friedman59b66882011-08-09 23:02:53 +00004376 case bitc::FUNC_CODE_INST_LOADATOMIC: {
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004377 // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
Eli Friedman59b66882011-08-09 23:02:53 +00004378 unsigned OpNum = 0;
4379 Value *Op;
4380 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004381 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004382 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004383
David Blaikie85035652015-02-25 01:07:20 +00004384 Type *Ty = nullptr;
4385 if (OpNum + 5 == Record.size())
4386 Ty = getTypeByID(Record[OpNum++]);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004387 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4388 return Err;
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004389 if (!Ty)
4390 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004391
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004392 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00004393 if (Ordering == AtomicOrdering::NotAtomic ||
4394 Ordering == AtomicOrdering::Release ||
4395 Ordering == AtomicOrdering::AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004396 return error("Invalid record");
JF Bastien800f87a2016-04-06 21:19:33 +00004397 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004398 return error("Invalid record");
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004399 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00004400
JF Bastien30bf96b2015-02-22 19:32:03 +00004401 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004402 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4403 return Err;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004404 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SSID);
David Blaikie85035652015-02-25 01:07:20 +00004405
Eli Friedman59b66882011-08-09 23:02:53 +00004406 InstructionList.push_back(I);
4407 break;
4408 }
David Blaikie612ddbf2015-04-22 04:14:42 +00004409 case bitc::FUNC_CODE_INST_STORE:
4410 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004411 unsigned OpNum = 0;
4412 Value *Val, *Ptr;
4413 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie612ddbf2015-04-22 04:14:42 +00004414 (BitCode == bitc::FUNC_CODE_INST_STORE
4415 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4416 : popValue(Record, OpNum, NextValueNo,
4417 cast<PointerType>(Ptr->getType())->getElementType(),
4418 Val)) ||
4419 OpNum + 2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004420 return error("Invalid record");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004421
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004422 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4423 return Err;
JF Bastien30bf96b2015-02-22 19:32:03 +00004424 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004425 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4426 return Err;
JF Bastien30bf96b2015-02-22 19:32:03 +00004427 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
Devang Patelaf206b82009-09-18 19:26:43 +00004428 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004429 break;
4430 }
David Blaikie50a06152015-04-22 04:14:46 +00004431 case bitc::FUNC_CODE_INST_STOREATOMIC:
4432 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004433 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
Eli Friedman59b66882011-08-09 23:02:53 +00004434 unsigned OpNum = 0;
4435 Value *Val, *Ptr;
4436 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Filipe Cabecinhas036e73c2016-06-05 18:43:33 +00004437 !isa<PointerType>(Ptr->getType()) ||
David Blaikie50a06152015-04-22 04:14:46 +00004438 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4439 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4440 : popValue(Record, OpNum, NextValueNo,
4441 cast<PointerType>(Ptr->getType())->getElementType(),
4442 Val)) ||
4443 OpNum + 4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004444 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004445
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004446 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4447 return Err;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004448 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00004449 if (Ordering == AtomicOrdering::NotAtomic ||
4450 Ordering == AtomicOrdering::Acquire ||
4451 Ordering == AtomicOrdering::AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004452 return error("Invalid record");
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004453 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
JF Bastien800f87a2016-04-06 21:19:33 +00004454 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004455 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004456
JF Bastien30bf96b2015-02-22 19:32:03 +00004457 unsigned Align;
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004458 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4459 return Err;
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004460 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SSID);
Eli Friedman59b66882011-08-09 23:02:53 +00004461 InstructionList.push_back(I);
4462 break;
4463 }
David Blaikie2a661cd2015-04-28 04:30:29 +00004464 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004465 case bitc::FUNC_CODE_INST_CMPXCHG: {
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004466 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, ssid,
Tim Northover420a2162014-06-13 14:24:07 +00004467 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004468 unsigned OpNum = 0;
4469 Value *Ptr, *Cmp, *New;
4470 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie2a661cd2015-04-28 04:30:29 +00004471 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4472 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4473 : popValue(Record, OpNum, NextValueNo,
4474 cast<PointerType>(Ptr->getType())->getElementType(),
4475 Cmp)) ||
4476 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4477 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004478 return error("Invalid record");
4479 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
JF Bastien800f87a2016-04-06 21:19:33 +00004480 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
4481 SuccessOrdering == AtomicOrdering::Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004482 return error("Invalid record");
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004483 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
Tim Northovere94a5182014-03-11 10:48:52 +00004484
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004485 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
4486 return Err;
Tim Northovere94a5182014-03-11 10:48:52 +00004487 AtomicOrdering FailureOrdering;
4488 if (Record.size() < 7)
4489 FailureOrdering =
4490 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4491 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004492 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
Tim Northovere94a5182014-03-11 10:48:52 +00004493
4494 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004495 SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004496 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00004497
4498 if (Record.size() < 8) {
4499 // Before weak cmpxchgs existed, the instruction simply returned the
4500 // value loaded from memory, so bitcode files from that era will be
4501 // expecting the first component of a modern cmpxchg.
4502 CurBB->getInstList().push_back(I);
4503 I = ExtractValueInst::Create(I, 0);
4504 } else {
4505 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4506 }
4507
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004508 InstructionList.push_back(I);
4509 break;
4510 }
4511 case bitc::FUNC_CODE_INST_ATOMICRMW: {
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004512 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004513 unsigned OpNum = 0;
4514 Value *Ptr, *Val;
4515 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Filipe Cabecinhas6328f8e2016-06-05 18:43:40 +00004516 !isa<PointerType>(Ptr->getType()) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004517 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004518 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4519 OpNum+4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004520 return error("Invalid record");
4521 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004522 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4523 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004524 return error("Invalid record");
4525 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
JF Bastien800f87a2016-04-06 21:19:33 +00004526 if (Ordering == AtomicOrdering::NotAtomic ||
4527 Ordering == AtomicOrdering::Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004528 return error("Invalid record");
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004529 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4530 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004531 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4532 InstructionList.push_back(I);
4533 break;
4534 }
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004535 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
Eli Friedmanfee02c62011-07-25 23:16:38 +00004536 if (2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004537 return error("Invalid record");
4538 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
JF Bastien800f87a2016-04-06 21:19:33 +00004539 if (Ordering == AtomicOrdering::NotAtomic ||
4540 Ordering == AtomicOrdering::Unordered ||
4541 Ordering == AtomicOrdering::Monotonic)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004542 return error("Invalid record");
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004543 SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
4544 I = new FenceInst(Context, Ordering, SSID);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004545 InstructionList.push_back(I);
4546 break;
4547 }
Chris Lattnerc44070802011-06-17 18:17:37 +00004548 case bitc::FUNC_CODE_INST_CALL: {
Sanjay Patelfa54ace2015-12-14 21:59:03 +00004549 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004550 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004551 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004552
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004553 unsigned OpNum = 0;
Reid Klecknerb5180542017-03-21 16:57:19 +00004554 AttributeList PAL = getAttributes(Record[OpNum++]);
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004555 unsigned CCInfo = Record[OpNum++];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004556
Sanjay Patelfa54ace2015-12-14 21:59:03 +00004557 FastMathFlags FMF;
4558 if ((CCInfo >> bitc::CALL_FMF) & 1) {
4559 FMF = getDecodedFastMathFlags(Record[OpNum++]);
4560 if (!FMF.any())
4561 return error("Fast math flags indicator set for call with no FMF");
4562 }
4563
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004564 FunctionType *FTy = nullptr;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004565 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004566 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004567 return error("Explicit call type is not a function type");
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004568
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004569 Value *Callee;
4570 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004571 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004572
Chris Lattner229907c2011-07-18 04:54:35 +00004573 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004574 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004575 return error("Callee is not a pointer type");
David Blaikie348de692015-04-23 21:36:23 +00004576 if (!FTy) {
4577 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4578 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004579 return error("Callee is not of pointer to function type");
David Blaikie348de692015-04-23 21:36:23 +00004580 } else if (OpTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004581 return error("Explicit call type does not match pointee type of "
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004582 "callee operand");
4583 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004584 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004585
Chris Lattner9f600c52007-05-03 22:04:19 +00004586 SmallVector<Value*, 16> Args;
4587 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004588 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004589 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00004590 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00004591 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00004592 Args.push_back(getValue(Record, OpNum, NextValueNo,
4593 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004594 if (!Args.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004595 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004596 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004597
Chris Lattner9f600c52007-05-03 22:04:19 +00004598 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00004599 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004600 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004601 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004602 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004603 while (OpNum != Record.size()) {
4604 Value *Op;
4605 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004606 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004607 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00004608 }
4609 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004610
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004611 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4612 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00004613 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00004614 cast<CallInst>(I)->setCallingConv(
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004615 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
Reid Kleckner5772b772014-04-24 20:14:34 +00004616 CallInst::TailCallKind TCK = CallInst::TCK_None;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004617 if (CCInfo & 1 << bitc::CALL_TAIL)
Reid Kleckner5772b772014-04-24 20:14:34 +00004618 TCK = CallInst::TCK_Tail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004619 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
Reid Kleckner5772b772014-04-24 20:14:34 +00004620 TCK = CallInst::TCK_MustTail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00004621 if (CCInfo & (1 << bitc::CALL_NOTAIL))
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00004622 TCK = CallInst::TCK_NoTail;
Reid Kleckner5772b772014-04-24 20:14:34 +00004623 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00004624 cast<CallInst>(I)->setAttributes(PAL);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00004625 if (FMF.any()) {
4626 if (!isa<FPMathOperator>(I))
4627 return error("Fast-math-flags specified for call without "
4628 "floating-point scalar or vector return type");
4629 I->setFastMathFlags(FMF);
4630 }
Chris Lattner9f600c52007-05-03 22:04:19 +00004631 break;
4632 }
4633 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4634 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004635 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004636 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004637 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00004638 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00004639 if (!OpTy || !Op || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004640 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004641 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00004642 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00004643 break;
4644 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004645
4646 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
4647 // A call or an invoke can be optionally prefixed with some variable
4648 // number of operand bundle blocks. These blocks are read into
4649 // OperandBundles and consumed at the next call or invoke instruction.
4650
4651 if (Record.size() < 1 || Record[0] >= BundleTags.size())
4652 return error("Invalid record");
4653
Sanjoy Dasf79d3442015-11-18 08:30:07 +00004654 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004655
4656 unsigned OpNum = 1;
4657 while (OpNum != Record.size()) {
4658 Value *Op;
4659 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4660 return error("Invalid record");
4661 Inputs.push_back(Op);
4662 }
4663
Sanjoy Dasf79d3442015-11-18 08:30:07 +00004664 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004665 continue;
4666 }
Chris Lattner83930552007-05-01 07:01:57 +00004667 }
4668
4669 // Add instruction to end of current BB. If there is no current BB, reject
4670 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00004671 if (!CurBB) {
Reid Kleckner96ab8722017-05-18 17:24:10 +00004672 I->deleteValue();
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004673 return error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00004674 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004675 if (!OperandBundles.empty()) {
Reid Kleckner96ab8722017-05-18 17:24:10 +00004676 I->deleteValue();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004677 return error("Operand bundles found with no consumer");
4678 }
Chris Lattner83930552007-05-01 07:01:57 +00004679 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004680
Chris Lattner83930552007-05-01 07:01:57 +00004681 // If this was a terminator instruction, move to the next block.
Chandler Carruth9ae926b2018-08-26 09:51:22 +00004682 if (I->isTerminator()) {
Chris Lattner83930552007-05-01 07:01:57 +00004683 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00004684 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00004685 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004686
Chris Lattner83930552007-05-01 07:01:57 +00004687 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00004688 if (I && !I->getType()->isVoidTy())
David Majnemer8a1c45d2015-12-12 05:38:55 +00004689 ValueList.assignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00004690 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004691
Chris Lattner27d38752013-01-20 02:13:19 +00004692OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00004693
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004694 if (!OperandBundles.empty())
4695 return error("Operand bundles found with no consumer");
4696
Chris Lattner83930552007-05-01 07:01:57 +00004697 // Check the function list for unresolved values.
4698 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004699 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00004700 // We found at least one unresolved value. Nuke them all to avoid leaks.
4701 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00004702 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00004703 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00004704 delete A;
4705 }
4706 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004707 return error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00004708 }
Chris Lattner83930552007-05-01 07:01:57 +00004709 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004710
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00004711 // Unexpected unresolved metadata about to be dropped.
Mehdi Aminief27db82016-12-12 19:34:26 +00004712 if (MDLoader->hasFwdRefs())
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00004713 return error("Invalid function metadata: outgoing forward refs");
Dan Gohman9b9ff462010-08-25 20:23:38 +00004714
Chris Lattner85b7b402007-05-01 05:52:21 +00004715 // Trim the value list down to the size it was before we parsed this function.
4716 ValueList.shrinkTo(ModuleValueListSize);
Mehdi Aminief27db82016-12-12 19:34:26 +00004717 MDLoader->shrinkTo(ModuleMDLoaderSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00004718 std::vector<BasicBlock*>().swap(FunctionBBs);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004719 return Error::success();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004720}
4721
Rafael Espindola7d712032013-11-05 17:16:08 +00004722/// Find the function body in the bitcode stream
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004723Error BitcodeReader::findFunctionInStream(
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004724 Function *F,
4725 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004726 while (DeferredFunctionInfoIterator->second == 0) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00004727 // This is the fallback handling for the old format bitcode that
Teresa Johnson1493ad92015-10-10 14:18:36 +00004728 // didn't contain the function index in the VST, or when we have
4729 // an anonymous function which would not have a VST entry.
4730 // Assert that we have one of those two cases.
4731 assert(VSTOffset == 0 || !F->hasName());
4732 // Parse the next body in the stream and set its position in the
4733 // DeferredFunctionInfo map.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004734 if (Error Err = rememberAndSkipFunctionBodies())
4735 return Err;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004736 }
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004737 return Error::success();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004738}
4739
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00004740SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
4741 if (Val == SyncScope::SingleThread || Val == SyncScope::System)
4742 return SyncScope::ID(Val);
4743 if (Val >= SSIDs.size())
4744 return SyncScope::System; // Map unknown synchronization scopes to system.
4745 return SSIDs[Val];
4746}
4747
Chris Lattner9eeada92007-05-18 04:02:46 +00004748//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004749// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00004750//===----------------------------------------------------------------------===//
4751
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00004752Error BitcodeReader::materialize(GlobalValue *GV) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004753 Function *F = dyn_cast<Function>(GV);
4754 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004755 if (!F || !F->isMaterializable())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004756 return Error::success();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004757
4758 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00004759 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004760 // If its position is recorded as 0, its body is somewhere in the stream
4761 // but we haven't seen it yet.
Rafael Espindola1c863ca2015-06-22 18:06:15 +00004762 if (DFII->second == 0)
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004763 if (Error Err = findFunctionInStream(F, DFII))
4764 return Err;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004765
Duncan P. N. Exon Smith03a04a52016-04-24 15:04:28 +00004766 // Materialize metadata before parsing any function bodies.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00004767 if (Error Err = materializeMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004768 return Err;
Duncan P. N. Exon Smith03a04a52016-04-24 15:04:28 +00004769
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004770 // Move the bit stream to the saved position of the deferred function body.
4771 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004772
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004773 if (Error Err = parseFunctionBody(F))
4774 return Err;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00004775 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00004776
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00004777 if (StripDebugInfo)
4778 stripDebugInfo(*F);
4779
Chandler Carruth7132e002007-08-04 01:51:18 +00004780 // Upgrade any old intrinsic calls in the function.
Rafael Espindola86e33402015-07-02 15:55:09 +00004781 for (auto &I : UpgradedIntrinsics) {
Rafael Espindola257a3532016-01-15 19:00:20 +00004782 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4783 UI != UE;) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004784 User *U = *UI;
4785 ++UI;
4786 if (CallInst *CI = dyn_cast<CallInst>(U))
4787 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00004788 }
4789 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004790
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00004791 // Update calls to the remangled intrinsics
4792 for (auto &I : RemangledIntrinsics)
4793 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4794 UI != UE;)
4795 // Don't expect any other users than call sites
4796 CallSite(*UI++).setCalledFunction(I.second);
4797
Peter Collingbourned4bff302015-11-05 22:03:56 +00004798 // Finish fn->subprogram upgrade for materialized functions.
Mehdi Aminief27db82016-12-12 19:34:26 +00004799 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
Peter Collingbourned4bff302015-11-05 22:03:56 +00004800 F->setSubprogram(SP);
4801
Mehdi Amini86623052016-12-16 19:16:29 +00004802 // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
4803 if (!MDLoader->isStrippingTBAA()) {
4804 for (auto &I : instructions(F)) {
4805 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
4806 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
4807 continue;
4808 MDLoader->setStripTBAA(true);
4809 stripTBAA(F->getParent());
4810 }
4811 }
4812
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004813 // Bring in any functions that this function forward-referenced via
4814 // blockaddresses.
4815 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00004816}
4817
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00004818Error BitcodeReader::materializeModule() {
4819 if (Error Err = materializeMetadata())
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004820 return Err;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004821
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004822 // Promise to materialize all forward references.
4823 WillMaterializeAllForwardRefs = true;
4824
Chris Lattner06310bf2009-06-16 05:15:21 +00004825 // Iterate over the module, deserializing any functions that are still on
4826 // disk.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00004827 for (Function &F : *TheModule) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00004828 if (Error Err = materialize(&F))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004829 return Err;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004830 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00004831 // At this point, if there are any function bodies, parse the rest of
4832 // the bits in the module past the last function block we have recorded
4833 // through either lazy scanning or the VST.
4834 if (LastFunctionBlockBit || NextUnreadBit)
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004835 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
4836 ? LastFunctionBlockBit
4837 : NextUnreadBit))
4838 return Err;
Derek Schuff92ef9752012-02-29 00:07:09 +00004839
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004840 // Check that all block address forward references got resolved (as we
4841 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004842 if (!BasicBlockFwdRefs.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004843 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004844
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004845 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4846 // delete the old functions to clean up. We can't do this unless the entire
4847 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00004848 // with calls to the old function.
Rafael Espindola86e33402015-07-02 15:55:09 +00004849 for (auto &I : UpgradedIntrinsics) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004850 for (auto *U : I.first->users()) {
4851 if (CallInst *CI = dyn_cast<CallInst>(U))
4852 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00004853 }
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004854 if (!I.first->use_empty())
4855 I.first->replaceAllUsesWith(I.second);
4856 I.first->eraseFromParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00004857 }
Rafael Espindola4e721212015-07-02 16:22:40 +00004858 UpgradedIntrinsics.clear();
Artur Pilipenko6c7a8ab2016-06-24 15:10:29 +00004859 // Do the same for remangled intrinsics
4860 for (auto &I : RemangledIntrinsics) {
4861 I.first->replaceAllUsesWith(I.second);
4862 I.first->eraseFromParent();
4863 }
4864 RemangledIntrinsics.clear();
Devang Patel80ae3492009-08-28 23:24:31 +00004865
Rafael Espindola79753a02015-12-18 21:18:57 +00004866 UpgradeDebugInfo(*TheModule);
Manman Renb5d7ff42016-05-25 23:14:48 +00004867
4868 UpgradeModuleFlags(*TheModule);
Gerolf Hoflehnerf41aa4f2018-04-05 02:44:46 +00004869
4870 UpgradeRetainReleaseMarker(*TheModule);
4871
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004872 return Error::success();
Chris Lattner9eeada92007-05-18 04:02:46 +00004873}
4874
Rafael Espindola2fa1e432014-12-03 07:18:23 +00004875std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4876 return IdentifiedStructTypes;
4877}
4878
Teresa Johnson26ab5772016-03-15 00:04:37 +00004879ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00004880 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
4881 StringRef ModulePath, unsigned ModuleId)
4882 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
4883 ModulePath(ModulePath), ModuleId(ModuleId) {}
4884
Teresa Johnson9766fd62018-06-26 01:32:58 +00004885void ModuleSummaryIndexBitcodeReader::addThisModule() {
4886 TheIndex.addModule(ModulePath, ModuleId);
4887}
4888
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00004889ModuleSummaryIndex::ModuleInfo *
Teresa Johnson9766fd62018-06-26 01:32:58 +00004890ModuleSummaryIndexBitcodeReader::getThisModule() {
4891 return TheIndex.getModule(ModulePath);
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00004892}
Teresa Johnson403a7872015-10-04 14:33:43 +00004893
Peter Collingbourne9667b912017-05-04 18:03:25 +00004894std::pair<ValueInfo, GlobalValue::GUID>
4895ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
4896 auto VGI = ValueIdToValueInfoMap[ValueId];
4897 assert(VGI.first);
4898 return VGI;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004899}
4900
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004901void ModuleSummaryIndexBitcodeReader::setValueGUID(
4902 uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
4903 StringRef SourceFileName) {
4904 std::string GlobalId =
4905 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
4906 auto ValueGUID = GlobalValue::getGUID(GlobalId);
4907 auto OriginalNameID = ValueGUID;
4908 if (GlobalValue::isLocalLinkage(Linkage))
4909 OriginalNameID = GlobalValue::getGUID(ValueName);
4910 if (PrintSummaryGUIDs)
4911 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
4912 << ValueName << "\n";
Teresa Johnson51905532018-06-26 02:29:08 +00004913
Eugene Leviant28d8a492018-01-22 13:35:40 +00004914 // UseStrtab is false for legacy summary formats and value names are
Teresa Johnson51905532018-06-26 02:29:08 +00004915 // created on stack. In that case we save the name in a string saver in
4916 // the index so that the value name can be recorded.
Eugene Leviant28d8a492018-01-22 13:35:40 +00004917 ValueIdToValueInfoMap[ValueID] = std::make_pair(
Teresa Johnson51905532018-06-26 02:29:08 +00004918 TheIndex.getOrInsertValueInfo(
4919 ValueGUID,
George Burgess IVa0082af2018-12-07 21:47:32 +00004920 UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
Eugene Leviant28d8a492018-01-22 13:35:40 +00004921 OriginalNameID);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004922}
4923
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004924// Specialized value symbol table parser used when reading module index
Teresa Johnson28e457b2016-04-24 14:57:11 +00004925// blocks where we don't actually create global values. The parsed information
4926// is saved in the bitcode reader for use when later parsing summaries.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004927Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004928 uint64_t Offset,
4929 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004930 // With a strtab the VST is not required to parse the summary.
4931 if (UseStrtab)
4932 return Error::success();
4933
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004934 assert(Offset > 0 && "Expected non-zero VST offset");
4935 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
4936
Teresa Johnson403a7872015-10-04 14:33:43 +00004937 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
4938 return error("Invalid record");
4939
4940 SmallVector<uint64_t, 64> Record;
4941
4942 // Read all the records for this value table.
4943 SmallString<128> ValueName;
Eugene Zelenko1804a772016-08-25 00:45:04 +00004944
4945 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00004946 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4947
4948 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004949 case BitstreamEntry::SubBlock: // Handled for us already.
4950 case BitstreamEntry::Error:
4951 return error("Malformed block");
4952 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004953 // Done parsing VST, jump back to wherever we came from.
4954 Stream.JumpToBit(CurrentBit);
Peter Collingbourne58f7f072016-11-09 00:51:04 +00004955 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004956 case BitstreamEntry::Record:
4957 // The interesting case.
4958 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00004959 }
4960
4961 // Read a record.
4962 Record.clear();
4963 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004964 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
4965 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004966 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
4967 if (convertToString(Record, 1, ValueName))
4968 return error("Invalid record");
4969 unsigned ValueID = Record[0];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004970 assert(!SourceFileName.empty());
4971 auto VLI = ValueIdToLinkageMap.find(ValueID);
4972 assert(VLI != ValueIdToLinkageMap.end() &&
4973 "No linkage found for VST entry?");
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00004974 auto Linkage = VLI->second;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004975 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004976 ValueName.clear();
4977 break;
4978 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004979 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00004980 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004981 if (convertToString(Record, 2, ValueName))
4982 return error("Invalid record");
4983 unsigned ValueID = Record[0];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004984 assert(!SourceFileName.empty());
4985 auto VLI = ValueIdToLinkageMap.find(ValueID);
4986 assert(VLI != ValueIdToLinkageMap.end() &&
4987 "No linkage found for VST entry?");
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00004988 auto Linkage = VLI->second;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00004989 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00004990 ValueName.clear();
4991 break;
4992 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00004993 case bitc::VST_CODE_COMBINED_ENTRY: {
4994 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
4995 unsigned ValueID = Record[0];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00004996 GlobalValue::GUID RefGUID = Record[1];
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00004997 // The "original name", which is the second value of the pair will be
4998 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
Peter Collingbourne9667b912017-05-04 18:03:25 +00004999 ValueIdToValueInfoMap[ValueID] =
5000 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005001 break;
5002 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005003 }
5004 }
5005}
5006
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005007// Parse just the blocks needed for building the index out of the module.
5008// At the end of this routine the module Index is populated with a map
Teresa Johnson28e457b2016-04-24 14:57:11 +00005009// from global value id to GlobalValueSummary objects.
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005010Error ModuleSummaryIndexBitcodeReader::parseModule() {
Teresa Johnson403a7872015-10-04 14:33:43 +00005011 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5012 return error("Invalid record");
5013
Teresa Johnsone1164de2016-02-10 21:55:02 +00005014 SmallVector<uint64_t, 64> Record;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005015 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
5016 unsigned ValueId = 0;
Teresa Johnsone1164de2016-02-10 21:55:02 +00005017
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005018 // Read the index for this module.
Eugene Zelenko1804a772016-08-25 00:45:04 +00005019 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005020 BitstreamEntry Entry = Stream.advance();
5021
5022 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005023 case BitstreamEntry::Error:
5024 return error("Malformed block");
5025 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005026 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005027
5028 case BitstreamEntry::SubBlock:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005029 switch (Entry.ID) {
5030 default: // Skip unknown content.
5031 if (Stream.SkipBlock())
5032 return error("Invalid record");
5033 break;
5034 case bitc::BLOCKINFO_BLOCK_ID:
5035 // Need to parse these to get abbrev ids (e.g. for VST)
Peter Collingbourne939c7d92016-11-08 04:16:57 +00005036 if (readBlockInfo())
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005037 return error("Malformed block");
5038 break;
5039 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005040 // Should have been parsed earlier via VSTOffset, unless there
5041 // is no summary section.
5042 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
5043 !SeenGlobalValSummary) &&
5044 "Expected early VST parse via VSTOffset record");
5045 if (Stream.SkipBlock())
5046 return error("Invalid record");
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005047 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005048 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005049 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
Teresa Johnson9766fd62018-06-26 01:32:58 +00005050 // Add the module if it is a per-module index (has a source file name).
5051 if (!SourceFileName.empty())
5052 addThisModule();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005053 assert(!SeenValueSymbolTable &&
5054 "Already read VST when parsing summary block?");
Teresa Johnson620c1402016-09-20 23:07:17 +00005055 // We might not have a VST if there were no values in the
5056 // summary. An empty summary block generated when we are
5057 // performing ThinLTO compiles so we don't later invoke
5058 // the regular LTO process on them.
5059 if (VSTOffset > 0) {
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005060 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
5061 return Err;
Teresa Johnson620c1402016-09-20 23:07:17 +00005062 SeenValueSymbolTable = true;
5063 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005064 SeenGlobalValSummary = true;
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005065 if (Error Err = parseEntireSummary(Entry.ID))
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005066 return Err;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005067 break;
5068 case bitc::MODULE_STRTAB_BLOCK_ID:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005069 if (Error Err = parseModuleStringTable())
5070 return Err;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005071 break;
5072 }
5073 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00005074
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005075 case BitstreamEntry::Record: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00005076 Record.clear();
5077 auto BitCode = Stream.readRecord(Entry.ID, Record);
5078 switch (BitCode) {
5079 default:
5080 break; // Default behavior, ignore unknown content.
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005081 case bitc::MODULE_CODE_VERSION: {
5082 if (Error Err = parseVersionRecord(Record).takeError())
5083 return Err;
5084 break;
5085 }
Teresa Johnsone1164de2016-02-10 21:55:02 +00005086 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005087 case bitc::MODULE_CODE_SOURCE_FILENAME: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00005088 SmallString<128> ValueName;
5089 if (convertToString(Record, 0, ValueName))
5090 return error("Invalid record");
5091 SourceFileName = ValueName.c_str();
5092 break;
5093 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005094 /// MODULE_CODE_HASH: [5*i32]
5095 case bitc::MODULE_CODE_HASH: {
5096 if (Record.size() != 5)
5097 return error("Invalid hash length " + Twine(Record.size()).str());
Teresa Johnson9766fd62018-06-26 01:32:58 +00005098 auto &Hash = getThisModule()->second.second;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005099 int Pos = 0;
5100 for (auto &Val : Record) {
5101 assert(!(Val >> 32) && "Unexpected high bits set");
5102 Hash[Pos++] = Val;
5103 }
5104 break;
5105 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005106 /// MODULE_CODE_VSTOFFSET: [offset]
5107 case bitc::MODULE_CODE_VSTOFFSET:
5108 if (Record.size() < 1)
5109 return error("Invalid record");
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005110 // Note that we subtract 1 here because the offset is relative to one
5111 // word before the start of the identification or module block, which
5112 // was historically always the start of the regular bitcode header.
5113 VSTOffset = Record[0] - 1;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005114 break;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005115 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
5116 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
5117 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
5118 // v2: [strtab offset, strtab size, v1]
Peter Collingbournef43e0ae2017-04-10 21:17:54 +00005119 case bitc::MODULE_CODE_GLOBALVAR:
5120 case bitc::MODULE_CODE_FUNCTION:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005121 case bitc::MODULE_CODE_ALIAS: {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005122 StringRef Name;
5123 ArrayRef<uint64_t> GVRecord;
5124 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
5125 if (GVRecord.size() <= 3)
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005126 return error("Invalid record");
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005127 uint64_t RawLinkage = GVRecord[3];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005128 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005129 if (!UseStrtab) {
5130 ValueIdToLinkageMap[ValueId++] = Linkage;
5131 break;
5132 }
5133
5134 setValueGUID(ValueId++, Name, Linkage, SourceFileName);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005135 break;
5136 }
5137 }
Teresa Johnsone1164de2016-02-10 21:55:02 +00005138 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005139 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00005140 }
5141 }
5142}
5143
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005144std::vector<ValueInfo>
5145ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
5146 std::vector<ValueInfo> Ret;
5147 Ret.reserve(Record.size());
5148 for (uint64_t RefValueId : Record)
Peter Collingbourne9667b912017-05-04 18:03:25 +00005149 Ret.push_back(getValueInfoFromValueId(RefValueId).first);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005150 return Ret;
5151}
5152
Easwaran Ramanc73cec82018-01-25 19:27:17 +00005153std::vector<FunctionSummary::EdgeTy>
5154ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
5155 bool IsOldProfileFormat,
5156 bool HasProfile, bool HasRelBF) {
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005157 std::vector<FunctionSummary::EdgeTy> Ret;
5158 Ret.reserve(Record.size());
5159 for (unsigned I = 0, E = Record.size(); I != E; ++I) {
5160 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
Easwaran Ramanc73cec82018-01-25 19:27:17 +00005161 uint64_t RelBF = 0;
Peter Collingbourne9667b912017-05-04 18:03:25 +00005162 ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005163 if (IsOldProfileFormat) {
5164 I += 1; // Skip old callsitecount field
5165 if (HasProfile)
5166 I += 1; // Skip old profilecount field
5167 } else if (HasProfile)
5168 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
Easwaran Ramanc73cec82018-01-25 19:27:17 +00005169 else if (HasRelBF)
5170 RelBF = Record[++I];
5171 Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)});
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005172 }
5173 return Ret;
5174}
5175
Vitaly Buka44396fa2018-02-14 22:41:15 +00005176static void
5177parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
5178 WholeProgramDevirtResolution &Wpd) {
5179 uint64_t ArgNum = Record[Slot++];
5180 WholeProgramDevirtResolution::ByArg &B =
5181 Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
5182 Slot += ArgNum;
5183
5184 B.TheKind =
5185 static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
5186 B.Info = Record[Slot++];
5187 B.Byte = Record[Slot++];
5188 B.Bit = Record[Slot++];
5189}
5190
5191static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
5192 StringRef Strtab, size_t &Slot,
5193 TypeIdSummary &TypeId) {
5194 uint64_t Id = Record[Slot++];
5195 WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
5196
5197 Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
5198 Wpd.SingleImplName = {Strtab.data() + Record[Slot],
5199 static_cast<size_t>(Record[Slot + 1])};
5200 Slot += 2;
5201
5202 uint64_t ResByArgNum = Record[Slot++];
5203 for (uint64_t I = 0; I != ResByArgNum; ++I)
5204 parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
5205}
5206
5207static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
5208 StringRef Strtab,
5209 ModuleSummaryIndex &TheIndex) {
5210 size_t Slot = 0;
5211 TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
5212 {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
5213 Slot += 2;
5214
5215 TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
5216 TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
5217 TypeId.TTRes.AlignLog2 = Record[Slot++];
5218 TypeId.TTRes.SizeM1 = Record[Slot++];
5219 TypeId.TTRes.BitMask = Record[Slot++];
5220 TypeId.TTRes.InlineBits = Record[Slot++];
5221
5222 while (Slot < Record.size())
5223 parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
5224}
5225
Eugene Leviantbf46e742018-11-16 07:08:00 +00005226static void setImmutableRefs(std::vector<ValueInfo> &Refs, unsigned Count) {
5227 // Read-only refs are in the end of the refs list.
5228 for (unsigned RefNo = Refs.size() - Count; RefNo < Refs.size(); ++RefNo)
5229 Refs[RefNo].setReadOnly();
5230}
5231
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005232// Eagerly parse the entire summary block. This populates the GlobalValueSummary
5233// objects in the index.
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005234Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
5235 if (Stream.EnterSubBlock(ID))
Teresa Johnson403a7872015-10-04 14:33:43 +00005236 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00005237 SmallVector<uint64_t, 64> Record;
Mehdi Amini8fe69362016-04-24 03:18:11 +00005238
5239 // Parse version
5240 {
5241 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5242 if (Entry.Kind != BitstreamEntry::Record)
5243 return error("Invalid Summary Block: record for version expected");
5244 if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
5245 return error("Invalid Summary Block: version expected");
5246 }
5247 const uint64_t Version = Record[0];
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005248 const bool IsOldProfileFormat = Version == 1;
Easwaran Raman5a7056f2018-12-13 19:54:27 +00005249 if (Version < 1 || Version > 6)
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005250 return error("Invalid summary version " + Twine(Version) +
Easwaran Raman5a7056f2018-12-13 19:54:27 +00005251 ". Version should be in the range [1-6].");
Mehdi Amini8fe69362016-04-24 03:18:11 +00005252 Record.clear();
5253
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005254 // Keep around the last seen summary to be used when we see an optional
5255 // "OriginalName" attachement.
5256 GlobalValueSummary *LastSeenSummary = nullptr;
Dehao Chen4a435e02017-03-14 17:33:01 +00005257 GlobalValue::GUID LastSeenGUID = 0;
Peter Collingbournefa3175f2017-02-11 03:19:22 +00005258
5259 // We can expect to see any number of type ID information records before
5260 // each function summary records; these variables store the information
5261 // collected so far so that it can be used to create the summary object.
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00005262 std::vector<GlobalValue::GUID> PendingTypeTests;
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005263 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
5264 PendingTypeCheckedLoadVCalls;
5265 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
5266 PendingTypeCheckedLoadConstVCalls;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005267
5268 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005269 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5270
5271 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005272 case BitstreamEntry::SubBlock: // Handled for us already.
5273 case BitstreamEntry::Error:
5274 return error("Malformed block");
5275 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005276 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005277 case BitstreamEntry::Record:
5278 // The interesting case.
5279 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005280 }
5281
5282 // Read a record. The record format depends on whether this
5283 // is a per-module index or a combined index file. In the per-module
5284 // case the records contain the associated value's ID for correlation
5285 // with VST entries. In the combined index the correlation is done
5286 // via the bitcode offset of the summary records (which were saved
5287 // in the combined index VST entries). The records also contain
5288 // information used for ThinLTO renaming and importing.
5289 Record.clear();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005290 auto BitCode = Stream.readRecord(Entry.ID, Record);
5291 switch (BitCode) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005292 default: // Default behavior: ignore.
5293 break;
Teresa Johnsonf3681012018-02-07 04:05:59 +00005294 case bitc::FS_FLAGS: { // [flags]
5295 uint64_t Flags = Record[0];
Teresa Johnson290a8392019-01-11 18:31:57 +00005296 // Scan flags.
5297 assert(Flags <= 0x1f && "Unexpected bits in flag");
Teresa Johnsonf3681012018-02-07 04:05:59 +00005298
5299 // 1 bit: WithGlobalValueDeadStripping flag.
Teresa Johnson290a8392019-01-11 18:31:57 +00005300 // Set on combined index only.
Teresa Johnsonf3681012018-02-07 04:05:59 +00005301 if (Flags & 0x1)
5302 TheIndex.setWithGlobalValueDeadStripping();
Vitaly Buka769134d2018-02-16 23:38:22 +00005303 // 1 bit: SkipModuleByDistributedBackend flag.
Teresa Johnson290a8392019-01-11 18:31:57 +00005304 // Set on combined index only.
Vitaly Buka769134d2018-02-16 23:38:22 +00005305 if (Flags & 0x2)
5306 TheIndex.setSkipModuleByDistributedBackend();
Easwaran Raman5a7056f2018-12-13 19:54:27 +00005307 // 1 bit: HasSyntheticEntryCounts flag.
Teresa Johnson290a8392019-01-11 18:31:57 +00005308 // Set on combined index only.
Easwaran Raman5a7056f2018-12-13 19:54:27 +00005309 if (Flags & 0x4)
5310 TheIndex.setHasSyntheticEntryCounts();
Teresa Johnson290a8392019-01-11 18:31:57 +00005311 // 1 bit: DisableSplitLTOUnit flag.
5312 // Set on per module indexes. It is up to the client to validate
5313 // the consistency of this flag across modules being linked.
5314 if (Flags & 0x8)
5315 TheIndex.setEnableSplitLTOUnit();
5316 // 1 bit: PartiallySplitLTOUnits flag.
5317 // Set on combined index only.
5318 if (Flags & 0x10)
5319 TheIndex.setPartiallySplitLTOUnits();
Teresa Johnsonf3681012018-02-07 04:05:59 +00005320 break;
5321 }
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005322 case bitc::FS_VALUE_GUID: { // [valueid, refguid]
5323 uint64_t ValueID = Record[0];
5324 GlobalValue::GUID RefGUID = Record[1];
Peter Collingbourne9667b912017-05-04 18:03:25 +00005325 ValueIdToValueInfoMap[ValueID] =
5326 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005327 break;
5328 }
Charles Saternos75da10d2017-08-04 16:00:58 +00005329 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
5330 // numrefs x valueid, n x (valueid)]
5331 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005332 // numrefs x valueid,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005333 // n x (valueid, hotness)]
Easwaran Ramanc73cec82018-01-25 19:27:17 +00005334 // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
5335 // numrefs x valueid,
5336 // n x (valueid, relblockfreq)]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005337 case bitc::FS_PERMODULE:
Easwaran Ramanc73cec82018-01-25 19:27:17 +00005338 case bitc::FS_PERMODULE_RELBF:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005339 case bitc::FS_PERMODULE_PROFILE: {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005340 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005341 uint64_t RawFlags = Record[1];
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005342 unsigned InstCount = Record[2];
Charles Saternos75da10d2017-08-04 16:00:58 +00005343 uint64_t RawFunFlags = 0;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005344 unsigned NumRefs = Record[3];
Eugene Leviantbf46e742018-11-16 07:08:00 +00005345 unsigned NumImmutableRefs = 0;
Charles Saternos75da10d2017-08-04 16:00:58 +00005346 int RefListStartIndex = 4;
5347 if (Version >= 4) {
5348 RawFunFlags = Record[3];
5349 NumRefs = Record[4];
5350 RefListStartIndex = 5;
Eugene Leviantbf46e742018-11-16 07:08:00 +00005351 if (Version >= 5) {
5352 NumImmutableRefs = Record[5];
5353 RefListStartIndex = 6;
5354 }
Charles Saternos75da10d2017-08-04 16:00:58 +00005355 }
5356
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005357 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005358 // The module path string ref set in the summary must be owned by the
5359 // index's module string table. Since we don't have a module path
5360 // string table section in the per-module index, we create a single
5361 // module path string table entry with an empty (0) ID to take
5362 // ownership.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005363 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5364 assert(Record.size() >= RefListStartIndex + NumRefs &&
5365 "Record size inconsistent with number of references");
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005366 std::vector<ValueInfo> Refs = makeRefList(
5367 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005368 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
Easwaran Ramanc73cec82018-01-25 19:27:17 +00005369 bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005370 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
5371 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
Easwaran Ramanc73cec82018-01-25 19:27:17 +00005372 IsOldProfileFormat, HasProfile, HasRelBF);
Eugene Leviantbf46e742018-11-16 07:08:00 +00005373 setImmutableRefs(Refs, NumImmutableRefs);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005374 auto FS = llvm::make_unique<FunctionSummary>(
Easwaran Raman5a7056f2018-12-13 19:54:27 +00005375 Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
5376 std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
Charles Saternos75da10d2017-08-04 16:00:58 +00005377 std::move(PendingTypeTestAssumeVCalls),
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005378 std::move(PendingTypeCheckedLoadVCalls),
5379 std::move(PendingTypeTestAssumeConstVCalls),
5380 std::move(PendingTypeCheckedLoadConstVCalls));
Peter Collingbourne704f8142016-12-22 02:52:23 +00005381 PendingTypeTests.clear();
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005382 PendingTypeTestAssumeVCalls.clear();
5383 PendingTypeCheckedLoadVCalls.clear();
5384 PendingTypeTestAssumeConstVCalls.clear();
5385 PendingTypeCheckedLoadConstVCalls.clear();
Peter Collingbourne9667b912017-05-04 18:03:25 +00005386 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
Teresa Johnson9766fd62018-06-26 01:32:58 +00005387 FS->setModulePath(getThisModule()->first());
Peter Collingbourne9667b912017-05-04 18:03:25 +00005388 FS->setOriginalName(VIAndOriginalGUID.second);
5389 TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
Teresa Johnsonbbe05452016-02-24 17:57:28 +00005390 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005391 }
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005392 // FS_ALIAS: [valueid, flags, valueid]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005393 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
5394 // they expect all aliasee summaries to be available.
5395 case bitc::FS_ALIAS: {
5396 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005397 uint64_t RawFlags = Record[1];
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005398 unsigned AliaseeID = Record[2];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005399 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Teresa Johnsoncbdc5ff2017-09-13 17:10:24 +00005400 auto AS = llvm::make_unique<AliasSummary>(Flags);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005401 // The module path string ref set in the summary must be owned by the
5402 // index's module string table. Since we don't have a module path
5403 // string table section in the per-module index, we create a single
5404 // module path string table entry with an empty (0) ID to take
5405 // ownership.
Teresa Johnson9766fd62018-06-26 01:32:58 +00005406 AS->setModulePath(getThisModule()->first());
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005407
Peter Collingbourne9667b912017-05-04 18:03:25 +00005408 GlobalValue::GUID AliaseeGUID =
5409 getValueInfoFromValueId(AliaseeID).first.getGUID();
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005410 auto AliaseeInModule =
5411 TheIndex.findSummaryInModule(AliaseeGUID, ModulePath);
5412 if (!AliaseeInModule)
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005413 return error("Alias expects aliasee summary to be parsed");
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005414 AS->setAliasee(AliaseeInModule);
Teresa Johnson81bbf742017-12-16 00:18:12 +00005415 AS->setAliaseeGUID(AliaseeGUID);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005416
Peter Collingbourne9667b912017-05-04 18:03:25 +00005417 auto GUID = getValueInfoFromValueId(ValueID);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005418 AS->setOriginalName(GUID.second);
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005419 TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005420 break;
5421 }
Eugene Leviantbf46e742018-11-16 07:08:00 +00005422 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005423 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
5424 unsigned ValueID = Record[0];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005425 uint64_t RawFlags = Record[1];
Eugene Leviantbf46e742018-11-16 07:08:00 +00005426 unsigned RefArrayStart = 2;
5427 GlobalVarSummary::GVarFlags GVF;
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005428 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Eugene Leviantbf46e742018-11-16 07:08:00 +00005429 if (Version >= 5) {
5430 GVF = getDecodedGVarFlags(Record[2]);
5431 RefArrayStart = 3;
5432 }
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005433 std::vector<ValueInfo> Refs =
Eugene Leviantbf46e742018-11-16 07:08:00 +00005434 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
5435 auto FS =
5436 llvm::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
Teresa Johnson9766fd62018-06-26 01:32:58 +00005437 FS->setModulePath(getThisModule()->first());
Peter Collingbourne9667b912017-05-04 18:03:25 +00005438 auto GUID = getValueInfoFromValueId(ValueID);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005439 FS->setOriginalName(GUID.second);
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005440 TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005441 break;
5442 }
Charles Saternos75da10d2017-08-04 16:00:58 +00005443 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005444 // numrefs x valueid, n x (valueid)]
Charles Saternos75da10d2017-08-04 16:00:58 +00005445 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +00005446 // numrefs x valueid, n x (valueid, hotness)]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005447 case bitc::FS_COMBINED:
5448 case bitc::FS_COMBINED_PROFILE: {
Teresa Johnson02e98332016-04-27 13:28:35 +00005449 unsigned ValueID = Record[0];
5450 uint64_t ModuleId = Record[1];
5451 uint64_t RawFlags = Record[2];
5452 unsigned InstCount = Record[3];
Charles Saternos75da10d2017-08-04 16:00:58 +00005453 uint64_t RawFunFlags = 0;
Easwaran Raman5a7056f2018-12-13 19:54:27 +00005454 uint64_t EntryCount = 0;
Teresa Johnson02e98332016-04-27 13:28:35 +00005455 unsigned NumRefs = Record[4];
Eugene Leviantbf46e742018-11-16 07:08:00 +00005456 unsigned NumImmutableRefs = 0;
Charles Saternos75da10d2017-08-04 16:00:58 +00005457 int RefListStartIndex = 5;
5458
5459 if (Version >= 4) {
5460 RawFunFlags = Record[4];
Charles Saternos75da10d2017-08-04 16:00:58 +00005461 RefListStartIndex = 6;
Easwaran Raman5a7056f2018-12-13 19:54:27 +00005462 size_t NumRefsIndex = 5;
Eugene Leviantbf46e742018-11-16 07:08:00 +00005463 if (Version >= 5) {
Eugene Leviantbf46e742018-11-16 07:08:00 +00005464 RefListStartIndex = 7;
Easwaran Raman5a7056f2018-12-13 19:54:27 +00005465 if (Version >= 6) {
5466 NumRefsIndex = 6;
5467 EntryCount = Record[5];
5468 RefListStartIndex = 8;
5469 }
5470 NumImmutableRefs = Record[RefListStartIndex - 1];
Eugene Leviantbf46e742018-11-16 07:08:00 +00005471 }
Easwaran Raman5a7056f2018-12-13 19:54:27 +00005472 NumRefs = Record[NumRefsIndex];
Charles Saternos75da10d2017-08-04 16:00:58 +00005473 }
5474
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005475 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005476 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5477 assert(Record.size() >= RefListStartIndex + NumRefs &&
5478 "Record size inconsistent with number of references");
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005479 std::vector<ValueInfo> Refs = makeRefList(
5480 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005481 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005482 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
5483 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
Easwaran Ramanc73cec82018-01-25 19:27:17 +00005484 IsOldProfileFormat, HasProfile, false);
Peter Collingbourne9667b912017-05-04 18:03:25 +00005485 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
Eugene Leviantbf46e742018-11-16 07:08:00 +00005486 setImmutableRefs(Refs, NumImmutableRefs);
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005487 auto FS = llvm::make_unique<FunctionSummary>(
Easwaran Raman5a7056f2018-12-13 19:54:27 +00005488 Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
5489 std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
Charles Saternos75da10d2017-08-04 16:00:58 +00005490 std::move(PendingTypeTestAssumeVCalls),
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005491 std::move(PendingTypeCheckedLoadVCalls),
5492 std::move(PendingTypeTestAssumeConstVCalls),
5493 std::move(PendingTypeCheckedLoadConstVCalls));
Peter Collingbourne704f8142016-12-22 02:52:23 +00005494 PendingTypeTests.clear();
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005495 PendingTypeTestAssumeVCalls.clear();
5496 PendingTypeCheckedLoadVCalls.clear();
5497 PendingTypeTestAssumeConstVCalls.clear();
5498 PendingTypeCheckedLoadConstVCalls.clear();
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005499 LastSeenSummary = FS.get();
Peter Collingbourne9667b912017-05-04 18:03:25 +00005500 LastSeenGUID = VI.getGUID();
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005501 FS->setModulePath(ModuleIdMap[ModuleId]);
Peter Collingbourne9667b912017-05-04 18:03:25 +00005502 TheIndex.addGlobalValueSummary(VI, std::move(FS));
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005503 break;
5504 }
Teresa Johnson02e98332016-04-27 13:28:35 +00005505 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005506 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
5507 // they expect all aliasee summaries to be available.
5508 case bitc::FS_COMBINED_ALIAS: {
Teresa Johnson02e98332016-04-27 13:28:35 +00005509 unsigned ValueID = Record[0];
5510 uint64_t ModuleId = Record[1];
5511 uint64_t RawFlags = Record[2];
5512 unsigned AliaseeValueId = Record[3];
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005513 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Teresa Johnsoncbdc5ff2017-09-13 17:10:24 +00005514 auto AS = llvm::make_unique<AliasSummary>(Flags);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005515 LastSeenSummary = AS.get();
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005516 AS->setModulePath(ModuleIdMap[ModuleId]);
5517
Peter Collingbourne9667b912017-05-04 18:03:25 +00005518 auto AliaseeGUID =
5519 getValueInfoFromValueId(AliaseeValueId).first.getGUID();
Teresa Johnson02e98332016-04-27 13:28:35 +00005520 auto AliaseeInModule =
Peter Collingbourne57f9b8c2016-12-01 06:21:08 +00005521 TheIndex.findSummaryInModule(AliaseeGUID, AS->modulePath());
Teresa Johnson02e98332016-04-27 13:28:35 +00005522 AS->setAliasee(AliaseeInModule);
Teresa Johnson81bbf742017-12-16 00:18:12 +00005523 AS->setAliaseeGUID(AliaseeGUID);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005524
Peter Collingbourne9667b912017-05-04 18:03:25 +00005525 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5526 LastSeenGUID = VI.getGUID();
5527 TheIndex.addGlobalValueSummary(VI, std::move(AS));
Mehdi Amini2d28f7a2016-04-16 06:56:44 +00005528 break;
5529 }
Teresa Johnson02e98332016-04-27 13:28:35 +00005530 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005531 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
Teresa Johnson02e98332016-04-27 13:28:35 +00005532 unsigned ValueID = Record[0];
5533 uint64_t ModuleId = Record[1];
5534 uint64_t RawFlags = Record[2];
Eugene Leviantbf46e742018-11-16 07:08:00 +00005535 unsigned RefArrayStart = 3;
5536 GlobalVarSummary::GVarFlags GVF;
Mehdi Aminic3ed48c2016-04-24 03:18:18 +00005537 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
Eugene Leviantbf46e742018-11-16 07:08:00 +00005538 if (Version >= 5) {
5539 GVF = getDecodedGVarFlags(Record[3]);
5540 RefArrayStart = 4;
5541 }
Peter Collingbourne0c30f082016-12-20 21:12:28 +00005542 std::vector<ValueInfo> Refs =
Eugene Leviantbf46e742018-11-16 07:08:00 +00005543 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
5544 auto FS =
5545 llvm::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005546 LastSeenSummary = FS.get();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005547 FS->setModulePath(ModuleIdMap[ModuleId]);
Peter Collingbourne9667b912017-05-04 18:03:25 +00005548 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5549 LastSeenGUID = VI.getGUID();
5550 TheIndex.addGlobalValueSummary(VI, std::move(FS));
Teresa Johnsonbbe05452016-02-24 17:57:28 +00005551 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005552 }
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005553 // FS_COMBINED_ORIGINAL_NAME: [original_name]
5554 case bitc::FS_COMBINED_ORIGINAL_NAME: {
5555 uint64_t OriginalName = Record[0];
5556 if (!LastSeenSummary)
5557 return error("Name attachment that does not follow a combined record");
5558 LastSeenSummary->setOriginalName(OriginalName);
Dehao Chen4a435e02017-03-14 17:33:01 +00005559 TheIndex.addOriginalName(LastSeenGUID, OriginalName);
Mehdi Aminiae64eaf2016-04-23 23:38:17 +00005560 // Reset the LastSeenSummary
5561 LastSeenSummary = nullptr;
Dehao Chen4a435e02017-03-14 17:33:01 +00005562 LastSeenGUID = 0;
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00005563 break;
5564 }
Eugene Zelenko975293f2017-09-07 23:28:24 +00005565 case bitc::FS_TYPE_TESTS:
Peter Collingbourne1b4137a72016-12-21 23:03:45 +00005566 assert(PendingTypeTests.empty());
5567 PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(),
5568 Record.end());
5569 break;
Eugene Zelenko975293f2017-09-07 23:28:24 +00005570
5571 case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005572 assert(PendingTypeTestAssumeVCalls.empty());
5573 for (unsigned I = 0; I != Record.size(); I += 2)
5574 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
5575 break;
Eugene Zelenko975293f2017-09-07 23:28:24 +00005576
5577 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005578 assert(PendingTypeCheckedLoadVCalls.empty());
5579 for (unsigned I = 0; I != Record.size(); I += 2)
5580 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
5581 break;
Eugene Zelenko975293f2017-09-07 23:28:24 +00005582
5583 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005584 PendingTypeTestAssumeConstVCalls.push_back(
5585 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5586 break;
Eugene Zelenko975293f2017-09-07 23:28:24 +00005587
5588 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +00005589 PendingTypeCheckedLoadConstVCalls.push_back(
5590 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5591 break;
Eugene Zelenko975293f2017-09-07 23:28:24 +00005592
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00005593 case bitc::FS_CFI_FUNCTION_DEFS: {
5594 std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
5595 for (unsigned I = 0; I != Record.size(); I += 2)
Evgeniy Stepanovf63d4142017-06-16 00:32:11 +00005596 CfiFunctionDefs.insert(
5597 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00005598 break;
5599 }
Vitaly Buka44396fa2018-02-14 22:41:15 +00005600
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00005601 case bitc::FS_CFI_FUNCTION_DECLS: {
5602 std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
5603 for (unsigned I = 0; I != Record.size(); I += 2)
Evgeniy Stepanovf63d4142017-06-16 00:32:11 +00005604 CfiFunctionDecls.insert(
5605 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +00005606 break;
5607 }
Vitaly Buka44396fa2018-02-14 22:41:15 +00005608
5609 case bitc::FS_TYPE_ID:
5610 parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
5611 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005612 }
5613 }
5614 llvm_unreachable("Exit infinite loop");
5615}
5616
5617// Parse the module string table block into the Index.
5618// This populates the ModulePathStringTable map in the index.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005619Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
Teresa Johnson403a7872015-10-04 14:33:43 +00005620 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5621 return error("Invalid record");
5622
5623 SmallVector<uint64_t, 64> Record;
5624
5625 SmallString<128> ModulePath;
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005626 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
Eugene Zelenko1804a772016-08-25 00:45:04 +00005627
5628 while (true) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005629 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5630
5631 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005632 case BitstreamEntry::SubBlock: // Handled for us already.
5633 case BitstreamEntry::Error:
5634 return error("Malformed block");
5635 case BitstreamEntry::EndBlock:
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005636 return Error::success();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005637 case BitstreamEntry::Record:
5638 // The interesting case.
5639 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005640 }
5641
5642 Record.clear();
5643 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005644 default: // Default behavior: ignore.
5645 break;
5646 case bitc::MST_CODE_ENTRY: {
5647 // MST_ENTRY: [modid, namechar x N]
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005648 uint64_t ModuleId = Record[0];
5649
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005650 if (convertToString(Record, 1, ModulePath))
5651 return error("Invalid record");
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005652
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005653 LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
5654 ModuleIdMap[ModuleId] = LastSeenModule->first();
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005655
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005656 ModulePath.clear();
5657 break;
5658 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005659 /// MST_CODE_HASH: [5*i32]
5660 case bitc::MST_CODE_HASH: {
5661 if (Record.size() != 5)
5662 return error("Invalid hash length " + Twine(Record.size()).str());
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005663 if (!LastSeenModule)
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005664 return error("Invalid hash that does not follow a module path");
5665 int Pos = 0;
5666 for (auto &Val : Record) {
5667 assert(!(Val >> 32) && "Unexpected high bits set");
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005668 LastSeenModule->second.second[Pos++] = Val;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005669 }
Peter Collingbourne5aa56d22017-06-14 22:35:27 +00005670 // Reset LastSeenModule to avoid overriding the hash unexpectedly.
5671 LastSeenModule = nullptr;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005672 break;
5673 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005674 }
5675 }
5676 llvm_unreachable("Exit infinite loop");
5677}
5678
Rafael Espindola48da4f42013-11-04 16:16:24 +00005679namespace {
Eugene Zelenko1804a772016-08-25 00:45:04 +00005680
Peter Collingbourne4718f8b2016-05-24 20:13:46 +00005681// FIXME: This class is only here to support the transition to llvm::Error. It
5682// will be removed once this transition is complete. Clients should prefer to
5683// deal with the Error value directly, rather than converting to error_code.
Rafael Espindola25188c92014-06-12 01:45:43 +00005684class BitcodeErrorCategoryType : public std::error_category {
Reid Kleckner990504e2016-10-19 23:52:38 +00005685 const char *name() const noexcept override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00005686 return "llvm.bitcode";
5687 }
Eugene Zelenko975293f2017-09-07 23:28:24 +00005688
Craig Topper73156022014-03-02 09:09:27 +00005689 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00005690 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00005691 switch (E) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00005692 case BitcodeError::CorruptedBitcode:
5693 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00005694 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00005695 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00005696 }
5697};
Eugene Zelenko1804a772016-08-25 00:45:04 +00005698
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00005699} // end anonymous namespace
Rafael Espindola48da4f42013-11-04 16:16:24 +00005700
Chris Bieneman770163e2014-09-19 20:29:02 +00005701static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5702
Rafael Espindolac3f2e732014-07-29 20:22:46 +00005703const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00005704 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005705}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00005706
Peter Collingbourne99b98c22017-06-27 23:50:24 +00005707static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
5708 unsigned Block, unsigned RecordID) {
5709 if (Stream.EnterSubBlock(Block))
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005710 return error("Invalid record");
5711
5712 StringRef Strtab;
Eugene Zelenko975293f2017-09-07 23:28:24 +00005713 while (true) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005714 BitstreamEntry Entry = Stream.advance();
5715 switch (Entry.Kind) {
5716 case BitstreamEntry::EndBlock:
5717 return Strtab;
5718
5719 case BitstreamEntry::Error:
5720 return error("Malformed block");
5721
5722 case BitstreamEntry::SubBlock:
5723 if (Stream.SkipBlock())
5724 return error("Malformed block");
5725 break;
5726
5727 case BitstreamEntry::Record:
5728 StringRef Blob;
5729 SmallVector<uint64_t, 1> Record;
Peter Collingbourne99b98c22017-06-27 23:50:24 +00005730 if (Stream.readRecord(Entry.ID, Record, &Blob) == RecordID)
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005731 Strtab = Blob;
5732 break;
5733 }
5734 }
5735}
5736
Chris Lattner6694f602007-04-29 07:54:31 +00005737//===----------------------------------------------------------------------===//
5738// External interface
5739//===----------------------------------------------------------------------===//
5740
Peter Collingbourne7a748032016-11-16 21:44:45 +00005741Expected<std::vector<BitcodeModule>>
5742llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
Peter Collingbourne8dde4cb2017-06-08 22:00:24 +00005743 auto FOrErr = getBitcodeFileContents(Buffer);
5744 if (!FOrErr)
5745 return FOrErr.takeError();
5746 return std::move(FOrErr->Mods);
5747}
5748
5749Expected<BitcodeFileContents>
5750llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
Peter Collingbourne7a748032016-11-16 21:44:45 +00005751 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5752 if (!StreamOrErr)
5753 return StreamOrErr.takeError();
5754 BitstreamCursor &Stream = *StreamOrErr;
5755
Peter Collingbourne8dde4cb2017-06-08 22:00:24 +00005756 BitcodeFileContents F;
Peter Collingbourne7a748032016-11-16 21:44:45 +00005757 while (true) {
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005758 uint64_t BCBegin = Stream.getCurrentByteNo();
5759
Peter Collingbourne7a748032016-11-16 21:44:45 +00005760 // We may be consuming bitcode from a client that leaves garbage at the end
5761 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
5762 // the end that there cannot possibly be another module, stop looking.
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005763 if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
Peter Collingbourne8dde4cb2017-06-08 22:00:24 +00005764 return F;
Peter Collingbourne7a748032016-11-16 21:44:45 +00005765
5766 BitstreamEntry Entry = Stream.advance();
5767 switch (Entry.Kind) {
5768 case BitstreamEntry::EndBlock:
5769 case BitstreamEntry::Error:
5770 return error("Malformed block");
5771
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005772 case BitstreamEntry::SubBlock: {
5773 uint64_t IdentificationBit = -1ull;
5774 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
5775 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5776 if (Stream.SkipBlock())
5777 return error("Malformed block");
5778
5779 Entry = Stream.advance();
5780 if (Entry.Kind != BitstreamEntry::SubBlock ||
5781 Entry.ID != bitc::MODULE_BLOCK_ID)
5782 return error("Malformed block");
5783 }
5784
5785 if (Entry.ID == bitc::MODULE_BLOCK_ID) {
5786 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5787 if (Stream.SkipBlock())
5788 return error("Malformed block");
5789
Peter Collingbourne8dde4cb2017-06-08 22:00:24 +00005790 F.Mods.push_back({Stream.getBitcodeBytes().slice(
5791 BCBegin, Stream.getCurrentByteNo() - BCBegin),
5792 Buffer.getBufferIdentifier(), IdentificationBit,
5793 ModuleBit});
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005794 continue;
5795 }
Peter Collingbourne7a748032016-11-16 21:44:45 +00005796
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005797 if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
Peter Collingbourne99b98c22017-06-27 23:50:24 +00005798 Expected<StringRef> Strtab =
5799 readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005800 if (!Strtab)
5801 return Strtab.takeError();
5802 // This string table is used by every preceding bitcode module that does
5803 // not have its own string table. A bitcode file may have multiple
5804 // string tables if it was created by binary concatenation, for example
5805 // with "llvm-cat -b".
Peter Collingbourne8dde4cb2017-06-08 22:00:24 +00005806 for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) {
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005807 if (!I->Strtab.empty())
5808 break;
5809 I->Strtab = *Strtab;
5810 }
Peter Collingbourne99b98c22017-06-27 23:50:24 +00005811 // Similarly, the string table is used by every preceding symbol table;
5812 // normally there will be just one unless the bitcode file was created
5813 // by binary concatenation.
5814 if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
5815 F.StrtabForSymtab = *Strtab;
5816 continue;
5817 }
5818
5819 if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
5820 Expected<StringRef> SymtabOrErr =
5821 readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
5822 if (!SymtabOrErr)
5823 return SymtabOrErr.takeError();
5824
5825 // We can expect the bitcode file to have multiple symbol tables if it
5826 // was created by binary concatenation. In that case we silently
5827 // ignore any subsequent symbol tables, which is fine because this is a
5828 // low level function. The client is expected to notice that the number
5829 // of modules in the symbol table does not match the number of modules
5830 // in the input file and regenerate the symbol table.
5831 if (F.Symtab.empty())
5832 F.Symtab = *SymtabOrErr;
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005833 continue;
5834 }
5835
Peter Collingbourne7a748032016-11-16 21:44:45 +00005836 if (Stream.SkipBlock())
5837 return error("Malformed block");
5838 continue;
Peter Collingbournebfcf9802016-11-29 02:27:04 +00005839 }
Peter Collingbourne7a748032016-11-16 21:44:45 +00005840 case BitstreamEntry::Record:
5841 Stream.skipRecord(Entry.ID);
5842 continue;
5843 }
5844 }
5845}
5846
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005847/// Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00005848///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005849/// This isn't always used in a lazy context. In particular, it's also used by
Peter Collingbourne7a748032016-11-16 21:44:45 +00005850/// \a parseModule(). If this is truly lazy, then we need to eagerly pull
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00005851/// in forward-referenced functions from block address references.
5852///
Rafael Espindola728074b2015-06-17 00:40:56 +00005853/// \param[in] MaterializeAll Set to \c true if we should materialize
5854/// everything.
Peter Collingbourne7a748032016-11-16 21:44:45 +00005855Expected<std::unique_ptr<Module>>
5856BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005857 bool ShouldLazyLoadMetadata, bool IsImporting) {
Peter Collingbourne7a748032016-11-16 21:44:45 +00005858 BitstreamCursor Stream(Buffer);
Peter Collingbournec0032b72016-11-11 19:50:10 +00005859
Peter Collingbourne7a748032016-11-16 21:44:45 +00005860 std::string ProducerIdentification;
5861 if (IdentificationBit != -1ull) {
5862 Stream.JumpToBit(IdentificationBit);
5863 Expected<std::string> ProducerIdentificationOrErr =
5864 readIdentificationBlock(Stream);
5865 if (!ProducerIdentificationOrErr)
5866 return ProducerIdentificationOrErr.takeError();
5867
5868 ProducerIdentification = *ProducerIdentificationOrErr;
5869 }
5870
5871 Stream.JumpToBit(ModuleBit);
Peter Collingbournea0f371a2017-04-17 17:51:36 +00005872 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
5873 Context);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005874
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005875 std::unique_ptr<Module> M =
Peter Collingbourne7a748032016-11-16 21:44:45 +00005876 llvm::make_unique<Module>(ModuleIdentifier, Context);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005877 M->setMaterializer(R);
Rafael Espindolab7993462012-01-02 07:49:53 +00005878
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005879 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005880 if (Error Err =
5881 R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting))
Peter Collingbourned9445c42016-11-13 07:00:17 +00005882 return std::move(Err);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005883
5884 if (MaterializeAll) {
5885 // Read in the entire module, and destroy the BitcodeReader.
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +00005886 if (Error Err = M->materializeAll())
Peter Collingbourned9445c42016-11-13 07:00:17 +00005887 return std::move(Err);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005888 } else {
5889 // Resolve forward references from blockaddresses.
Peter Collingbourne58f7f072016-11-09 00:51:04 +00005890 if (Error Err = R->materializeForwardReferencedFunctions())
Peter Collingbourned9445c42016-11-13 07:00:17 +00005891 return std::move(Err);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00005892 }
5893 return std::move(M);
Chris Lattner6694f602007-04-29 07:54:31 +00005894}
5895
Peter Collingbourned9445c42016-11-13 07:00:17 +00005896Expected<std::unique_ptr<Module>>
Teresa Johnsona61f5e32016-12-16 21:25:01 +00005897BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
5898 bool IsImporting) {
5899 return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting);
Peter Collingbourne7a748032016-11-16 21:44:45 +00005900}
5901
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005902// Parse the specified bitcode buffer and merge the index into CombinedIndex.
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005903// We don't use ModuleIdentifier here because the client may need to control the
5904// module path used in the combined summary (e.g. when reading summaries for
5905// regular LTO modules).
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005906Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005907 StringRef ModulePath, uint64_t ModuleId) {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005908 BitstreamCursor Stream(Buffer);
5909 Stream.JumpToBit(ModuleBit);
5910
5911 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005912 ModulePath, ModuleId);
Peter Collingbourne440e2042017-05-01 22:48:10 +00005913 return R.parseModule();
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005914}
5915
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005916// Parse the specified bitcode buffer, returning the function info index.
5917Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
5918 BitstreamCursor Stream(Buffer);
5919 Stream.JumpToBit(ModuleBit);
5920
Teresa Johnson4ffc3e72018-06-06 22:22:01 +00005921 auto Index = llvm::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005922 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
5923 ModuleIdentifier, 0);
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005924
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00005925 if (Error Err = R.parseModule())
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005926 return std::move(Err);
5927
5928 return std::move(Index);
5929}
5930
Teresa Johnson290a8392019-01-11 18:31:57 +00005931static Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream,
5932 unsigned ID) {
5933 if (Stream.EnterSubBlock(ID))
5934 return error("Invalid record");
5935 SmallVector<uint64_t, 64> Record;
5936
5937 while (true) {
5938 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5939
5940 switch (Entry.Kind) {
5941 case BitstreamEntry::SubBlock: // Handled for us already.
5942 case BitstreamEntry::Error:
5943 return error("Malformed block");
5944 case BitstreamEntry::EndBlock:
5945 // If no flags record found, conservatively return true to mimic
5946 // behavior before this flag was added.
5947 return true;
5948 case BitstreamEntry::Record:
5949 // The interesting case.
5950 break;
5951 }
5952
5953 // Look for the FS_FLAGS record.
5954 Record.clear();
5955 auto BitCode = Stream.readRecord(Entry.ID, Record);
5956 switch (BitCode) {
5957 default: // Default behavior: ignore.
5958 break;
5959 case bitc::FS_FLAGS: { // [flags]
5960 uint64_t Flags = Record[0];
5961 // Scan flags.
5962 assert(Flags <= 0x1f && "Unexpected bits in flag");
5963
5964 return Flags & 0x8;
5965 }
5966 }
5967 }
5968 llvm_unreachable("Exit infinite loop");
5969}
5970
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005971// Check if the given bitcode buffer contains a global value summary block.
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005972Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005973 BitstreamCursor Stream(Buffer);
5974 Stream.JumpToBit(ModuleBit);
5975
5976 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5977 return error("Invalid record");
5978
5979 while (true) {
5980 BitstreamEntry Entry = Stream.advance();
5981
5982 switch (Entry.Kind) {
5983 case BitstreamEntry::Error:
5984 return error("Malformed block");
5985 case BitstreamEntry::EndBlock:
Teresa Johnson290a8392019-01-11 18:31:57 +00005986 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
5987 /*EnableSplitLTOUnit=*/false};
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00005988
5989 case BitstreamEntry::SubBlock:
Teresa Johnson290a8392019-01-11 18:31:57 +00005990 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
5991 Expected<bool> EnableSplitLTOUnit =
5992 getEnableSplitLTOUnitFlag(Stream, Entry.ID);
5993 if (!EnableSplitLTOUnit)
5994 return EnableSplitLTOUnit.takeError();
5995 return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true,
5996 *EnableSplitLTOUnit};
5997 }
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00005998
Teresa Johnson290a8392019-01-11 18:31:57 +00005999 if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
6000 Expected<bool> EnableSplitLTOUnit =
6001 getEnableSplitLTOUnitFlag(Stream, Entry.ID);
6002 if (!EnableSplitLTOUnit)
6003 return EnableSplitLTOUnit.takeError();
6004 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true,
6005 *EnableSplitLTOUnit};
6006 }
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00006007
6008 // Ignore other sub-blocks.
6009 if (Stream.SkipBlock())
6010 return error("Malformed block");
6011 continue;
6012
6013 case BitstreamEntry::Record:
6014 Stream.skipRecord(Entry.ID);
6015 continue;
6016 }
6017 }
6018}
6019
6020static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
Peter Collingbourne7a748032016-11-16 21:44:45 +00006021 Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
6022 if (!MsOrErr)
6023 return MsOrErr.takeError();
6024
6025 if (MsOrErr->size() != 1)
6026 return error("Expected a single module");
6027
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00006028 return (*MsOrErr)[0];
6029}
6030
6031Expected<std::unique_ptr<Module>>
Teresa Johnsona61f5e32016-12-16 21:25:01 +00006032llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
6033 bool ShouldLazyLoadMetadata, bool IsImporting) {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00006034 Expected<BitcodeModule> BM = getSingleModule(Buffer);
6035 if (!BM)
6036 return BM.takeError();
6037
Teresa Johnsona61f5e32016-12-16 21:25:01 +00006038 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006039}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006040
Teresa Johnsona61f5e32016-12-16 21:25:01 +00006041Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
6042 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
6043 bool ShouldLazyLoadMetadata, bool IsImporting) {
6044 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
6045 IsImporting);
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +00006046 if (MOrErr)
6047 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
6048 return MOrErr;
6049}
6050
Peter Collingbourne7a748032016-11-16 21:44:45 +00006051Expected<std::unique_ptr<Module>>
6052BitcodeModule::parseModule(LLVMContext &Context) {
Teresa Johnsona61f5e32016-12-16 21:25:01 +00006053 return getModuleImpl(Context, true, false, false);
Chad Rosierca2567b2011-12-07 21:44:12 +00006054 // TODO: Restore the use-lists to the in-memory state when the bitcode was
6055 // written. We must defer until the Module has been fully materialized.
Chris Lattner6694f602007-04-29 07:54:31 +00006056}
Bill Wendling0198ce02010-10-06 01:22:42 +00006057
Peter Collingbourne7a748032016-11-16 21:44:45 +00006058Expected<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
6059 LLVMContext &Context) {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00006060 Expected<BitcodeModule> BM = getSingleModule(Buffer);
6061 if (!BM)
6062 return BM.takeError();
Peter Collingbourne7a748032016-11-16 21:44:45 +00006063
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00006064 return BM->parseModule(Context);
Peter Collingbourne7a748032016-11-16 21:44:45 +00006065}
6066
Peter Collingbournecd513a42016-11-11 19:50:24 +00006067Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
6068 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
Peter Collingbournec0032b72016-11-11 19:50:10 +00006069 if (!StreamOrErr)
Peter Collingbournecd513a42016-11-11 19:50:24 +00006070 return StreamOrErr.takeError();
Peter Collingbournec0032b72016-11-11 19:50:10 +00006071
Peter Collingbournecd513a42016-11-11 19:50:24 +00006072 return readTriple(*StreamOrErr);
Bill Wendling0198ce02010-10-06 01:22:42 +00006073}
Teresa Johnson403a7872015-10-04 14:33:43 +00006074
Peter Collingbournecd513a42016-11-11 19:50:24 +00006075Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
6076 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
Peter Collingbournec0032b72016-11-11 19:50:10 +00006077 if (!StreamOrErr)
Peter Collingbournecd513a42016-11-11 19:50:24 +00006078 return StreamOrErr.takeError();
Peter Collingbournec0032b72016-11-11 19:50:10 +00006079
Peter Collingbournecd513a42016-11-11 19:50:24 +00006080 return hasObjCCategory(*StreamOrErr);
Mehdi Aminie75aa6f2016-07-11 23:10:18 +00006081}
6082
Peter Collingbournecd513a42016-11-11 19:50:24 +00006083Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
6084 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
Peter Collingbournec0032b72016-11-11 19:50:10 +00006085 if (!StreamOrErr)
Peter Collingbournecd513a42016-11-11 19:50:24 +00006086 return StreamOrErr.takeError();
6087
6088 return readIdentificationCode(*StreamOrErr);
Mehdi Amini3383ccc2015-11-09 02:46:41 +00006089}
6090
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00006091Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
6092 ModuleSummaryIndex &CombinedIndex,
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00006093 uint64_t ModuleId) {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00006094 Expected<BitcodeModule> BM = getSingleModule(Buffer);
6095 if (!BM)
6096 return BM.takeError();
6097
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00006098 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
Peter Collingbourne74d22dd2017-05-01 22:04:36 +00006099}
6100
Peter Collingbourne6de481a2016-11-11 19:50:39 +00006101Expected<std::unique_ptr<ModuleSummaryIndex>>
6102llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00006103 Expected<BitcodeModule> BM = getSingleModule(Buffer);
6104 if (!BM)
6105 return BM.takeError();
Peter Collingbournec0032b72016-11-11 19:50:10 +00006106
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00006107 return BM->getSummary();
Teresa Johnson403a7872015-10-04 14:33:43 +00006108}
6109
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00006110Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
Peter Collingbournea46ec9f2016-12-01 06:00:53 +00006111 Expected<BitcodeModule> BM = getSingleModule(Buffer);
6112 if (!BM)
6113 return BM.takeError();
Teresa Johnson403a7872015-10-04 14:33:43 +00006114
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00006115 return BM->getLTOInfo();
Teresa Johnson403a7872015-10-04 14:33:43 +00006116}
Peter Collingbournec15d60b2017-05-01 20:42:32 +00006117
6118Expected<std::unique_ptr<ModuleSummaryIndex>>
Teresa Johnson4cd12ce2017-05-12 19:32:11 +00006119llvm::getModuleSummaryIndexForFile(StringRef Path,
6120 bool IgnoreEmptyThinLTOIndexFile) {
Peter Collingbournec15d60b2017-05-01 20:42:32 +00006121 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6122 MemoryBuffer::getFileOrSTDIN(Path);
6123 if (!FileOrErr)
6124 return errorCodeToError(FileOrErr.getError());
6125 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
6126 return nullptr;
6127 return getModuleSummaryIndex(**FileOrErr);
6128}